MCPcopy Create free account
hub / github.com/DeusData/codebase-memory-mcp / write_index_btree

Function write_index_btree

internal/cbm/sqlite_writer.c:1335–1396  ·  view source on GitHub ↗

Write leaf pages for an index, returns root page.

Source from the content-addressed store, hash-verified

1333
1334// Write leaf pages for an index, returns root page.
1335static uint32_t write_index_btree(FILE *fp, uint32_t *next_page, uint8_t **cells, int *cell_lens,
1336 int count) {
1337 if (count == 0) {
1338 return write_empty_index_leaf(fp, next_page);
1339 }
1340
1341 /* Spill oversized index payloads to overflow pages BEFORE page building so
1342 * every cell added below is within the local-payload limit (see
1343 * INDEX_OVERFLOW_MAX_LOCAL). Overflow pages are allocated from *next_page
1344 * ahead of the leaf pages, which is fine — page order is arbitrary. */
1345 for (int i = 0; i < count; i++) {
1346 cells[i] = overflowize_index_cell(fp, next_page, cells[i], &cell_lens[i]);
1347 }
1348
1349 PageBuilder pb;
1350 pb_init(&pb, fp, *next_page, true);
1351
1352 for (int i = 0; i < count; i++) {
1353 if (!pb_cell_fits(&pb, cell_lens[i])) {
1354 if (pb.cell_count > 0) {
1355 if (!pb_promote_and_flush(&pb, cells, cell_lens, i - SKIP_ONE)) {
1356 return 0;
1357 }
1358 }
1359 // After flush, check if the cell still doesn't fit on an empty page.
1360 // Index cells larger than a full page can never be stored; skip them.
1361 if (!pb_cell_fits(&pb, cell_lens[i])) {
1362 (void)fprintf(stderr, "cbm_write_db: index cell oversized, skipped len=%d idx=%d\n",
1363 cell_lens[i], i);
1364 continue;
1365 }
1366 }
1367 pb_add_cell(&pb, cells[i], cell_lens[i]);
1368 }
1369
1370 if (pb.cell_count > 0) {
1371 if (!pb_ensure_leaf_cap(&pb)) {
1372 return 0;
1373 }
1374 pb.leaves[pb.leaf_count].max_key = 0;
1375 int last = count - SKIP_ONE;
1376 pb.leaves[pb.leaf_count].sep_cell = (uint8_t *)malloc(cell_lens[last]);
1377 memcpy(pb.leaves[pb.leaf_count].sep_cell, cells[last], cell_lens[last]);
1378 pb.leaves[pb.leaf_count].sep_cell_len = cell_lens[last];
1379 pb_flush_leaf(&pb);
1380 }
1381
1382 *next_page = pb.next_page;
1383
1384 uint32_t root;
1385 if (!pb.leaves) {
1386 root = 0;
1387 } else if (pb.leaf_count == SKIP_ONE) {
1388 root = pb.leaves[0].page_num;
1389 } else {
1390 root = pb_build_interior(&pb, true);
1391 *next_page = pb.next_page;
1392 }

Callers 3

build_edge_index_sortedFunction · 0.85
build_node_index_sortedFunction · 0.85
write_db_after_nodesFunction · 0.85

Calls 10

write_empty_index_leafFunction · 0.85
overflowize_index_cellFunction · 0.85
pb_initFunction · 0.85
pb_cell_fitsFunction · 0.85
pb_promote_and_flushFunction · 0.85
pb_add_cellFunction · 0.85
pb_ensure_leaf_capFunction · 0.85
pb_flush_leafFunction · 0.85
pb_build_interiorFunction · 0.85
pb_freeFunction · 0.85

Tested by

no test coverage detected