| 1178 | #endif |
| 1179 | |
| 1180 | cbm_store_t *cbm_store_open_path_query(const char *db_path) { |
| 1181 | if (!db_path) { |
| 1182 | return NULL; |
| 1183 | } |
| 1184 | |
| 1185 | cbm_store_t *s = calloc(CBM_ALLOC_ONE, sizeof(cbm_store_t)); |
| 1186 | if (!s) { |
| 1187 | return NULL; |
| 1188 | } |
| 1189 | |
| 1190 | /* One query connection at a time takes its first look at the WAL. On an |
| 1191 | * idle DB (no connection open, -shm reset) that first read runs WAL |
| 1192 | * recovery, rebuilding the shared wal-index header under SQLite's write |
| 1193 | * lock, while another opener reads the same header lock-free before it |
| 1194 | * takes its read lock (walTryBeginRead). Across processes SQLite's file |
| 1195 | * locks order the two; between this process's request threads nothing |
| 1196 | * did, and TSan reported walTryBeginRead against walIndexRecover from |
| 1197 | * concurrent index_repository requests. Holding one process-wide mutex |
| 1198 | * across open + first access puts a recovery before the next connection's |
| 1199 | * first read. The probe is one sqlite_master read, so the hold is short. */ |
| 1200 | sqlite3_mutex *first_access = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_APP1); |
| 1201 | sqlite3_mutex_enter(first_access); |
| 1202 | bool opened = query_open_first_access(s, db_path); |
| 1203 | query_first_access_hook(); |
| 1204 | sqlite3_mutex_leave(first_access); |
| 1205 | if (!opened) { |
| 1206 | free(s); |
| 1207 | return NULL; |
| 1208 | } |
| 1209 | |
| 1210 | s->db_path = heap_strdup(db_path); |
| 1211 | s->query_store = true; |
| 1212 | |
| 1213 | /* Security: block ATTACH/DETACH to prevent file creation via SQL injection. */ |
| 1214 | sqlite3_set_authorizer(s->db, store_authorizer, NULL); |
| 1215 | |
| 1216 | /* Register REGEXP functions. */ |
| 1217 | sqlite3_create_function(s->db, "regexp", ST_COL_2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, |
| 1218 | sqlite_regexp, NULL, NULL); |
| 1219 | sqlite3_create_function(s->db, "iregexp", ST_COL_2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, |
| 1220 | sqlite_iregexp, NULL, NULL); |
| 1221 | sqlite3_create_function(s->db, "cbm_cosine_i8", ST_COL_2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, |
| 1222 | NULL, sqlite_cosine_i8, NULL, NULL); |
| 1223 | sqlite3_create_function(s->db, "cbm_camel_split", SKIP_ONE, SQLITE_UTF8 | SQLITE_DETERMINISTIC, |
| 1224 | NULL, sqlite_camel_split, NULL, NULL); |
| 1225 | |
| 1226 | if (configure_pragmas(s, false, true) != CBM_STORE_OK) { |
| 1227 | sqlite3_close(s->db); |
| 1228 | safe_str_free(&s->db_path); |
| 1229 | free(s); |
| 1230 | return NULL; |
| 1231 | } |
| 1232 | |
| 1233 | return s; |
| 1234 | } |
| 1235 | |
| 1236 | /* ── Integrity check ───────────────────────────────────────────── */ |
| 1237 | |