| 950 | } |
| 951 | |
| 952 | static cbm_store_t *store_open_internal(const char *path, bool in_memory, bool create) { |
| 953 | cbm_store_t *s = calloc(CBM_ALLOC_ONE, sizeof(cbm_store_t)); |
| 954 | if (!s) { |
| 955 | return NULL; |
| 956 | } |
| 957 | |
| 958 | int flags = SQLITE_OPEN_READWRITE | (create ? SQLITE_OPEN_CREATE : 0); |
| 959 | if (in_memory) { |
| 960 | flags |= SQLITE_OPEN_MEMORY; |
| 961 | } |
| 962 | |
| 963 | char open_path[4096]; |
| 964 | const char *effective_path = path; |
| 965 | if (path && !in_memory) { |
| 966 | if (!cbm_path_for_file_api(path, open_path, sizeof(open_path))) { |
| 967 | free(s); |
| 968 | return NULL; |
| 969 | } |
| 970 | effective_path = open_path; |
| 971 | } |
| 972 | int rc = sqlite3_open_v2(effective_path, &s->db, flags, NULL); |
| 973 | if (rc != SQLITE_OK) { |
| 974 | sqlite3_close(s->db); |
| 975 | free(s); |
| 976 | return NULL; |
| 977 | } |
| 978 | |
| 979 | if (path && !in_memory) { |
| 980 | s->db_path = heap_strdup(path); |
| 981 | } |
| 982 | |
| 983 | /* Security: block ATTACH/DETACH to prevent file creation via SQL injection. |
| 984 | * The authorizer runs inside SQLite's query planner — no string-level bypass. */ |
| 985 | sqlite3_set_authorizer(s->db, store_authorizer, NULL); |
| 986 | |
| 987 | /* Register REGEXP function (SQLite doesn't have one built-in) */ |
| 988 | sqlite3_create_function(s->db, "regexp", ST_COL_2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, |
| 989 | sqlite_regexp, NULL, NULL); |
| 990 | /* Case-insensitive variant for search with case_sensitive=false */ |
| 991 | sqlite3_create_function(s->db, "iregexp", ST_COL_2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, |
| 992 | sqlite_iregexp, NULL, NULL); |
| 993 | /* Int8 cosine similarity for vector search */ |
| 994 | sqlite3_create_function(s->db, "cbm_cosine_i8", ST_COL_2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, |
| 995 | NULL, sqlite_cosine_i8, NULL, NULL); |
| 996 | /* camelCase splitter for FTS5 BM25 indexing */ |
| 997 | sqlite3_create_function(s->db, "cbm_camel_split", SKIP_ONE, SQLITE_UTF8 | SQLITE_DETERMINISTIC, |
| 998 | NULL, sqlite_camel_split, NULL, NULL); |
| 999 | |
| 1000 | if (configure_pragmas(s, in_memory, false) != CBM_STORE_OK || init_schema(s) != CBM_STORE_OK || |
| 1001 | create_user_indexes(s) != CBM_STORE_OK) { |
| 1002 | sqlite3_close(s->db); |
| 1003 | safe_str_free(&s->db_path); |
| 1004 | free(s); |
| 1005 | return NULL; |
| 1006 | } |
| 1007 | |
| 1008 | return s; |
| 1009 | } |
no test coverage detected