-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsqlite-memory.c
More file actions
1657 lines (1323 loc) · 61 KB
/
sqlite-memory.c
File metadata and controls
1657 lines (1323 loc) · 61 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-memory.c
// sqlitememory
//
// Created by Marco Bambini on 30/01/26.
//
#include <math.h>
#include <float.h>
#include <stdio.h>
#include <ctype.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#ifndef _WIN32
#include <unistd.h>
#endif
#include <stdint.h>
#include <stdbool.h>
#include <stdarg.h>
#include <stddef.h>
#include <time.h>
#include "sqlite-memory.h"
#include "dbmem-utils.h"
#include "dbmem-embed.h"
#include "dbmem-parser.h"
#include "dbmem-search.h"
#ifndef SQLITE_CORE
SQLITE_EXTENSION_INIT1
#endif
// available compilation options
// DBMEM_OMIT_IO // to be used when compiled for WASM
// DBMEM_OMIT_LOCAL_ENGINE // to be used when compiled for WASM or when the local inference engine is not needed
// DBMEM_OMIT_REMOTE_ENGINE // to be used when remote provider should not be used
#define DBMEM_TYPE_VALUE 500
#define DBMEM_LOCAL_PROVIDER "local"
#define DBMEM_SAVEPOINT_NAME "memory_transaction"
#define DBMEM_SETTINGS_KEY_PROVIDER "provider"
#define DBMEM_SETTINGS_KEY_MODEL "model"
#define DBMEM_SETTINGS_KEY_DIMENSION "dimension"
#define DBMEM_SETTINGS_KEY_MAX_TOKENS "max_tokens"
#define DBMEM_SETTINGS_KEY_OVERLAY_TOKENS "overlay_tokens"
#define DBMEM_SETTINGS_KEY_CHARS_PER_TOKENS "chars_per_tokens"
#define DBMEM_SETTINGS_KEY_SAVE_CONTEXT "save_content"
#define DBMEM_SETTINGS_KEY_SKIP_SEMANTIC "skip_semantic"
#define DBMEM_SETTINGS_KEY_SKIP_HTML "skip_html"
#define DBMEM_SETTINGS_KEY_EXTENSIONS "extensions"
#define DBMEM_SETTINGS_KEY_ENGINE_WARMUP "engine_warmup"
#define DBMEM_SETTINGS_KEY_MAX_RESULTS "max_results"
#define DBMEM_SETTINGS_KEY_FTS_ENABLED "fts_enabled"
#define DBMEM_SETTINGS_KEY_VECTOR_WEIGHT "vector_weight"
#define DBMEM_SETTINGS_KEY_TEXT_WEIGHT "text_weight"
#define DBMEM_SETTINGS_KEY_MIN_SCORE "min_score"
#define DBMEM_SETTINGS_KEY_UPDATE_ACCESS "update_access"
#define DBMEM_SETTINGS_KEY_EMBEDDING_CACHE "embedding_cache"
#define DBMEM_SETTINGS_KEY_CACHE_MAX_ENTRIES "cache_max_entries"
#define DBMEM_SETTINGS_KEY_SEARCH_OVERSAMPLE "search_oversample"
// default values from https://docs.openclaw.ai/concepts/memory
#define DEFAULT_CHARS_PER_TOKEN 4 // Approximate number of characters per token (GPT ≈ 4, Claude ≈ 3.5)
#define DEFAULT_MAX_TOKENS 400 // Maximum tokens per chunk
#define DEFAULT_OVERLAY_TOKENS 80 // Token overlap between consecutive chunks
#define DEFAULT_MAX_SNIPPET_CHARS 700 // Maximum characters for search result snippets
#define DEFAULT_MAX_RESULTS 20 // Maximum number of search results
#define DEFAULT_VECTOR_WEIGHT 0.6 // Semantic similarity weight in hybrid search scoring
#define DEFAULT_TEXT_WEIGHT 0.4 // Full-text match weight in hybrid search scoring
#define DEFAULT_MIN_SCORE 0.7 // Minimum score threshold to filter irrelevant results
struct dbmem_context {
// Database and engine
sqlite3 *db; // SQLite database connection
bool is_local; // Flag set based on memory_set_model
dbmem_local_engine_t *l_engine; // Local embedding engine (llama.cpp based)
dbmem_remote_engine_t *r_engine; // Remote embedding engine (vectors.space based)
// Custom embedding provider
dbmem_provider_t custom_provider; // User-registered callbacks
char *custom_provider_name; // Provider name for matching
void *custom_engine; // Opaque engine from custom_provider.init
bool is_custom; // True when custom provider is active
// Provider configuration
char *provider; // Embedding provider: "local" or remote service name
char *model; // Model path (local) or model identifier (remote)
char *api_key; // API key for remote embedding services
char *extensions; // Comma-separated file extensions to process (e.g., "md,txt")
int dimension; // Embedding dimension from provider/model (stored into the database)
// Chunking parameters
size_t max_tokens; // Maximum tokens per chunk
size_t overlay_tokens; // Token overlap between consecutive chunks
size_t chars_per_tokens; // Estimated characters per token (for size calculations)
size_t snippet_max_chars; // Maximum characters for search result snippets
// Processing flags
bool engine_warmup; // Whether engine has been warmed up (GPU shaders compiled)
bool save_content; // Whether to store original content in database
bool skip_semantic; // Skip markdown parsing, treat as raw text
bool skip_html; // Strip HTML tags when parsing markdown
bool perform_fts; // Enable/Disable FTS during search
bool vector_extension_available; // SQLite-vector available and correctly loaded flag
bool sync_extension_available; // SQLite-sync available and correctly loadedflag
bool dimension_saved; // Embedding dimension needs to be automatically serialized
// Settings
int max_results; // Maximum number of results to be returned from a search
double vector_weight; // Weight of the vector results during the merge of the result
double text_weight; // Weight of the FTS results during the merge of the result
double min_score; // Minimum score threshold to filter irrelevant results
bool update_access; // Whether to update last_accessed on search
bool embedding_cache; // Enable/disable embedding cache (default: true)
int cache_max_entries; // Max cache entries (0 = no limit)
int search_oversample; // Search oversampling multiplier (0 = no oversampling)
// Cache
float *cache_buffer; // Reusable buffer for cache hits
int cache_buffer_size; // Allocated size in floats
// Runtime state
int64_t counter; // Chunk counter during file processing
uint64_t hash; // Hash of the current text
const char *context; // Optional context string for current operation
const char *path; // Full path file (optional)
char error_msg[DBMEM_ERRBUF_SIZE]; // Error message buffer
};
static bool fts5_is_available = true;
// MARK: - Settings -
static int dbmem_settings_write (sqlite3 *db, const char *key, const char *text_value, sqlite3_int64 int_value, const sqlite3_value *sql_value, int bind_type) {
static const char *sql = "REPLACE INTO dbmem_settings (key, value) VALUES (?1, ?2);";
sqlite3_stmt *vm = NULL;
int rc = sqlite3_prepare_v2(db, sql, -1, &vm, NULL);
if (rc != SQLITE_OK) goto cleanup;
rc = sqlite3_bind_text(vm, 1, key, -1, NULL);
if (rc != SQLITE_OK) goto cleanup;
switch (bind_type) {
case SQLITE_TEXT: rc = sqlite3_bind_text(vm, 2, text_value, -1, NULL); break;
case SQLITE_INTEGER: rc = sqlite3_bind_int64(vm, 2, int_value); break;
case DBMEM_TYPE_VALUE: rc = sqlite3_bind_value(vm, 2, sql_value); break;
default: rc = SQLITE_MISUSE; goto cleanup;
}
rc = sqlite3_step(vm);
if (rc == SQLITE_DONE) rc = SQLITE_OK;
cleanup:
if (rc != SQLITE_OK) DEBUG_DBMEM("Error in dbmem_settings_write: %s", sqlite3_errmsg(db));
if (vm) sqlite3_finalize(vm);
return rc;
}
static int dbmem_settings_write_text (sqlite3 *db, const char *key, const char *value) {
return dbmem_settings_write(db, key, value, 0, NULL, SQLITE_TEXT);
}
static int dbmem_settings_write_int (sqlite3 *db, const char *key, sqlite3_int64 value) {
return dbmem_settings_write(db, key, NULL, value, NULL, SQLITE_INTEGER);
}
static int dbmem_settings_write_value (sqlite3 *db, const char *key, sqlite3_value *value) {
return dbmem_settings_write(db, key, NULL, 0, value, DBMEM_TYPE_VALUE);
}
static int dbmem_settings_sync (dbmem_context *ctx, const char *key, sqlite3_value *value) {
if (!value) return 0;
if (strcasecmp(key, DBMEM_SETTINGS_KEY_MAX_TOKENS) == 0) {
int n = sqlite3_value_int(value);
if (n > 0) ctx->max_tokens = n;
return 0;
}
if (strcasecmp(key, DBMEM_SETTINGS_KEY_OVERLAY_TOKENS) == 0) {
int n = sqlite3_value_int(value);
if (n > 0) ctx->overlay_tokens = n;
return 0;
}
if (strcasecmp(key, DBMEM_SETTINGS_KEY_CHARS_PER_TOKENS) == 0) {
int n = sqlite3_value_int(value);
if (n > 0) ctx->chars_per_tokens = n;
return 0;
}
if (strcasecmp(key, DBMEM_SETTINGS_KEY_DIMENSION) == 0) {
int n = sqlite3_value_int(value);
if (n > 0) {ctx->dimension = n; ctx->dimension_saved = true;}
return 0;
}
if (strcasecmp(key, DBMEM_SETTINGS_KEY_SAVE_CONTEXT) == 0) {
int n = sqlite3_value_int(value);
ctx->save_content = (n > 0) ? 1 : 0;
return 0;
}
if (strcasecmp(key, DBMEM_SETTINGS_KEY_SKIP_SEMANTIC) == 0) {
int n = sqlite3_value_int(value);
ctx->skip_semantic = (n > 0) ? 1 : 0;
return 0;
}
if (strcasecmp(key, DBMEM_SETTINGS_KEY_SKIP_HTML) == 0) {
int n = sqlite3_value_int(value);
ctx->skip_html = (n > 0) ? 1 : 0;
return 0;
}
if (strcasecmp(key, DBMEM_SETTINGS_KEY_ENGINE_WARMUP) == 0) {
int n = sqlite3_value_int(value);
ctx->engine_warmup = (n > 0) ? 1 : 0;
return 0;
}
if (strcasecmp(key, DBMEM_SETTINGS_KEY_FTS_ENABLED) == 0) {
int n = sqlite3_value_int(value);
ctx->perform_fts = (n > 0) ? 1 : 0;
return 0;
}
if (strcasecmp(key, DBMEM_SETTINGS_KEY_MAX_RESULTS) == 0) {
int n = sqlite3_value_int(value);
if (n > 0) ctx->max_results = n;
return 0;
}
if (strcasecmp(key, DBMEM_SETTINGS_KEY_VECTOR_WEIGHT) == 0) {
double n = sqlite3_value_double(value);
if (n > 0) ctx->vector_weight = n;
return 0;
}
if (strcasecmp(key, DBMEM_SETTINGS_KEY_TEXT_WEIGHT) == 0) {
double n = sqlite3_value_double(value);
if (n > 0) ctx->text_weight = n;
return 0;
}
if (strcasecmp(key, DBMEM_SETTINGS_KEY_MIN_SCORE) == 0) {
double n = sqlite3_value_double(value);
if (n > 0) ctx->min_score = n;
return 0;
}
if (strcasecmp(key, DBMEM_SETTINGS_KEY_UPDATE_ACCESS) == 0) {
int n = sqlite3_value_int(value);
ctx->update_access = (n > 0) ? 1 : 0;
return 0;
}
if (strcasecmp(key, DBMEM_SETTINGS_KEY_EMBEDDING_CACHE) == 0) {
int n = sqlite3_value_int(value);
ctx->embedding_cache = (n > 0) ? 1 : 0;
return 0;
}
if (strcasecmp(key, DBMEM_SETTINGS_KEY_CACHE_MAX_ENTRIES) == 0) {
int n = sqlite3_value_int(value);
if (n >= 0) ctx->cache_max_entries = n;
return 0;
}
if (strcasecmp(key, DBMEM_SETTINGS_KEY_SEARCH_OVERSAMPLE) == 0) {
int n = sqlite3_value_int(value);
if (n >= 0) ctx->search_oversample = n;
return 0;
}
if (strcasecmp(key, DBMEM_SETTINGS_KEY_PROVIDER) == 0) {
char *provider = dbmem_strdup((const char *)sqlite3_value_text(value));
if (provider) {
if (ctx->provider) dbmemory_free(ctx->provider);
ctx->provider = provider;
}
return 0;
}
if (strcasecmp(key, DBMEM_SETTINGS_KEY_MODEL) == 0) {
char *model = dbmem_strdup((const char *)sqlite3_value_text(value));
if (model) {
if (ctx->model) dbmemory_free(ctx->model);
ctx->model = model;
}
return 0;
}
if (strcasecmp(key, DBMEM_SETTINGS_KEY_EXTENSIONS) == 0) {
char *extensions = dbmem_strdup((const char *)sqlite3_value_text(value));
if (extensions) {
if (ctx->extensions) dbmemory_free(ctx->extensions);
ctx->extensions = extensions;
}
return 0;
}
return 0;
}
void dbmem_settings_load (sqlite3 *db, dbmem_context *ctx) {
const char *sql = "SELECT key, value FROM dbmem_settings;";
sqlite3_stmt *vm = NULL;
int rc = sqlite3_prepare_v2(db, sql, -1, &vm, NULL);
if (rc != SQLITE_OK) goto cleanup;
while (1) {
// no error handling here
rc = sqlite3_step(vm);
if (rc != SQLITE_ROW) break;
const char *key = (const char *)sqlite3_column_text(vm, 0);
if (!key) continue;
dbmem_settings_sync(ctx, key, sqlite3_column_value(vm, 1));
}
cleanup:
if (vm) sqlite3_finalize(vm);
return;
}
// MARK: - Database -
static int dbmem_database_init (sqlite3 *db) {
const char *sql = "CREATE TABLE IF NOT EXISTS dbmem_settings (key TEXT PRIMARY KEY, value TEXT);";
int rc = sqlite3_exec(db, sql, NULL, NULL, NULL);
if (rc != SQLITE_OK) return rc;
sql = "CREATE TABLE IF NOT EXISTS dbmem_content (hash INTEGER PRIMARY KEY NOT NULL, path TEXT NOT NULL UNIQUE, value TEXT DEFAULT NULL, length INTEGER NOT NULL, context TEXT DEFAULT NULL, created_at INTEGER DEFAULT 0, last_accessed INTEGER DEFAULT 0);";
rc = sqlite3_exec(db, sql, NULL, NULL, NULL);
if (rc != SQLITE_OK) return rc;
sql = "CREATE TABLE IF NOT EXISTS dbmem_vault (hash INTEGER NOT NULL, seq INTEGER NOT NULL, embedding BLOB NOT NULL, offset INTEGER NOT NULL, length INTEGER NOT NULL, PRIMARY KEY (hash, seq));";
rc = sqlite3_exec(db, sql, NULL, NULL, NULL);
if (rc != SQLITE_OK) return rc;
sql = "CREATE TABLE IF NOT EXISTS dbmem_cache (text_hash INTEGER NOT NULL, provider TEXT NOT NULL, model TEXT NOT NULL, embedding BLOB NOT NULL, dimension INTEGER NOT NULL, PRIMARY KEY (text_hash, provider, model));";
rc = sqlite3_exec(db, sql, NULL, NULL, NULL);
if (rc != SQLITE_OK) return rc;
sql = "CREATE VIRTUAL TABLE IF NOT EXISTS dbmem_vault_fts USING fts5 (content, hash UNINDEXED, seq UNINDEXED, context UNINDEXED);";
rc = sqlite3_exec(db, sql, NULL, NULL, NULL);
if (rc != SQLITE_OK) {
fts5_is_available = false;
rc = SQLITE_OK;
}
// explicitly allows extension loading (only available when linked statically)
// when loaded dynamically, the calling application must enable extension loading
#if defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
rc = sqlite3_enable_load_extension(db, 1);
if (rc != SQLITE_OK) return rc;
#endif
return rc;
}
static bool dbmem_database_check_if_stored (sqlite3 *db, uint64_t hash, int64_t len) {
static const char *sql = "SELECT length FROM dbmem_content WHERE hash=? LIMIT 1;";
bool result = false;
sqlite3_stmt *vm = NULL;
int rc = sqlite3_prepare_v2(db, sql, -1, &vm, NULL);
if (rc != SQLITE_OK) goto cleanup;
rc = sqlite3_bind_int64(vm, 1, (sqlite3_int64)hash);
if (rc != SQLITE_OK) goto cleanup;
rc = sqlite3_step(vm);
if (rc == SQLITE_DONE) rc = SQLITE_OK;
else if (rc != SQLITE_ROW) goto cleanup;
// SQLITE_ROW case
sqlite3_int64 saved_len = sqlite3_column_int64(vm, 0);
result = (saved_len == len);
cleanup:
if (vm) sqlite3_finalize(vm);
return result;
}
static void dbmem_database_delete_hash (sqlite3 *db, sqlite3_int64 hash) {
sqlite3_stmt *vm = NULL;
if (fts5_is_available) {
sqlite3_prepare_v2(db, "DELETE FROM dbmem_vault_fts WHERE hash=?1;", -1, &vm, NULL);
sqlite3_bind_int64(vm, 1, hash);
sqlite3_step(vm);
sqlite3_finalize(vm);
}
sqlite3_prepare_v2(db, "DELETE FROM dbmem_vault WHERE hash=?1;", -1, &vm, NULL);
sqlite3_bind_int64(vm, 1, hash);
sqlite3_step(vm);
sqlite3_finalize(vm);
sqlite3_prepare_v2(db, "DELETE FROM dbmem_content WHERE hash=?1;", -1, &vm, NULL);
sqlite3_bind_int64(vm, 1, hash);
sqlite3_step(vm);
sqlite3_finalize(vm);
}
static void dbmem_database_delete_stale_path (sqlite3 *db, const char *path, uint64_t new_hash) {
if (!path) return;
sqlite3_stmt *vm = NULL;
int rc = sqlite3_prepare_v2(db, "SELECT hash FROM dbmem_content WHERE path=?1;", -1, &vm, NULL);
if (rc != SQLITE_OK) return;
sqlite3_bind_text(vm, 1, path, -1, SQLITE_STATIC);
rc = sqlite3_step(vm);
if (rc == SQLITE_ROW) {
sqlite3_int64 old_hash = sqlite3_column_int64(vm, 0);
sqlite3_finalize(vm);
if ((uint64_t)old_hash != new_hash) {
dbmem_database_delete_hash(db, old_hash);
}
} else {
sqlite3_finalize(vm);
}
}
static int dbmem_database_add_entry (dbmem_context *ctx, sqlite3 *db, uint64_t hash, const char *buffer, int64_t len) {
static const char *sql = "INSERT INTO dbmem_content (hash, path, value, length, context, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6);";
sqlite3_stmt *vm = NULL;
int rc = sqlite3_prepare_v2(db, sql, -1, &vm, NULL);
if (rc != SQLITE_OK) goto cleanup;
rc = sqlite3_bind_int64(vm, 1, (sqlite3_int64)hash);
if (rc != SQLITE_OK) goto cleanup;
const char *path = ctx->path;
char uuid[DBMEM_UUID_STR_MAXLEN];
if (path == NULL) path = dbmem_uuid_v7(uuid);
rc = sqlite3_bind_text(vm, 2, path, -1, SQLITE_STATIC);
if (rc != SQLITE_OK) goto cleanup;
if (len > (int64_t)INT_MAX) { rc = SQLITE_TOOBIG; goto cleanup; }
rc = (ctx->save_content) ? sqlite3_bind_text(vm, 3, buffer, (int)len, SQLITE_STATIC) : sqlite3_bind_null(vm, 3);
if (rc != SQLITE_OK) goto cleanup;
rc = sqlite3_bind_int64(vm, 4, (sqlite3_int64)len);
if (rc != SQLITE_OK) goto cleanup;
rc = (ctx->context) ? sqlite3_bind_text(vm, 5, ctx->context, -1, SQLITE_STATIC) : sqlite3_bind_null(vm, 5);
if (rc != SQLITE_OK) goto cleanup;
rc = sqlite3_bind_int64(vm, 6, (sqlite3_int64)time(NULL));
if (rc != SQLITE_OK) goto cleanup;
rc = sqlite3_step(vm);
if (rc == SQLITE_DONE) rc = SQLITE_OK;
cleanup:
if (rc != SQLITE_OK) DEBUG_DBMEM_ALWAYS("Error in dbmem_database_add_entry: %s", sqlite3_errmsg(ctx->db));
if (vm) sqlite3_finalize(vm);
return rc;
}
static int dbmem_database_add_chunk (dbmem_context *ctx, embedding_result_t *result, size_t offset, size_t length, size_t index) {
static const char *sql = "INSERT INTO dbmem_vault (hash, seq, embedding, offset, length) VALUES (?1, ?2, ?3, ?4, ?5);";
sqlite3_stmt *vm = NULL;
int rc = sqlite3_prepare_v2(ctx->db, sql, -1, &vm, NULL);
if (rc != SQLITE_OK) goto cleanup;
rc = sqlite3_bind_int64(vm, 1, (sqlite3_int64)ctx->hash);
if (rc != SQLITE_OK) goto cleanup;
rc = sqlite3_bind_int64(vm, 2, (sqlite3_int64)index);
if (rc != SQLITE_OK) goto cleanup;
rc = sqlite3_bind_blob(vm, 3, result->embedding, (int)(result->n_embd * sizeof(float)), SQLITE_STATIC);
if (rc != SQLITE_OK) goto cleanup;
rc = sqlite3_bind_int64(vm, 4, (sqlite3_int64)offset);
if (rc != SQLITE_OK) goto cleanup;
rc = sqlite3_bind_int64(vm, 5, (sqlite3_int64)length);
if (rc != SQLITE_OK) goto cleanup;
rc = sqlite3_step(vm);
if (rc == SQLITE_DONE) rc = SQLITE_OK;
cleanup:
if (rc != SQLITE_OK) DEBUG_DBMEM_ALWAYS("Error in dbmem_database_add_chunk: %s", sqlite3_errmsg(ctx->db));
if (vm) sqlite3_finalize(vm);
return rc;
}
static int dbmem_database_add_fts5 (dbmem_context *ctx, const char *text, size_t text_len, size_t index) {
static const char *sql = "INSERT INTO dbmem_vault_fts (content, hash, seq, context) VALUES (?1, ?2, ?3, ?4);";
sqlite3_stmt *vm = NULL;
int rc = sqlite3_prepare_v2(ctx->db, sql, -1, &vm, NULL);
if (rc != SQLITE_OK) goto cleanup;
rc = sqlite3_bind_text(vm, 1, text, (int)text_len, SQLITE_STATIC);
if (rc != SQLITE_OK) goto cleanup;
rc = sqlite3_bind_int64(vm, 2, (sqlite3_int64)ctx->hash);
if (rc != SQLITE_OK) goto cleanup;
rc = sqlite3_bind_int64(vm, 3, (sqlite3_int64)index);
if (rc != SQLITE_OK) goto cleanup;
rc = (ctx->context) ? sqlite3_bind_text(vm, 4, ctx->context, -1, SQLITE_STATIC) : sqlite3_bind_null(vm, 4);
if (rc != SQLITE_OK) goto cleanup;
rc = sqlite3_step(vm);
if (rc == SQLITE_DONE) rc = SQLITE_OK;
cleanup:
if (rc != SQLITE_OK) DEBUG_DBMEM_ALWAYS("Error in dbmem_database_add_fts5: %s", sqlite3_errmsg(ctx->db));
if (vm) sqlite3_finalize(vm);
return rc;
}
static int dbmem_database_begin_transaction (sqlite3 *db) {
return sqlite3_exec(db, "SAVEPOINT " DBMEM_SAVEPOINT_NAME ";", NULL, NULL, NULL);
}
static int dbmem_database_commit_transaction (sqlite3 *db) {
return sqlite3_exec(db, "RELEASE " DBMEM_SAVEPOINT_NAME ";", NULL, NULL, NULL);
}
static int dbmem_database_rollback_transaction (sqlite3 *db) {
return sqlite3_exec(db, "ROLLBACK TO " DBMEM_SAVEPOINT_NAME "; RELEASE " DBMEM_SAVEPOINT_NAME ";", NULL, NULL, NULL);
}
// MARK: - Context -
static void *dbmem_context_create (sqlite3 *db) {
dbmem_context *ctx = (dbmem_context *)dbmemory_zeroalloc(sizeof(dbmem_context));
if (!ctx) return NULL;
ctx->db = db;
ctx->chars_per_tokens = DEFAULT_CHARS_PER_TOKEN;
ctx->max_tokens = DEFAULT_MAX_TOKENS;
ctx->overlay_tokens = DEFAULT_OVERLAY_TOKENS;
ctx->snippet_max_chars = DEFAULT_MAX_SNIPPET_CHARS;
ctx->skip_html = true;
ctx->save_content = true;
ctx->engine_warmup = false;
ctx->perform_fts = fts5_is_available;
ctx->max_results = DEFAULT_MAX_RESULTS;
ctx->vector_weight = DEFAULT_VECTOR_WEIGHT;
ctx->text_weight = DEFAULT_TEXT_WEIGHT;
ctx->min_score = DEFAULT_MIN_SCORE;
ctx->update_access = true;
ctx->embedding_cache = true;
return (void *)ctx;
}
static void dbmem_context_free (void *ptr) {
if (!ptr) return;
dbmem_context *ctx = (dbmem_context *)ptr;
if (ctx->provider) dbmemory_free(ctx->provider);
if (ctx->model) dbmemory_free(ctx->model);
if (ctx->api_key) dbmemory_free(ctx->api_key);
if (ctx->extensions) dbmemory_free(ctx->extensions);
if (ctx->cache_buffer) dbmemory_free(ctx->cache_buffer);
// custom provider
if (ctx->custom_engine && ctx->custom_provider.free) ctx->custom_provider.free(ctx->custom_engine, ctx->custom_provider.xdata);
if (ctx->custom_provider_name) dbmemory_free(ctx->custom_provider_name);
#ifndef DBMEM_OMIT_LOCAL_ENGINE
if (ctx->l_engine) dbmem_local_engine_free(ctx->l_engine);
#endif
#ifndef DBMEM_OMIT_REMOTE_ENGINE
if (ctx->r_engine) dbmem_remote_engine_free(ctx->r_engine);
#endif
dbmemory_free(ctx);
}
static void dbmem_context_reset_temp_values (dbmem_context *ctx) {
ctx->counter = 0;
ctx->hash = 0;
ctx->context = NULL;
ctx->path = NULL;
ctx->error_msg[0] = 0;
}
void *dbmem_context_engine (dbmem_context *ctx, bool *is_local) {
if (ctx->is_custom) {
if (is_local) *is_local = false;
return ctx->custom_engine;
}
if (is_local) *is_local = ctx->is_local;
return (ctx->is_local) ? (void *)ctx->l_engine : (void *)ctx->r_engine;
}
bool dbmem_context_is_custom (dbmem_context *ctx) {
return ctx->is_custom;
}
int dbmem_context_custom_compute (dbmem_context *ctx, const char *text, int text_len, embedding_result_t *result) {
dbmem_embedding_result_t cr = {0};
int rc = ctx->custom_provider.compute(ctx->custom_engine, text, text_len, ctx->custom_provider.xdata, &cr);
if (rc != 0) return rc;
result->n_tokens = cr.n_tokens;
result->n_tokens_truncated = cr.n_tokens_truncated;
result->n_embd = cr.n_embd;
result->embedding = cr.embedding;
return 0;
}
bool dbmem_context_load_vector (dbmem_context *ctx) {
if (ctx->vector_extension_available) return true;
// check if sqlite-vector is loaded
// there's no built-in way to verify if sqlite-vector has already been already loaded for this specific database connection
// the workaround is to attempt to execute vector_version and check for an error
// an error indicates that initialization has not been performed
if (sqlite3_exec(ctx->db, "SELECT vector_version();", NULL, NULL, NULL) != SQLITE_OK) {
dbmem_context_set_error(ctx, "SQLite-vector extension not found, make sure to load it before using the memory_search function");
return false;
}
if (ctx->dimension == 0) {
dbmem_context_set_error(ctx, "SQLite-vector extension cannot be loaded because embedding dimension is not specified");
return false;
}
// In the future can check for quantization options and embedding type here
char sql[1024];
snprintf(sql, sizeof(sql), "SELECT vector_init('dbmem_vault', 'embedding', 'type=FLOAT32,distance=COSINE,dimension=%d');", ctx->dimension);
int rc = sqlite3_exec(ctx->db, sql, NULL, NULL, NULL);
if (rc != SQLITE_OK) {
dbmem_context_set_error(ctx, sqlite3_errmsg(ctx->db));
return false;
}
ctx->vector_extension_available = true;
return true;
}
bool dbmem_context_sync_available (dbmem_context *ctx) {
if (ctx->sync_extension_available) return true;
// there's no built-in way to verify if sqlite-sync has already been already loaded for this specific database connection
// the workaround is to attempt to execute cloudsync_version and check for an error (an error indicates that initialization has not been performed)
if (sqlite3_exec(ctx->db, "SELECT cloudsync_version();", NULL, NULL, NULL) != SQLITE_OK) {
snprintf(ctx->error_msg, DBMEM_ERRBUF_SIZE, "%s", "SQLite-sync extension not found, make sure to load it before using the memory_sync function");
return false;
}
ctx->sync_extension_available = true;
return true;
}
bool dbmem_context_perform_fts (dbmem_context *ctx) {
if (!fts5_is_available) return false;
return ctx->perform_fts;
}
int dbmem_context_max_results (dbmem_context *ctx) {
return ctx->max_results;
}
double dbmem_context_vector_weight (dbmem_context *ctx) {
return ctx->vector_weight;
}
double dbmem_context_text_weight (dbmem_context *ctx) {
return ctx->text_weight;
}
double dbmem_context_min_score (dbmem_context *ctx) {
return ctx->min_score;
}
bool dbmem_context_update_access (dbmem_context *ctx) {
return ctx->update_access;
}
int dbmem_context_search_oversample (dbmem_context *ctx) {
return ctx->search_oversample;
}
const char *dbmem_context_errmsg (dbmem_context *ctx) {
return ctx->error_msg;
}
const char *dbmem_context_apikey (dbmem_context *ctx) {
return ctx->api_key;
}
void dbmem_context_set_error (dbmem_context *ctx, const char *str) {
snprintf(ctx->error_msg, DBMEM_ERRBUF_SIZE, "%s", str);
}
void dbmem_context_set_errorf (dbmem_context *ctx, const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vsnprintf(ctx->error_msg, DBMEM_ERRBUF_SIZE, fmt, ap);
va_end(ap);
}
// MARK: - Deletion -
static void dbmem_delete (sqlite3_context *context, int argc, sqlite3_value **argv) {
UNUSED_PARAM(argc);
if (sqlite3_value_type(argv[0]) != SQLITE_INTEGER) {
sqlite3_result_error(context, "The function memory_delete expects one argument of type INTEGER (hash)", SQLITE_ERROR);
return;
}
sqlite3_int64 hash = sqlite3_value_int64(argv[0]);
sqlite3 *db = sqlite3_context_db_handle(context);
int rc = dbmem_database_begin_transaction(db);
if (rc != SQLITE_OK) {
sqlite3_result_error(context, sqlite3_errmsg(db), -1);
return;
}
// Delete from FTS first (if available)
if (fts5_is_available) {
sqlite3_stmt *vm = NULL;
rc = sqlite3_prepare_v2(db, "DELETE FROM dbmem_vault_fts WHERE hash = ?1;", -1, &vm, NULL);
if (rc == SQLITE_OK) {
sqlite3_bind_int64(vm, 1, hash);
sqlite3_step(vm);
sqlite3_finalize(vm);
}
}
// Delete from vault
sqlite3_stmt *vm = NULL;
rc = sqlite3_prepare_v2(db, "DELETE FROM dbmem_vault WHERE hash = ?1;", -1, &vm, NULL);
if (rc != SQLITE_OK) goto rollback;
sqlite3_bind_int64(vm, 1, hash);
rc = sqlite3_step(vm);
sqlite3_finalize(vm);
if (rc != SQLITE_DONE) goto rollback;
// Delete from content
rc = sqlite3_prepare_v2(db, "DELETE FROM dbmem_content WHERE hash = ?1;", -1, &vm, NULL);
if (rc != SQLITE_OK) goto rollback;
sqlite3_bind_int64(vm, 1, hash);
rc = sqlite3_step(vm);
sqlite3_finalize(vm);
if (rc != SQLITE_DONE) goto rollback;
int changes = sqlite3_changes(db);
dbmem_database_commit_transaction(db);
sqlite3_result_int(context, changes);
return;
rollback:
dbmem_database_rollback_transaction(db);
sqlite3_result_error(context, sqlite3_errmsg(db), -1);
}
static void dbmem_delete_context (sqlite3_context *context, int argc, sqlite3_value **argv) {
UNUSED_PARAM(argc);
if (sqlite3_value_type(argv[0]) != SQLITE_TEXT) {
sqlite3_result_error(context, "The function memory_delete_context expects one argument of type TEXT (context)", SQLITE_ERROR);
return;
}
const char *ctx_name = (const char *)sqlite3_value_text(argv[0]);
sqlite3 *db = sqlite3_context_db_handle(context);
int rc = dbmem_database_begin_transaction(db);
if (rc != SQLITE_OK) {
sqlite3_result_error(context, sqlite3_errmsg(db), -1);
return;
}
// Delete from FTS first (if available)
if (fts5_is_available) {
sqlite3_stmt *vm = NULL;
rc = sqlite3_prepare_v2(db, "DELETE FROM dbmem_vault_fts WHERE hash IN (SELECT hash FROM dbmem_content WHERE context = ?1);", -1, &vm, NULL);
if (rc == SQLITE_OK) {
sqlite3_bind_text(vm, 1, ctx_name, -1, SQLITE_STATIC);
sqlite3_step(vm);
sqlite3_finalize(vm);
}
}
// Delete from vault
sqlite3_stmt *vm = NULL;
rc = sqlite3_prepare_v2(db, "DELETE FROM dbmem_vault WHERE hash IN (SELECT hash FROM dbmem_content WHERE context = ?1);", -1, &vm, NULL);
if (rc != SQLITE_OK) goto rollback;
sqlite3_bind_text(vm, 1, ctx_name, -1, SQLITE_STATIC);
rc = sqlite3_step(vm);
sqlite3_finalize(vm);
if (rc != SQLITE_DONE) goto rollback;
// Delete from content
rc = sqlite3_prepare_v2(db, "DELETE FROM dbmem_content WHERE context = ?1;", -1, &vm, NULL);
if (rc != SQLITE_OK) goto rollback;
sqlite3_bind_text(vm, 1, ctx_name, -1, SQLITE_STATIC);
rc = sqlite3_step(vm);
sqlite3_finalize(vm);
if (rc != SQLITE_DONE) goto rollback;
int changes = sqlite3_changes(db);
dbmem_database_commit_transaction(db);
sqlite3_result_int(context, changes);
return;
rollback:
dbmem_database_rollback_transaction(db);
sqlite3_result_error(context, sqlite3_errmsg(db), -1);
}
static void dbmem_clear (sqlite3_context *context, int argc, sqlite3_value **argv) {
UNUSED_PARAM(argc); UNUSED_PARAM(argv);
sqlite3 *db = sqlite3_context_db_handle(context);
int rc = dbmem_database_begin_transaction(db);
if (rc != SQLITE_OK) {
sqlite3_result_error(context, sqlite3_errmsg(db), -1);
return;
}
// Delete from FTS first (if available)
if (fts5_is_available) {
rc = sqlite3_exec(db, "DELETE FROM dbmem_vault_fts;", NULL, NULL, NULL);
if (rc != SQLITE_OK) goto rollback;
}
// Delete from vault
rc = sqlite3_exec(db, "DELETE FROM dbmem_vault;", NULL, NULL, NULL);
if (rc != SQLITE_OK) goto rollback;
// Delete from content
rc = sqlite3_exec(db, "DELETE FROM dbmem_content;", NULL, NULL, NULL);
if (rc != SQLITE_OK) goto rollback;
dbmem_database_commit_transaction(db);
sqlite3_result_int(context, 1);
return;
rollback:
dbmem_database_rollback_transaction(db);
sqlite3_result_error(context, sqlite3_errmsg(db), -1);
}
// MARK: - Cache Clear -
static void dbmem_cache_clear (sqlite3_context *context, int argc, sqlite3_value **argv) {
sqlite3 *db = sqlite3_context_db_handle(context);
int rc;
if (argc == 0) {
rc = sqlite3_exec(db, "DELETE FROM dbmem_cache;", NULL, NULL, NULL);
} else if (argc == 2) {
if (sqlite3_value_type(argv[0]) != SQLITE_TEXT || sqlite3_value_type(argv[1]) != SQLITE_TEXT) {
sqlite3_result_error(context, "The function memory_cache_clear expects two arguments of type TEXT (provider, model)", SQLITE_ERROR);
return;
}
const char *provider = (const char *)sqlite3_value_text(argv[0]);
const char *model = (const char *)sqlite3_value_text(argv[1]);
sqlite3_stmt *vm = NULL;
rc = sqlite3_prepare_v2(db, "DELETE FROM dbmem_cache WHERE provider=?1 AND model=?2;", -1, &vm, NULL);
if (rc == SQLITE_OK) {
sqlite3_bind_text(vm, 1, provider, -1, SQLITE_STATIC);
sqlite3_bind_text(vm, 2, model, -1, SQLITE_STATIC);
rc = sqlite3_step(vm);
if (rc == SQLITE_DONE) rc = SQLITE_OK;
}
if (vm) sqlite3_finalize(vm);
} else {
sqlite3_result_error(context, "The function memory_cache_clear expects 0 or 2 arguments", SQLITE_ERROR);
return;
}
if (rc != SQLITE_OK) {
sqlite3_result_error(context, sqlite3_errmsg(db), -1);
return;
}
sqlite3_result_int(context, sqlite3_changes(db));
}
// MARK: - General -
static void dbmem_version (sqlite3_context *context, int argc, sqlite3_value **argv) {
UNUSED_PARAM(argc); UNUSED_PARAM(argv);
sqlite3_result_text(context, SQLITE_DBMEMORY_VERSION, -1, NULL);
}
static int dbmem_reindex(dbmem_context *ctx);
static void dbmem_set_model (sqlite3_context *context, int argc, sqlite3_value **argv) {
// 2 TEXT arguments: provider and model
// if provider is local then model is the full path to the model to use
// options are saved into settings
// sanity check type
if ((sqlite3_value_type(argv[0]) != SQLITE_TEXT) || (sqlite3_value_type(argv[1]) != SQLITE_TEXT)) {
sqlite3_result_error(context, "The function memory_set_model expects two arguments of type TEXT", SQLITE_ERROR);
return;
}
// retrieve arguments
const char *provider = (const char *)sqlite3_value_text(argv[0]);
const char *model = (const char *)sqlite3_value_text(argv[1]);
// retrieve context
dbmem_context *ctx = (dbmem_context *)sqlite3_user_data(context);
// detect model change (only if a model was previously configured)
bool model_changed = false;
if (ctx->provider && ctx->model) {
model_changed = (strcasecmp(ctx->provider, provider) != 0 || strcasecmp(ctx->model, model) != 0);
}
bool is_local_provider = (strcasecmp(provider, DBMEM_LOCAL_PROVIDER) == 0);
// check if a custom provider matches
bool is_custom_provider = (ctx->custom_provider_name && ctx->custom_provider.compute &&
strcasecmp(provider, ctx->custom_provider_name) == 0);
if (!is_custom_provider) {
#ifdef DBMEM_OMIT_LOCAL_ENGINE
if (is_local_provider) {
sqlite3_result_error(context, "Local provider cannot be set because SQLite-memory was compiled without local provider support", SQLITE_ERROR);
return;
}
#endif
#ifdef DBMEM_OMIT_REMOTE_ENGINE
if (!is_local_provider) {
sqlite3_result_error(context, "Remote provider cannot be set because SQLite-memory was compiled without remote provider support", SQLITE_ERROR);
return;
}
#endif
}
// custom provider path
if (is_custom_provider) {
// free previous custom engine if any
if (ctx->custom_engine && ctx->custom_provider.free) ctx->custom_provider.free(ctx->custom_engine, ctx->custom_provider.xdata);
ctx->custom_engine = NULL;
ctx->custom_engine = ctx->custom_provider.init(model, ctx->api_key, ctx->custom_provider.xdata, ctx->error_msg);
if (ctx->custom_engine == NULL) {
sqlite3_result_error(context, ctx->error_msg, -1);
return;
}
ctx->is_custom = true;
ctx->is_local = false;
}
// if provider is local then make sure model file exists
#ifndef DBMEM_OMIT_LOCAL_ENGINE
if (!is_custom_provider && is_local_provider) {
if (dbmem_file_exists(model) == false) {
sqlite3_result_error(context, "Local model not found in the specified path", SQLITE_ERROR);
return;
}
if (ctx->l_engine) dbmem_local_engine_free(ctx->l_engine);
ctx->l_engine = NULL;
ctx->l_engine = dbmem_local_engine_init(ctx, model, ctx->error_msg);
if (ctx->l_engine == NULL) {
sqlite3_result_error(context, ctx->error_msg, -1);
return;
}
if (ctx->engine_warmup) {
dbmem_local_engine_warmup(ctx->l_engine);
}
ctx->is_local = true;
ctx->is_custom = false;
}
#endif
#ifndef DBMEM_OMIT_REMOTE_ENGINE
if (!is_custom_provider && !is_local_provider) {
if (ctx->r_engine) dbmem_remote_engine_free(ctx->r_engine);
ctx->r_engine = NULL;