forked from DeusData/codebase-memory-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlite_writer.c
More file actions
1956 lines (1764 loc) · 76.4 KB
/
sqlite_writer.c
File metadata and controls
1956 lines (1764 loc) · 76.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// sqlite_writer.c — Direct SQLite page writer.
// Constructs a valid .db file from sorted in-memory data without using
// the SQL parser, INSERT statements, or B-tree rebalancing.
//
// SQLite file format reference: https://www.sqlite.org/fileformat2.html
//
// Key invariants:
// - Page size: 4096 bytes
// - Page 1 has a 100-byte database header before the B-tree header
// - Leaf table B-tree pages: flag 0x0D
// - Interior table B-tree pages: flag 0x05
// - Leaf index B-tree pages: flag 0x0A
// - Interior index B-tree pages: flag 0x02
// - Records: header (varint count + serial types) + body (column values)
// - Varints: 1-9 bytes, big-endian, MSB continuation
#include "sqlite_writer.h"
#include "foundation/compat_thread.h"
#include <stddef.h> // NULL
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#define PAGE_SIZE 65536
#define SCHEMA_FORMAT 4
#define FILE_FORMAT 1
#define SQLITE_VERSION 3046000 // 3.46.0
// Varint encoding constants.
#define VARINT_MASK 0x7f
#define VARINT_CONTINUE 0x80
#define BYTE_MASK 0xff
// SQLite text serial type offset: serial_type = len*2 + TEXT_SERIAL_BASE.
#define TEXT_SERIAL_BASE 13
// SQLite integer storage range limits.
#define INT8_MAX_VAL 127
#define INT16_MAX_VAL 32767
#define INT24_MIN_VAL (-8388608)
#define INT24_MAX_VAL 8388607
#define INT32_MIN_VAL (-2147483648LL)
#define INT32_MAX_VAL 2147483647LL
#define INT48_MIN_VAL (-140737488355328LL)
#define INT48_MAX_VAL 140737488355327LL
// SQLite B-tree page type flags.
#define BTREE_LEAF_TABLE 0x0D
#define BTREE_INTERIOR_TABLE 0x05
#define BTREE_LEAF_INDEX 0x0A
#define BTREE_INTERIOR_INDEX 0x02
// SQLite 100-byte database header field offsets.
#define HDR_OFF_PAGE_SIZE 16
#define HDR_OFF_WRITE_VERSION 18
#define HDR_OFF_READ_VERSION 19
#define HDR_OFF_RESERVED 20
#define HDR_OFF_MAX_EMBED_FRAC 21
#define HDR_OFF_MIN_EMBED_FRAC 22
#define HDR_OFF_LEAF_FRAC 23
#define HDR_OFF_FILE_CHANGE 24
#define HDR_OFF_DB_SIZE 28
#define HDR_OFF_FREELIST_TRUNK 32
#define HDR_OFF_FREELIST_COUNT 36
#define HDR_OFF_SCHEMA_COOKIE 40
#define HDR_OFF_SCHEMA_FORMAT 44
#define HDR_OFF_DEFAULT_CACHE 48
#define HDR_OFF_AUTOVAC_TOP 52
#define HDR_OFF_TEXT_ENCODING 56
#define HDR_OFF_USER_VERSION 60
#define HDR_OFF_INCR_VACUUM 64
#define HDR_OFF_APP_ID 68
#define HDR_OFF_VERSION_VALID 92
#define HDR_OFF_SQLITE_VERSION 96
// --- Varint encoding ---
static int put_varint(uint8_t *buf, int64_t value) {
uint64_t v = (uint64_t)value;
if (v <= VARINT_MASK) {
buf[0] = (uint8_t)v;
return 1;
}
// Encode in big-endian with MSB continuation bits
uint8_t tmp[10];
int n = 0;
while (v > VARINT_MASK) {
tmp[n++] = (uint8_t)(v & VARINT_MASK);
v >>= 7;
}
tmp[n++] = (uint8_t)v;
// Reverse into output with continuation bits
for (int i = 0; i < n; i++) {
buf[i] = tmp[n - 1 - i];
if (i < n - 1) {
buf[i] |= VARINT_CONTINUE;
}
}
return n;
}
static int varint_len(int64_t value) {
uint64_t v = (uint64_t)value;
int n = 1;
while (v > VARINT_MASK) {
v >>= 7;
n++;
}
return n;
}
// SQLite serial type for a TEXT value
static int64_t text_serial_type(int len) {
return (len * 2) + TEXT_SERIAL_BASE;
}
// SQLite serial type for an integer value
static int64_t int_serial_type(int64_t val) {
if (val == 0) {
return 8; // integer value 0
}
if (val == 1) {
return 9; // integer value 1
}
if (val >= -INT8_MAX_VAL - 1 && val <= INT8_MAX_VAL) {
return 1; // 1 byte
}
if (val >= -INT16_MAX_VAL - 1 && val <= INT16_MAX_VAL) {
return 2; // 2 bytes
}
if (val >= INT24_MIN_VAL && val <= INT24_MAX_VAL) {
return 3; // 3 bytes
}
if (val >= INT32_MIN_VAL && val <= INT32_MAX_VAL) {
return 4; // 4 bytes
}
if (val >= INT48_MIN_VAL && val <= INT48_MAX_VAL) {
return 5; // 6 bytes
}
return 6; // 8 bytes
}
// Bytes needed to store an integer of given serial type
static int int_storage_bytes(int serial_type) {
switch (serial_type) {
case 0:
return 0; // NULL
case 1:
return 1;
case 2:
return 2;
case 3:
return 3;
case 4:
return 4;
case 5:
return 6;
case 6:
return 8;
case 8: // integer 0
case 9: // integer 1
default:
return 0;
}
}
// Write integer in big-endian for given byte count
// NOLINTNEXTLINE(bugprone-easily-swappable-parameters)
static void put_int_be(uint8_t *buf, int64_t val, int nbytes) {
for (int i = nbytes - 1; i >= 0; i--) {
buf[i] = (uint8_t)(val & BYTE_MASK);
val >>= 8; // NOLINT(readability-magic-numbers) — standard byte shift
}
}
// Write a 2-byte big-endian value
static void put_u16(uint8_t *buf, uint16_t val) {
buf[0] = (uint8_t)(val >> 8);
buf[1] = (uint8_t)(val & BYTE_MASK);
}
// Write a 4-byte big-endian value
static void put_u32(uint8_t *buf, uint32_t val) {
buf[0] = (uint8_t)(val >> 24); // NOLINT(readability-magic-numbers) — standard byte shift
buf[1] = (uint8_t)(val >> 16); // NOLINT(readability-magic-numbers) — standard byte shift
buf[2] = (uint8_t)(val >> 8); // NOLINT(readability-magic-numbers) — standard byte shift
buf[3] = (uint8_t)(val & BYTE_MASK);
}
// --- Dynamic buffer ---
typedef struct {
uint8_t *data;
int len;
int cap;
} DynBuf;
static void dynbuf_init(DynBuf *b) {
b->data = NULL;
b->len = 0;
b->cap = 0;
}
static bool dynbuf_ensure(DynBuf *b, int needed) {
if (b->len + needed <= b->cap) {
return true;
}
int newcap = b->cap == 0 ? 4096 : b->cap;
while (newcap < b->len + needed) {
newcap *= 2;
}
uint8_t *p = (uint8_t *)realloc(b->data, newcap);
if (!p) {
// NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling,cert-err33-c)
fprintf(stderr, "cbm_write_db: dynbuf realloc failed size=%d\n", newcap);
return false;
}
b->data = p;
b->cap = newcap;
return true;
}
static bool dynbuf_append(DynBuf *b, const void *data, int len) {
if (len <= 0) {
return true;
}
if (!data) {
return false;
}
if (!dynbuf_ensure(b, len)) {
return false;
}
memcpy(b->data + b->len, data, len);
b->len += len;
return true;
}
static void dynbuf_free(DynBuf *b) {
free(b->data);
b->data = NULL;
b->len = b->cap = 0;
}
// --- Record builder ---
// Builds a SQLite record: header (header_len varint + serial types) + body (values)
typedef struct {
DynBuf header; // serial type varints
DynBuf body; // column values
} RecordBuilder;
static void rec_init(RecordBuilder *r) {
dynbuf_init(&r->header);
dynbuf_init(&r->body);
}
static void rec_free(RecordBuilder *r) {
dynbuf_free(&r->header);
dynbuf_free(&r->body);
}
static void rec_add_null(RecordBuilder *r) {
uint8_t v[1] = {0};
dynbuf_append(&r->header, v, 1);
}
static void rec_add_int(RecordBuilder *r, int64_t val) {
int64_t st = int_serial_type(val);
uint8_t vbuf[9];
int vlen = put_varint(vbuf, st);
dynbuf_append(&r->header, vbuf, vlen);
int nbytes = int_storage_bytes((int)st);
if (nbytes > 0) {
uint8_t ibuf[8];
put_int_be(ibuf, val, nbytes);
dynbuf_append(&r->body, ibuf, nbytes);
}
}
static void rec_add_text(RecordBuilder *r, const char *s) {
int slen = s ? (int)strlen(s) : 0;
int64_t st = text_serial_type(slen);
uint8_t vbuf[9];
int vlen = put_varint(vbuf, st);
dynbuf_append(&r->header, vbuf, vlen);
if (slen > 0) {
dynbuf_append(&r->body, s, slen);
}
}
// Finalize: returns the complete record bytes (header_len + header + body).
// Caller must free the returned buffer.
static uint8_t *rec_finalize(RecordBuilder *r, int *out_len) {
*out_len = 0;
int header_content_len = r->header.len;
int header_len_varint_len = varint_len(header_content_len + varint_len(header_content_len));
// The header size varint includes itself, so we may need to iterate
int total_header = header_len_varint_len + header_content_len;
// Check if the header_len varint changes size when it includes itself
int recalc = varint_len(total_header);
if (recalc != header_len_varint_len) {
header_len_varint_len = recalc;
total_header = header_len_varint_len + header_content_len;
}
int total = total_header + r->body.len;
uint8_t *buf = (uint8_t *)malloc(total);
if (!buf) {
return NULL;
}
int pos = put_varint(buf, total_header);
memcpy(buf + pos, r->header.data, header_content_len);
pos += header_content_len;
memcpy(buf + pos, r->body.data, r->body.len);
*out_len = total;
return buf;
}
// --- Page builder ---
// Accumulates cells (records) into B-tree leaf pages.
typedef struct {
uint32_t page_num; // page number of this page (1-based)
int64_t max_key; // max rowid on this page (table B-trees)
uint8_t *sep_cell; // separator cell content for index interior pages (owned, NULL for table)
int sep_cell_len;
} PageRef;
typedef struct {
FILE *fp;
uint32_t next_page; // next page number to allocate
int page1_offset; // 100 for page 1, 0 for others
bool is_index; // true for index B-trees
// Current leaf page being built
uint8_t page[PAGE_SIZE];
int cell_count;
int content_offset; // where cell content starts (grows down from page end)
int ptr_offset; // where cell pointers are written (grows up from header)
// Completed leaf pages for building interior nodes
PageRef *leaves;
int leaf_count;
int leaf_cap;
} PageBuilder;
static void pb_init(PageBuilder *pb, FILE *fp, uint32_t start_page, bool is_index) {
pb->fp = fp;
pb->next_page = start_page;
pb->is_index = is_index;
pb->cell_count = 0;
pb->content_offset = PAGE_SIZE;
pb->page1_offset = (start_page == 1) ? 100 : 0;
// Header: flag(1) + freeblock(2) + cell_count(2) + content_start(2) + fragmented(1) = 8
pb->ptr_offset = pb->page1_offset + 8;
memset(pb->page, 0, PAGE_SIZE);
pb->leaves = NULL;
pb->leaf_count = 0;
pb->leaf_cap = 0;
}
static void pb_free(PageBuilder *pb) {
if (pb->leaves) {
for (int i = 0; i < pb->leaf_count; i++) {
free(pb->leaves[i].sep_cell);
}
free(pb->leaves);
}
}
// Flush current leaf page to file
static void pb_flush_leaf(PageBuilder *pb) {
if (pb->cell_count == 0) {
return;
}
int hdr = pb->page1_offset;
// Write leaf page header
// NOLINTNEXTLINE(readability-implicit-bool-conversion)
pb->page[hdr + 0] = pb->is_index ? BTREE_LEAF_INDEX : BTREE_LEAF_TABLE; // leaf flag
put_u16(pb->page + hdr + 1, 0); // first freeblock
put_u16(pb->page + hdr + 3, (uint16_t)pb->cell_count);
put_u16(pb->page + hdr + 5, (uint16_t)pb->content_offset);
pb->page[hdr + 7] = 0; // fragmented free bytes
// Write page to file
uint32_t page_num = pb->next_page;
long offset = (long)(page_num - 1) * PAGE_SIZE;
// NOLINTNEXTLINE(cert-err33-c) — best-effort page write, errors detected at fclose
fseek(pb->fp, offset, SEEK_SET);
// NOLINTNEXTLINE(cert-err33-c) — best-effort page write, errors detected at fclose
fwrite(pb->page, 1, PAGE_SIZE, pb->fp);
// Record this leaf for interior page building
if (pb->leaf_count >= pb->leaf_cap) {
pb->leaf_cap = pb->leaf_cap == 0 ? 256 : pb->leaf_cap * 2;
void *tmp = realloc(pb->leaves, (size_t)pb->leaf_cap * sizeof(PageRef));
if (!tmp) {
free(pb->leaves);
pb->leaves = NULL;
return;
}
pb->leaves = (PageRef *)tmp;
}
pb->leaves[pb->leaf_count].page_num = page_num;
// max_key is set by caller before flush
pb->leaf_count++;
// Reset for next page
pb->next_page++;
pb->cell_count = 0;
pb->content_offset = PAGE_SIZE;
pb->page1_offset = 0; // only page 1 has the 100-byte header
pb->ptr_offset = 8; // standard B-tree header size for non-page-1
memset(pb->page, 0, PAGE_SIZE);
}
// Check if a cell of given size fits in the current page
static bool pb_cell_fits(PageBuilder *pb, int cell_len) {
// Cell pointer (2 bytes) + cell content
int available = pb->content_offset - pb->ptr_offset - 2;
return cell_len <= available;
}
// Add a cell to the current leaf page.
// For table leaves: varint(payload_len) + varint(rowid) + payload
// For index leaves: varint(payload_len) + payload
static void pb_add_cell(PageBuilder *pb, const uint8_t *cell, int cell_len) {
// Write cell content (grows down)
pb->content_offset -= cell_len;
memcpy(pb->page + pb->content_offset, cell, cell_len);
// Write cell pointer (grows up)
put_u16(pb->page + pb->ptr_offset, (uint16_t)pb->content_offset);
pb->ptr_offset += 2;
pb->cell_count++;
}
// Build interior pages from child page references.
// Returns the root page number.
//
// SQLite interior page structure:
// - Header has right-child pointer (the last child page)
// - Each cell contains: child_page(4) + key
// - For N children, there are N-1 cells (children[0..N-2] get cells,
// children[N-1] becomes the right-child in the header)
// - Cell[j] = {left_child: children[j].page, key: children[j].max_key/sep_cell}
// - Lookup: X ≤ K0 → cell[0].left_child, K0 < X ≤ K1 → cell[1].left_child, etc.
// - Table keys: varint(rowid)
// - Index keys: varint(payload_len) + payload (full index record)
static uint32_t pb_build_interior(PageBuilder *pb, bool is_index) {
if (!pb->leaves) {
return 0;
}
if (pb->leaf_count <= 1) {
return pb->leaves[0].page_num;
}
PageRef *children = pb->leaves;
int child_count = pb->leaf_count;
while (child_count > 1 && children) {
PageRef *parents = NULL;
int parent_count = 0;
int parent_cap = 0;
int i = 0;
while (i < child_count) {
// Start a new interior page
uint8_t page[PAGE_SIZE];
memset(page, 0, PAGE_SIZE);
int cell_count = 0;
int content_offset = PAGE_SIZE;
// Interior header:
// flag(1)+freeblock(2)+cell_count(2)+content_start(2)+frag(1)+right_child(4) = 12
int ptr_offset = 12;
// Add cells for children[i..] until page fills or children exhausted.
// Each child gets a cell EXCEPT the last one (which becomes right_child).
while (i < child_count - 1) {
// Build cell: child_page(4) + key for children[i]
uint8_t *cell_data = NULL;
int clen;
uint8_t tbuf[20];
bool heap_cell = false;
if (!is_index) {
put_u32(tbuf, children[i].page_num);
clen = 4 + put_varint(tbuf + 4, children[i].max_key);
cell_data = tbuf;
} else {
clen = 4 + children[i].sep_cell_len;
cell_data = (uint8_t *)malloc(clen);
heap_cell = true;
put_u32(cell_data, children[i].page_num);
memcpy(cell_data + 4, children[i].sep_cell, children[i].sep_cell_len);
}
int available = content_offset - ptr_offset - 2;
if (clen > available && cell_count > 0) {
if (heap_cell) {
free(cell_data);
}
break; // page full, flush with what we have
}
content_offset -= clen;
memcpy(page + content_offset, cell_data, clen);
put_u16(page + ptr_offset, (uint16_t)content_offset);
ptr_offset += 2;
cell_count++;
if (heap_cell) {
free(cell_data);
}
i++;
}
// Determine right-child: if we consumed all children, it's the last one.
// If we stopped early due to page full, right-child is children[i-1]
// (the last child we added a cell for)... No: cells were added for
// children[page_start..i-1], so right-child = children[i].
// But if cell_count == 0 and we didn't add anything, we have a problem.
// That can happen only if the first cell doesn't fit — shouldn't happen
// for typical cell sizes on a 4096 page.
uint32_t right_child_page;
int right_child_idx;
if (i < child_count - 1) {
// Page full before reaching the end. Cells cover children[page_start..i-1].
// Right-child = children[i] (first child NOT given a cell on this page).
// But wait, we need right-child to be the last child whose keys are > last cell's
// key. Actually: cells[page_start..i-1] have keys K_{page_start}..K_{i-1}.
// Right-child should contain keys > K_{i-1}, which is children[i].
// But children[i] hasn't been processed yet — it will be on the next interior page.
// The right-child for THIS page should be children[i], and on the NEXT page,
// children[i] will get a cell too. But that would mean children[i] is both
// the right-child of this page AND has a cell on the next page.
// That's wrong — each child should appear exactly once.
//
// Correct approach: cells for children[page_start..i-1], right-child = children[i].
// Then next page starts at i+1.
right_child_page = children[i].page_num;
right_child_idx = i;
i++; // skip the right-child for the next page's iteration
} else {
// Reached the end normally. Last child = right-child.
right_child_page = children[child_count - 1].page_num;
right_child_idx = child_count - 1;
i = child_count; // exit outer loop
}
// Write the interior page
uint32_t pnum = pb->next_page++;
// NOLINTNEXTLINE(readability-implicit-bool-conversion)
page[0] = is_index ? 0x02 : 0x05;
put_u16(page + 1, 0);
put_u16(page + 3, (uint16_t)cell_count);
put_u16(page + 5, (uint16_t)content_offset);
page[7] = 0;
put_u32(page + 8, right_child_page);
// NOLINTNEXTLINE(cert-err33-c) — best-effort page write, errors detected at fclose
fseek(pb->fp, (long)(pnum - 1) * PAGE_SIZE, SEEK_SET);
// NOLINTNEXTLINE(cert-err33-c) — best-effort page write, errors detected at fclose
fwrite(page, 1, PAGE_SIZE, pb->fp);
// Record this interior page as a parent for the next level
if (parent_count >= parent_cap) {
parent_cap = parent_cap == 0 ? 64 : parent_cap * 2;
PageRef *tmp = (PageRef *)realloc(parents, parent_cap * sizeof(PageRef));
if (!tmp) {
free(parents);
parents = NULL;
break;
}
parents = tmp;
}
parents[parent_count].page_num = pnum;
parents[parent_count].max_key = children[right_child_idx].max_key;
// For multi-level index trees, copy the separator from the rightmost child
if (is_index && children[right_child_idx].sep_cell) {
int slen = children[right_child_idx].sep_cell_len;
parents[parent_count].sep_cell = (uint8_t *)malloc(slen);
memcpy(parents[parent_count].sep_cell, children[right_child_idx].sep_cell, slen);
parents[parent_count].sep_cell_len = slen;
} else {
parents[parent_count].sep_cell = NULL;
parents[parent_count].sep_cell_len = 0;
}
parent_count++;
}
if (children != pb->leaves) {
for (int j = 0; j < child_count; j++) {
free(children[j].sep_cell);
}
free(children);
}
children = parents;
child_count = parent_count;
}
uint32_t root = children ? children[0].page_num : 0;
if (children != pb->leaves) {
for (int j = 0; j < child_count; j++) {
free(children[j].sep_cell);
}
free(children);
}
return root;
}
// --- Table record builders ---
// Build a nodes table record: (id, project, label, name, qualified_name, file_path, start_line,
// end_line, properties)
static uint8_t *build_node_record(const CBMDumpNode *n, int *out_len) {
RecordBuilder r;
rec_init(&r);
rec_add_int(&r, n->id);
rec_add_text(&r, n->project);
rec_add_text(&r, n->label);
rec_add_text(&r, n->name);
rec_add_text(&r, n->qualified_name);
rec_add_text(&r, n->file_path ? n->file_path : "");
rec_add_int(&r, n->start_line);
rec_add_int(&r, n->end_line);
rec_add_text(&r, n->properties ? n->properties : "{}");
uint8_t *data = rec_finalize(&r, out_len);
rec_free(&r);
return data;
}
// Build an edges table record: (id, project, source_id, target_id, type, properties)
// url_path_gen is a VIRTUAL generated column — NOT stored in the record.
static uint8_t *build_edge_record(const CBMDumpEdge *e, int *out_len) {
RecordBuilder r;
rec_init(&r);
rec_add_int(&r, e->id);
rec_add_text(&r, e->project);
rec_add_int(&r, e->source_id);
rec_add_int(&r, e->target_id);
rec_add_text(&r, e->type);
rec_add_text(&r, e->properties ? e->properties : "{}");
uint8_t *data = rec_finalize(&r, out_len);
rec_free(&r);
return data;
}
// Build a projects table record: (name, indexed_at, root_path)
static uint8_t *build_project_record(const char *name, const char *indexed_at,
const char *root_path, int *out_len) {
RecordBuilder r;
rec_init(&r);
rec_add_text(&r, name);
rec_add_text(&r, indexed_at);
rec_add_text(&r, root_path);
uint8_t *data = rec_finalize(&r, out_len);
rec_free(&r);
return data;
}
// --- Table cell builder ---
// Table leaf cell: varint(payload_len) + varint(rowid) + payload
static uint8_t *build_table_cell(int64_t rowid, const uint8_t *payload, int payload_len,
int *out_cell_len) {
int rl = varint_len(payload_len);
int kl = varint_len(rowid);
int total = rl + kl + payload_len;
uint8_t *cell = (uint8_t *)malloc(total);
if (!cell) {
return NULL;
}
int pos = 0;
pos += put_varint(cell + pos, payload_len);
pos += put_varint(cell + pos, rowid);
memcpy(cell + pos, payload, payload_len);
*out_cell_len = pos + payload_len;
return cell;
}
// Build a table leaf cell with overflow: stores only the first local_len bytes of
// payload inline, followed by a 4-byte overflow page number.
// total_payload_len is the FULL original payload length (written as the payload-size
// varint so SQLite knows the real record size).
static uint8_t *build_table_cell_overflow(int64_t rowid, const uint8_t *payload,
int total_payload_len, int local_len,
uint32_t overflow_page, int *out_cell_len) {
int rl = varint_len(total_payload_len);
int kl = varint_len(rowid);
// cell = varint(total_payload_len) + varint(rowid) + payload[0..local_len) + uint32(overflow)
int total = rl + kl + local_len + 4;
uint8_t *cell = (uint8_t *)malloc(total);
if (!cell) {
return NULL;
}
int pos = 0;
pos += put_varint(cell + pos, total_payload_len);
pos += put_varint(cell + pos, rowid);
memcpy(cell + pos, payload, local_len);
pos += local_len;
put_u32(cell + pos, overflow_page);
pos += 4;
*out_cell_len = pos;
return cell;
}
// --- Overflow page writer ---
// Writes overflow pages for payload bytes that exceed local storage.
// Returns the first overflow page number (embedded in the leaf cell).
// Each overflow page: 4-byte next-page pointer + up to (PAGE_SIZE-4) bytes of data.
// NOLINTNEXTLINE(bugprone-easily-swappable-parameters)
static uint32_t write_overflow_pages(FILE *fp, uint32_t *next_page, const uint8_t *data,
int data_len) {
int per_page = PAGE_SIZE - 4; // 4 bytes reserved for next-page pointer
uint32_t first_page = 0;
long prev_next_ptr_offset = -1; // file offset of the next-page field in the previous overflow page
int offset = 0;
while (offset < data_len) {
uint32_t pnum = (*next_page)++;
if (first_page == 0) {
first_page = pnum;
}
// Backpatch previous overflow page's next-page pointer
if (prev_next_ptr_offset >= 0) {
uint8_t ptr[4];
put_u32(ptr, pnum);
// NOLINTNEXTLINE(cert-err33-c)
fseek(fp, prev_next_ptr_offset, SEEK_SET);
// NOLINTNEXTLINE(cert-err33-c)
fwrite(ptr, 1, 4, fp);
}
int chunk = data_len - offset;
if (chunk > per_page) {
chunk = per_page;
}
uint8_t page[PAGE_SIZE];
memset(page, 0, PAGE_SIZE);
put_u32(page, 0); // next-page pointer — 0 for now, backpatched on next iteration
memcpy(page + 4, data + offset, chunk);
long page_offset = (long)(pnum - 1) * PAGE_SIZE;
prev_next_ptr_offset = page_offset; // next-page pointer is at byte 0 of this page
// NOLINTNEXTLINE(cert-err33-c)
fseek(fp, page_offset, SEEK_SET);
// NOLINTNEXTLINE(cert-err33-c)
fwrite(page, 1, PAGE_SIZE, fp);
offset += chunk;
}
return first_page;
}
// --- Index record builders ---
// Build an index entry for a 2-column TEXT index (project, col) + rowid.
// Index records: varint(payload_len) + payload(record of indexed cols + rowid)
static uint8_t *build_index_entry_2text_rowid(const char *col1, const char *col2, int64_t rowid,
int *out_len) {
// Build the record portion: (col1, col2, rowid)
RecordBuilder r;
rec_init(&r);
rec_add_text(&r, col1);
rec_add_text(&r, col2);
rec_add_int(&r, rowid);
int payload_len = 0;
uint8_t *payload = rec_finalize(&r, &payload_len);
rec_free(&r);
if (!payload) {
*out_len = 0;
return NULL;
}
// Index cell: varint(payload_len) + payload
int vl = varint_len(payload_len);
int total = vl + payload_len;
uint8_t *cell = (uint8_t *)malloc(total);
if (!cell) {
free(payload);
*out_len = 0;
return NULL;
}
int pos = put_varint(cell, payload_len);
memcpy(cell + pos, payload, payload_len);
free(payload);
*out_len = total;
return cell;
}
// Build index entry for (int64, text) + rowid (e.g., idx_edges_source)
static uint8_t *build_index_entry_int_text_rowid(int64_t val, const char *text, int64_t rowid,
int *out_len) {
RecordBuilder r;
rec_init(&r);
rec_add_int(&r, val);
rec_add_text(&r, text);
rec_add_int(&r, rowid);
int payload_len = 0;
uint8_t *payload = rec_finalize(&r, &payload_len);
rec_free(&r);
if (!payload) {
*out_len = 0;
return NULL;
}
int vl = varint_len(payload_len);
int total = vl + payload_len;
uint8_t *cell = (uint8_t *)malloc(total);
if (!cell) {
free(payload);
*out_len = 0;
return NULL;
}
int pos = put_varint(cell, payload_len);
memcpy(cell + pos, payload, payload_len);
free(payload);
*out_len = total;
return cell;
}
// Build index entry for (text, int64, text) + rowid (e.g., idx_edges_target_type)
static uint8_t *build_index_entry_text_int_text_rowid(const char *t1, int64_t val, const char *t2,
int64_t rowid, int *out_len) {
RecordBuilder r;
rec_init(&r);
rec_add_text(&r, t1);
rec_add_int(&r, val);
rec_add_text(&r, t2);
rec_add_int(&r, rowid);
int payload_len = 0;
uint8_t *payload = rec_finalize(&r, &payload_len);
rec_free(&r);
if (!payload) {
*out_len = 0;
return NULL;
}
int vl = varint_len(payload_len);
int total = vl + payload_len;
uint8_t *cell = (uint8_t *)malloc(total);
if (!cell) {
free(payload);
*out_len = 0;
return NULL;
}
int pos = put_varint(cell, payload_len);
memcpy(cell + pos, payload, payload_len);
free(payload);
*out_len = total;
return cell;
}
// Build UNIQUE index entry for (text, text) + rowid (e.g., nodes unique(project, qualified_name))
// Build UNIQUE index entry for (int64, int64, text) + rowid (edges unique(source_id, target_id,
// type))
static uint8_t *build_index_entry_unique_2int_text_rowid(int64_t v1, int64_t v2, const char *text,
int64_t rowid, int *out_len) {
RecordBuilder r;
rec_init(&r);
rec_add_int(&r, v1);
rec_add_int(&r, v2);
rec_add_text(&r, text);
rec_add_int(&r, rowid);
int payload_len = 0;
uint8_t *payload = rec_finalize(&r, &payload_len);
rec_free(&r);
if (!payload) {
*out_len = 0;
return NULL;
}
// NOLINTNEXTLINE(misc-confusable-identifiers) — identifiers are distinct in context
int vl = varint_len(payload_len);
int total = vl + payload_len;
uint8_t *cell = (uint8_t *)malloc(total);
if (!cell) {
free(payload);
*out_len = 0;
return NULL;
}
int pos = put_varint(cell, payload_len);
memcpy(cell + pos, payload, payload_len);
free(payload);
*out_len = total;
return cell;
}
// --- Write a table B-tree from records ---
// Helper: ensure leaf_cap, flush current leaf page with given max_key
static void pb_ensure_leaf_cap(PageBuilder *pb) {
if (pb->leaf_count >= pb->leaf_cap) {
pb->leaf_cap = pb->leaf_cap == 0 ? 256 : pb->leaf_cap * 2;
void *tmp = realloc(pb->leaves, (size_t)pb->leaf_cap * sizeof(PageRef));
if (!tmp) {
free(pb->leaves);
pb->leaves = NULL;
return;
}
pb->leaves = (PageRef *)tmp;
}
}
// SQLite overflow thresholds for leaf table B-tree pages (PAGE_SIZE=65536, reserved=0):
// usable = PAGE_SIZE = 65536
// max_local = usable - 35 = 65501
// min_local = (usable - 12) * 32 / 255 - 23 = 8199 (C integer arithmetic, same as SQLite)
//
// These must match SQLite's btree.c formulas exactly:
// pBt->maxLeaf = usableSize - 35
// pBt->minLeaf = (usableSize-12)*32/255 - 23
#define TABLE_OVERFLOW_MAX_LOCAL 65501
#define TABLE_OVERFLOW_MIN_LOCAL 8199
// Add a table cell to the PageBuilder, flushing leaf pages as needed.
// If the payload exceeds max_local, overflow pages are written and only the
// local portion plus a 4-byte overflow page pointer is stored in the leaf cell.
static void pb_add_table_cell_with_flush(PageBuilder *pb, int64_t rowid, const uint8_t *payload,
// NOLINTNEXTLINE(bugprone-easily-swappable-parameters)
int payload_len, int64_t prev_rowid) {
int cell_len = 0;
uint8_t *cell = NULL;
if (payload_len > TABLE_OVERFLOW_MAX_LOCAL) {
// Compute local_len per SQLite spec §overflow-pages for leaf table cells.
int local_len =
TABLE_OVERFLOW_MIN_LOCAL +
((payload_len - TABLE_OVERFLOW_MIN_LOCAL) % (PAGE_SIZE - 4));
if (local_len > TABLE_OVERFLOW_MAX_LOCAL) {
local_len = TABLE_OVERFLOW_MIN_LOCAL;
}
// Write overflow pages for the bytes that don't fit locally.
uint32_t overflow_page =
write_overflow_pages(pb->fp, &pb->next_page, payload + local_len,
payload_len - local_len);
if (overflow_page == 0) {
return; // overflow write failed
}
cell = build_table_cell_overflow(rowid, payload, payload_len, local_len, overflow_page,
&cell_len);
} else {
cell = build_table_cell(rowid, payload, payload_len, &cell_len);
}
if (!cell) {
return;
}
if (!pb_cell_fits(pb, cell_len) && pb->cell_count > 0) {
pb_ensure_leaf_cap(pb);
if (!pb->leaves) {
free(cell);
return;
}
pb->leaves[pb->leaf_count].max_key = prev_rowid;
pb->leaves[pb->leaf_count].sep_cell = NULL;
pb->leaves[pb->leaf_count].sep_cell_len = 0;
pb_flush_leaf(pb);
}
pb_add_cell(pb, cell, cell_len);
free(cell);
}
// Finalize a table PageBuilder: flush last leaf and build interior pages.
static uint32_t pb_finalize_table(PageBuilder *pb, uint32_t *next_page, int64_t last_rowid) {
if (pb->cell_count > 0) {
pb_ensure_leaf_cap(pb);
if (!pb->leaves) {
pb_free(pb);
return 0;
}
pb->leaves[pb->leaf_count].max_key = last_rowid;
pb->leaves[pb->leaf_count].sep_cell = NULL;
pb->leaves[pb->leaf_count].sep_cell_len = 0;
pb_flush_leaf(pb);
}
*next_page = pb->next_page;
uint32_t root;
if (pb->leaf_count == 1) {
root = pb->leaves[0].page_num;
} else if (pb->leaf_count > 1) {