@amritk/nish-x86_64-linux 0.41.0 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/bin/nish +0 -0
  2. package/docs/AI.md +282 -126
  3. package/package.json +2 -2
  4. package/runtime/core.d.ts +16 -0
  5. package/runtime/core.mjs +5 -0
  6. package/runtime/nish.d.ts +204 -33
  7. package/runtime/nish.h +19 -3
  8. package/runtime/nish.mjs +5 -1
  9. package/runtime/runtime-cross.c +15 -0
  10. package/runtime/runtime-net.c +876 -10
  11. package/runtime/runtime-region.c +21 -0
  12. package/runtime/runtime-sandbox.c +112 -15
  13. package/runtime/runtime-text.c +11 -0
  14. package/runtime/runtime-uring.c +533 -77
  15. package/runtime/runtime-wasm.c +3 -0
  16. package/runtime/runtime.c +474 -5
  17. package/runtime/sqlite/README.md +16 -3
  18. package/runtime/sqlite/nish-sqlite.c +940 -29
  19. package/scripts/build.sh +125 -29
  20. package/std/README.md +3 -3
  21. package/std/crypto/base64url.ts +102 -1
  22. package/std/crypto/scram.ts +142 -0
  23. package/std/crypto/sha1.ts +99 -41
  24. package/std/host/ring.ts +1 -1
  25. package/std/host/text.ts +1 -1
  26. package/std/net/fetch.ts +9 -1
  27. package/std/net/handler.ts +79 -15
  28. package/std/net/http-server.ts +2 -3
  29. package/std/net/http1-server.ts +294 -51
  30. package/std/net/http3-server.ts +26 -15
  31. package/std/net/http3.ts +2 -2
  32. package/std/net/oidc.ts +1107 -0
  33. package/std/net/postgres-async.ts +64 -33
  34. package/std/net/postgres.ts +65 -76
  35. package/std/net/quic-conn-ack.ts +57 -7
  36. package/std/net/quic-frame.ts +104 -2
  37. package/std/net/quic-listener.ts +9 -2
  38. package/std/net/quic.ts +16 -1
  39. package/std/net/serve.ts +10 -8
  40. package/std/net/websocket.ts +188 -49
  41. package/std/sqlite.ts +325 -0
  42. package/std/text.ts +80 -11
@@ -22,29 +22,44 @@
22
22
  * SQLITE_THREADSAFE=2 under --threads (scripts/build.sh), which allows one
23
23
  * connection per thread. A thread's tables are not freed when it exits.
24
24
  *
25
- * Nothing here allocates except a table growing (`slot_take`) and SQLite
26
- * itself. Each adapter is a table load and the SQLite call, compiled to LTO
27
- * bitcode (scripts/build.sh, `sqlite_units`), so it inlines into the program.
25
+ * Nothing here allocates except a table growing (`slot_take`), a cursor
26
+ * opening (`nishsqlite_cursor_open`, one block for the cursor and its key),
27
+ * a cursor's row buffer growing for a record that spills onto overflow pages
28
+ * (`row_of`), and SQLite itself. Each adapter is a table load and the SQLite call. This file
29
+ * includes the amalgamation, sqlite3.c, and is the one unit of
30
+ * runtime/sqlite/ (scripts/build.sh, `sqlite_units`): the cursor adapter
31
+ * below calls SQLite's B-tree and record functions, which are static there
32
+ * (docs/sqlite-cursor.md). The unit is native code, so the adapters do not
33
+ * inline into the program, but SQLite's own calls inline into them.
28
34
  *
29
35
  * Results follow SQLite: an `int32_t` result code, extended, because every
30
- * connection is opened with SQLITE_OPEN_EXRESCODE. Two adapters answer a
31
- * handle or a length when they succeed and the negated code when they fail.
36
+ * connection is opened with SQLITE_OPEN_EXRESCODE. Some adapters answer a
37
+ * handle, a length or a cursor move when they succeed and the negated code when they fail.
32
38
  * Text and blobs are bound SQLITE_TRANSIENT, so SQLite copies them, because
33
39
  * the program lends its bytes for the length of one call
34
40
  * (docs/LANGUAGE.md, "Calling C"). */
35
41
 
42
+ #include "sqlite3.c"
43
+
44
+ /* A cursor holds its B-tree's pages by its connection's Btree. With a shared
45
+ * cache another connection could free them under it, so the cursors refuse
46
+ * to build without SQLITE_OMIT_SHARED_CACHE, which scripts/build.sh passes. */
47
+ #ifndef SQLITE_OMIT_SHARED_CACHE
48
+ #error "nish-sqlite.c needs SQLITE_OMIT_SHARED_CACHE"
49
+ #endif
50
+
36
51
  #include <stdint.h>
37
52
  #include <stdlib.h>
38
53
  #include <string.h>
39
54
 
40
55
  #include "../nish.h"
41
- #include "sqlite3.h"
42
56
 
43
57
  typedef struct nishsqlite_slot {
44
- void *p; /* the sqlite3 * or sqlite3_stmt *, NULL while free */
58
+ void *p; /* the connection, statement or cursor; NULL while free */
45
59
  int32_t gen; /* 1..32767, the high bits of the slot's handle */
46
- int32_t owner; /* a statement's database handle; 0 for a database */
60
+ int32_t owner; /* the database handle of a statement or cursor; 0 for a database */
47
61
  int32_t next; /* the next free slot, oldest first; 0 ends the list */
62
+ int32_t flags; /* a statement's NISH_SQLITE_PLAIN */
48
63
  } nishsqlite_slot;
49
64
 
50
65
  typedef struct nishsqlite_table {
@@ -60,6 +75,43 @@ typedef struct nishsqlite_table {
60
75
 
61
76
  static NISH_TLS nishsqlite_table nishsqlite_dbs;
62
77
  static NISH_TLS nishsqlite_table nishsqlite_stmts;
78
+ static NISH_TLS nishsqlite_table nishsqlite_cursors;
79
+
80
+ /* A shape `cursor_build` checked: what the schema check found for one `name`
81
+ * and `columns`, under one schema cookie. It is kept only from a transaction
82
+ * that is a read (`SQLITE_TXN_READ`), whose cookie is a committed one, and
83
+ * answered only to an open whose read sees the same cookie: SQLite's own test
84
+ * of whether a prepared statement still matches the schema. */
85
+ #define NISH_SQLITE_SHAPES 8
86
+ typedef struct nishsqlite_shape {
87
+ char *name; /* NULL for an empty entry */
88
+ char *columns;
89
+ u32 cookie;
90
+ int32_t is_index, ncol, nkey, alias;
91
+ Pgno root;
92
+ KeyInfo *ki; /* one reference, the entry's */
93
+ } nishsqlite_shape;
94
+
95
+ /* A connection: the slot of a database handle points at one of these. The
96
+ * authorizer (`nishsqlite_authorize`) gets it as its user data. */
97
+ typedef struct nishsqlite_conn {
98
+ sqlite3 *db;
99
+ int32_t self; /* the connection's own handle */
100
+ int32_t classifying; /* inside nishsqlite_prepare: record what is authorized */
101
+ int32_t seen_select; /* SQLITE_SELECT was authorized while classifying */
102
+ int32_t seen_other; /* an action off the allowlist was authorized */
103
+ int32_t internal; /* the adapter's own statements are running */
104
+ int32_t ncursors; /* open cursors, so invalidating none costs no scan */
105
+ int32_t shape_next; /* the entry of `shapes` the next miss replaces */
106
+ /* `nishsqlite_begin_read`'s and `nishsqlite_end_read`'s statements,
107
+ * prepared on first use and reset after each run. */
108
+ sqlite3_stmt *begin_st, *schema_st, *commit_st;
109
+ nishsqlite_shape shapes[NISH_SQLITE_SHAPES];
110
+ } nishsqlite_conn;
111
+
112
+ /* A statement that authorized SQLITE_SELECT and nothing off the allowlist: one
113
+ * that may step while the connection's cursors stay open. */
114
+ #define NISH_SQLITE_PLAIN 1
63
115
 
64
116
  /* What the last failed `nishsqlite_open` said, kept because the connection it
65
117
  * came from is closed before the open answers. */
@@ -73,9 +125,14 @@ static inline nishsqlite_slot *slot_of(nishsqlite_table *t, int32_t h) {
73
125
  return s;
74
126
  }
75
127
 
76
- static inline sqlite3 *db_of(int32_t h) {
128
+ static inline nishsqlite_conn *conn_of(int32_t h) {
77
129
  nishsqlite_slot *s = slot_of(&nishsqlite_dbs, h);
78
- return s ? (sqlite3 *)s->p : NULL;
130
+ return s ? (nishsqlite_conn *)s->p : NULL;
131
+ }
132
+
133
+ static inline sqlite3 *db_of(int32_t h) {
134
+ nishsqlite_conn *c = conn_of(h);
135
+ return c ? c->db : NULL;
79
136
  }
80
137
 
81
138
  static inline sqlite3_stmt *stmt_of(int32_t h) {
@@ -106,6 +163,7 @@ static int32_t slot_take(nishsqlite_table *t, void *p, int32_t owner) {
106
163
  t->at[i].p = p;
107
164
  t->at[i].owner = owner;
108
165
  t->at[i].next = 0;
166
+ t->at[i].flags = 0;
109
167
  return (t->at[i].gen << 16) | i;
110
168
  }
111
169
 
@@ -126,6 +184,49 @@ static void slot_give(nishsqlite_table *t, int32_t h) {
126
184
 
127
185
  /* ---- Connections -------------------------------------------------------- */
128
186
 
187
+ static void cursors_invalidate(nishsqlite_conn *c);
188
+
189
+ /* Empties the connection's checked shapes. Before the close: a KeyInfo is
190
+ * freed through its connection. */
191
+ static void shapes_clear(nishsqlite_conn *c) {
192
+ sqlite3_mutex *mx = sqlite3_db_mutex(c->db);
193
+ sqlite3_mutex_enter(mx); /* a KeyInfo is freed through its db */
194
+ for (int32_t i = 0; i < NISH_SQLITE_SHAPES; i++) {
195
+ nishsqlite_shape *s = &c->shapes[i];
196
+ sqlite3_free(s->name);
197
+ sqlite3_free(s->columns);
198
+ sqlite3KeyInfoUnref(s->ki);
199
+ memset(s, 0, sizeof *s);
200
+ }
201
+ c->shape_next = 0;
202
+ sqlite3_mutex_leave(mx);
203
+ }
204
+
205
+ /* The connection's authorizer, which the adapter owns: `nish/sqlite` exposes
206
+ * none. It never refuses anything; it only watches. While `nishsqlite_prepare`
207
+ * classifies a statement it records whether the statement authorized
208
+ * SQLITE_SELECT and whether it authorized anything off the allowlist. Outside
209
+ * that, and outside the adapter's own statements, an action off the allowlist
210
+ * is a statement about to run that the classification did not see (one
211
+ * `sqlite3_exec` prepares, a re-prepare inside `sqlite3_step`, the statement a
212
+ * pragma table-valued function prepares), so the connection's cursors are
213
+ * invalidated on the spot (docs/sqlite-cursor.md). */
214
+ static int nishsqlite_authorize(void *user, int action, const char *a, const char *b,
215
+ const char *db_name, const char *trigger) {
216
+ (void)a, (void)b, (void)db_name, (void)trigger;
217
+ nishsqlite_conn *c = user;
218
+ int listed = action == SQLITE_SELECT || action == SQLITE_READ || action == SQLITE_FUNCTION ||
219
+ action == SQLITE_RECURSIVE;
220
+ if (c->internal) return SQLITE_OK;
221
+ if (c->classifying) {
222
+ if (action == SQLITE_SELECT) c->seen_select = 1;
223
+ if (!listed) c->seen_other = 1;
224
+ } else if (!listed) {
225
+ cursors_invalidate(c);
226
+ }
227
+ return SQLITE_OK;
228
+ }
229
+
129
230
  #define NISH_SQLITE_OPEN_FLAGS \
130
231
  (SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | \
131
232
  SQLITE_OPEN_URI | SQLITE_OPEN_MEMORY | SQLITE_OPEN_NOFOLLOW)
@@ -143,8 +244,15 @@ int32_t nishsqlite_open(const char *path, int32_t flags) {
143
244
  sqlite3 *db = NULL;
144
245
  int rc = sqlite3_open_v2(path, &db, flags | SQLITE_OPEN_EXRESCODE, NULL);
145
246
  if (rc == SQLITE_OK) {
146
- int32_t h = slot_take(&nishsqlite_dbs, db, 0);
147
- if (h != 0) return h;
247
+ nishsqlite_conn *c = calloc(1, sizeof *c);
248
+ int32_t h = c ? slot_take(&nishsqlite_dbs, c, 0) : 0;
249
+ if (h != 0) {
250
+ c->db = db;
251
+ c->self = h;
252
+ sqlite3_set_authorizer(db, nishsqlite_authorize, c);
253
+ return h;
254
+ }
255
+ free(c);
148
256
  rc = SQLITE_NOMEM;
149
257
  }
150
258
  const char *message = db && rc != SQLITE_NOMEM ? sqlite3_errmsg(db) : sqlite3_errstr(rc);
@@ -156,14 +264,21 @@ int32_t nishsqlite_open(const char *path, int32_t flags) {
156
264
  /* The message of the last `nishsqlite_open` that failed on this thread. */
157
265
  const char *nishsqlite_open_errmsg(void) { return nishsqlite_open_message; }
158
266
 
159
- /* Finalizes every statement of the connection, frees their handles, then
160
- * closes it. close_v2 rather than close, so a connection something else still
161
- * holds (none can, today) is closed when that ends instead of staying open.
162
- * The handle is freed only once the close succeeds, so a close that fails
163
- * leaves the connection usable and its message readable. */
267
+ /* Closes every cursor of the connection, then finalizes every statement of
268
+ * it, frees their handles, then closes it. close_v2 rather than close, so a
269
+ * connection something else still holds (none can, today) is closed when that
270
+ * ends instead of staying open. The handle is freed only once the close
271
+ * succeeds, so a close that fails leaves the connection usable and its message
272
+ * readable. */
164
273
  int32_t nishsqlite_close(int32_t h) {
165
- sqlite3 *db = db_of(h);
166
- if (db == NULL) return SQLITE_MISUSE;
274
+ nishsqlite_conn *c = conn_of(h);
275
+ if (c == NULL) return SQLITE_MISUSE;
276
+ sqlite3 *db = c->db;
277
+ cursors_invalidate(c);
278
+ shapes_clear(c);
279
+ sqlite3_finalize(c->begin_st);
280
+ sqlite3_finalize(c->schema_st);
281
+ sqlite3_finalize(c->commit_st);
167
282
  nishsqlite_table *t = &nishsqlite_stmts;
168
283
  for (int32_t i = 1; i < t->len; i++) {
169
284
  if (t->at[i].p != NULL && t->at[i].owner == h) {
@@ -172,13 +287,20 @@ int32_t nishsqlite_close(int32_t h) {
172
287
  }
173
288
  }
174
289
  int rc = sqlite3_close_v2(db);
175
- if (rc == SQLITE_OK) slot_give(&nishsqlite_dbs, h);
290
+ if (rc == SQLITE_OK) {
291
+ slot_give(&nishsqlite_dbs, h);
292
+ free(c);
293
+ }
176
294
  return rc;
177
295
  }
178
296
 
297
+ /* Invalidates the connection's cursors first: exec answers no rows, so a plain
298
+ * read through it has no use, and it runs `BEGIN`, `COMMIT` and `ROLLBACK`. */
179
299
  int32_t nishsqlite_exec(int32_t h, const char *sql) {
180
- sqlite3 *db = db_of(h);
181
- return db ? sqlite3_exec(db, sql, NULL, NULL, NULL) : SQLITE_MISUSE;
300
+ nishsqlite_conn *c = conn_of(h);
301
+ if (c == NULL) return SQLITE_MISUSE;
302
+ cursors_invalidate(c);
303
+ return sqlite3_exec(c->db, sql, NULL, NULL, NULL);
182
304
  }
183
305
 
184
306
  /* The connection's message for its last failure, or SQLITE_MISUSE's own for
@@ -202,16 +324,25 @@ int64_t nishsqlite_changes(int32_t h) {
202
324
 
203
325
  /* A statement handle for the first statement of `sql`, or the negated code.
204
326
  * Text with no statement in it, only space or comments, is SQLITE_MISUSE:
205
- * SQLite answers OK and no statement, which leaves nothing to hand back. */
327
+ * SQLite answers OK and no statement, which leaves nothing to hand back. The
328
+ * authorizer classifies the statement while it is prepared: it is plain when
329
+ * it authorized SQLITE_SELECT and nothing off the allowlist. */
206
330
  int32_t nishsqlite_prepare(int32_t h, const char *sql) {
207
- sqlite3 *db = db_of(h);
208
- if (db == NULL) return -SQLITE_MISUSE;
331
+ nishsqlite_conn *c = conn_of(h);
332
+ if (c == NULL) return -SQLITE_MISUSE;
209
333
  sqlite3_stmt *st = NULL;
210
- int rc = sqlite3_prepare_v3(db, sql, -1, SQLITE_PREPARE_PERSISTENT, &st, NULL);
334
+ c->classifying = 1;
335
+ c->seen_select = 0;
336
+ c->seen_other = 0;
337
+ int rc = sqlite3_prepare_v3(c->db, sql, -1, SQLITE_PREPARE_PERSISTENT, &st, NULL);
338
+ c->classifying = 0;
211
339
  if (rc != SQLITE_OK) return -rc;
212
340
  if (st == NULL) return -SQLITE_MISUSE;
213
341
  int32_t s = slot_take(&nishsqlite_stmts, st, h);
214
- if (s != 0) return s;
342
+ if (s != 0) {
343
+ if (c->seen_select && !c->seen_other) nishsqlite_stmts.at[s & NISH_SQLITE_INDEX].flags = NISH_SQLITE_PLAIN;
344
+ return s;
345
+ }
215
346
  sqlite3_finalize(st);
216
347
  return -SQLITE_NOMEM;
217
348
  }
@@ -230,9 +361,16 @@ int32_t nishsqlite_finalize(int32_t h) {
230
361
  return SQLITE_OK;
231
362
  }
232
363
 
364
+ /* Invalidates the connection's cursors before a statement that is not plain
365
+ * steps. */
233
366
  int32_t nishsqlite_step(int32_t h) {
234
- sqlite3_stmt *st = stmt_of(h);
235
- return st ? sqlite3_step(st) : SQLITE_MISUSE;
367
+ nishsqlite_slot *s = slot_of(&nishsqlite_stmts, h);
368
+ if (s == NULL) return SQLITE_MISUSE;
369
+ if (!(s->flags & NISH_SQLITE_PLAIN)) {
370
+ nishsqlite_conn *c = conn_of(s->owner);
371
+ if (c->ncursors != 0) cursors_invalidate(c);
372
+ }
373
+ return sqlite3_step((sqlite3_stmt *)s->p);
236
374
  }
237
375
 
238
376
  /* SQLite's reset answers the last step's failure again; the program has seen
@@ -357,3 +495,776 @@ int32_t nishsqlite_column_into(int32_t h, int32_t c, uint8_t *buf, uint64_t n, i
357
495
  if (p != NULL && (uint64_t)len <= n - (uint64_t)at) memcpy(buf + at, p, (size_t)len);
358
496
  return len;
359
497
  }
498
+
499
+ /* ---- Cursors ------------------------------------------------------------ */
500
+
501
+ /* A cursor reads one table or index of `main` through SQLite's own B-tree
502
+ * cursor (`sqlite3BtreeCursor`) and record decoder (`sqlite3VdbeRecordUnpack`),
503
+ * inside a read transaction `nishsqlite_begin_read` opened. Nothing here reads
504
+ * the file format or writes a field of SQLite's structures that its functions
505
+ * do not take: the cursor, the KeyInfo, the decoded row and the seek key are
506
+ * all made by SQLite's functions. The fields set by hand are the ones of the
507
+ * UnpackedRecord a seek passes in, which is how SQLite's own VDBE builds one,
508
+ * and a KeyInfo's `aSortFlags` entry for a DESC key column, which is how
509
+ * SQLite's own `sqlite3KeyInfoOfIndex` fills it (docs/sqlite-cursor.md, "What
510
+ * the adapter calls").
511
+ *
512
+ * A cursor belongs to its connection (the slot's owner) and lives until the
513
+ * program closes it, `nishsqlite_end_read`, or anything that could change what
514
+ * it reads: a statement that is not plain stepping, `nishsqlite_exec`, the
515
+ * authorizer seeing an action off its allowlist, or the transaction ending
516
+ * under it (`cursor_of`). Invalidating frees the cursor and its slot, so its
517
+ * handle answers SQLITE_MISUSE from then on. The moves and reads allocate
518
+ * nothing once the first row has been read: the decoded row and the copy
519
+ * buffer are the cursor's and are reused. */
520
+
521
+ #define NISH_SQLITE_SEEK_GE 1
522
+ #define NISH_SQLITE_SEEK_GT 2
523
+ #define NISH_SQLITE_SEEK_LE 3
524
+ #define NISH_SQLITE_SEEK_LT 4
525
+
526
+ /* Bytes past a copied record that are kept zeroed: on a corrupt record the
527
+ * decoder can read a varint and an 8-byte value past its end. 18 is the
528
+ * padding `sqlite3BtreeIndexMoveto` gives the copy it decodes (`nOverrun`). */
529
+ #define NISH_SQLITE_SLACK 18
530
+
531
+ typedef struct nishsqlite_cursor {
532
+ nishsqlite_conn *conn;
533
+ Btree *btree; /* `main`, from sqlite3DbNameToBtree */
534
+ BtCursor *bt; /* in the same block, after this struct */
535
+ KeyInfo *ki; /* the record's fields, for the decoder and a seek */
536
+ UnpackedRecord *row; /* the current row, decoded on the first read of it */
537
+ Mem *key; /* the seek key's `nkeyfields` values, in the block */
538
+ int32_t nkeyparts; /* how many of them are set */
539
+ int32_t nkeyfields; /* an index's key columns; a table's columns */
540
+ u8 *buf; /* a record that is not all on its page, copied */
541
+ u32 cap;
542
+ int32_t ncol; /* columns the program reads: a table's, or an index's key and rowid */
543
+ int32_t alias; /* a table's INTEGER PRIMARY KEY column, -1 when none */
544
+ int32_t is_index;
545
+ int32_t has_row; /* the last move answered a row */
546
+ int32_t unpacked; /* `row` holds the current row */
547
+ int32_t nfields; /* the fields the current row's record holds */
548
+ } nishsqlite_cursor;
549
+
550
+ static void cursor_free(nishsqlite_cursor *cur) {
551
+ sqlite3 *db = cur->conn->db;
552
+ sqlite3BtreeCloseCursor(cur->bt);
553
+ for (int32_t i = 0; i < cur->nkeyfields; i++) sqlite3VdbeMemRelease(&cur->key[i]);
554
+ if (cur->row) sqlite3DbFree(db, cur->row);
555
+ sqlite3KeyInfoUnref(cur->ki);
556
+ sqlite3_free(cur->buf);
557
+ sqlite3_free(cur);
558
+ }
559
+
560
+ static void cursors_invalidate(nishsqlite_conn *c) {
561
+ if (c->ncursors == 0) return;
562
+ sqlite3_mutex *mx = sqlite3_db_mutex(c->db);
563
+ sqlite3_mutex_enter(mx);
564
+ nishsqlite_table *t = &nishsqlite_cursors;
565
+ for (int32_t i = 1; i < t->len; i++) {
566
+ nishsqlite_slot *s = &t->at[i];
567
+ if (s->p == NULL || s->owner != c->self) continue;
568
+ cursor_free(s->p);
569
+ slot_give(t, (s->gen << 16) | i);
570
+ }
571
+ c->ncursors = 0;
572
+ sqlite3_mutex_leave(mx);
573
+ }
574
+
575
+ /* The cursor `h` names, or NULL. A cursor whose transaction has ended, by
576
+ * whatever route, is invalidated here with every other cursor of its
577
+ * connection before anything reads it. */
578
+ static inline nishsqlite_cursor *cursor_of(int32_t h) {
579
+ nishsqlite_slot *s = slot_of(&nishsqlite_cursors, h);
580
+ if (s == NULL) return NULL;
581
+ nishsqlite_cursor *cur = s->p;
582
+ if (sqlite3_get_autocommit(cur->conn->db) || sqlite3BtreeTxnState(cur->btree) == SQLITE_TXN_NONE) {
583
+ cursors_invalidate(cur->conn);
584
+ return NULL;
585
+ }
586
+ return cur;
587
+ }
588
+
589
+ /* Runs the adapter's own SQL, which the authorizer lets through unwatched. */
590
+ static int internal_exec(nishsqlite_conn *c, const char *sql) {
591
+ c->internal = 1;
592
+ int rc = sqlite3_exec(c->db, sql, NULL, NULL, NULL);
593
+ c->internal = 0;
594
+ return rc;
595
+ }
596
+
597
+ static int internal_prepare(nishsqlite_conn *c, const char *sql, const char *arg, sqlite3_stmt **st) {
598
+ c->internal = 1;
599
+ int rc = sqlite3_prepare_v2(c->db, sql, -1, st, NULL);
600
+ if (rc == SQLITE_OK && arg) rc = sqlite3_bind_text(*st, 1, arg, -1, SQLITE_TRANSIENT);
601
+ c->internal = 0;
602
+ return rc;
603
+ }
604
+
605
+ static int internal_step(nishsqlite_conn *c, sqlite3_stmt *st) {
606
+ c->internal = 1;
607
+ int rc = sqlite3_step(st);
608
+ c->internal = 0;
609
+ return rc;
610
+ }
611
+
612
+ /* Runs `sql` to its end as the adapter's own SQL, through the statement kept
613
+ * in `*st`: prepared the first time, reset after each run so it holds no
614
+ * lock. A schema change re-prepares it inside `sqlite3_step`, under the same
615
+ * `internal` flag. */
616
+ static int internal_run(nishsqlite_conn *c, sqlite3_stmt **st, const char *sql) {
617
+ c->internal = 1;
618
+ int rc = *st ? SQLITE_OK : sqlite3_prepare_v3(c->db, sql, -1, SQLITE_PREPARE_PERSISTENT, st, NULL);
619
+ if (rc == SQLITE_OK) {
620
+ rc = sqlite3_step(*st);
621
+ while (rc == SQLITE_ROW) rc = sqlite3_step(*st);
622
+ rc = rc == SQLITE_DONE ? SQLITE_OK : rc;
623
+ sqlite3_reset(*st);
624
+ }
625
+ c->internal = 0;
626
+ return rc;
627
+ }
628
+
629
+ static int main_in_read(sqlite3 *db) {
630
+ return !sqlite3_get_autocommit(db) && sqlite3_txn_state(db, "main") >= SQLITE_TXN_READ;
631
+ }
632
+
633
+ /* Opens a read transaction on `main`: BEGIN, then a read of the schema table,
634
+ * which is what takes the read lock (BEGIN alone defers it). The transaction
635
+ * is the snapshot every cursor of the connection reads until
636
+ * `nishsqlite_end_read`. A transaction already open is SQLITE_MISUSE. */
637
+ int32_t nishsqlite_begin_read(int32_t h) {
638
+ nishsqlite_conn *c = conn_of(h);
639
+ if (c == NULL || !sqlite3_get_autocommit(c->db)) return SQLITE_MISUSE;
640
+ cursors_invalidate(c);
641
+ int rc = internal_run(c, &c->begin_st, "BEGIN");
642
+ if (rc != SQLITE_OK) return rc;
643
+ rc = internal_run(c, &c->schema_st, "SELECT 1 FROM main.sqlite_schema LIMIT 1");
644
+ if (rc == SQLITE_OK && !main_in_read(c->db)) rc = SQLITE_ERROR;
645
+ if (rc != SQLITE_OK && !sqlite3_get_autocommit(c->db)) internal_exec(c, "ROLLBACK");
646
+ return rc;
647
+ }
648
+
649
+ /* Closes the connection's cursors and commits the transaction. Outside one it
650
+ * is SQLITE_MISUSE. */
651
+ int32_t nishsqlite_end_read(int32_t h) {
652
+ nishsqlite_conn *c = conn_of(h);
653
+ if (c == NULL || sqlite3_get_autocommit(c->db)) return SQLITE_MISUSE;
654
+ cursors_invalidate(c);
655
+ return internal_run(c, &c->commit_st, "COMMIT");
656
+ }
657
+
658
+ /* Appends `name` to the expected column list, after a comma unless first.
659
+ * The list joins names unescaped, so a name it could not spell apart is
660
+ * SQLITE_SCHEMA: one holding a comma, or ending in " DESC" (which reads as a
661
+ * descending key column). */
662
+ static int columns_add(sqlite3_str *want, const char *name, int first) {
663
+ if (name == NULL) return SQLITE_SCHEMA;
664
+ size_t len = 0;
665
+ for (; name[len] != 0; len++)
666
+ if (name[len] == ',') return SQLITE_SCHEMA;
667
+ if (len >= 5 && strcmp(name + len - 5, " DESC") == 0) return SQLITE_SCHEMA;
668
+ if (!first) sqlite3_str_appendchar(want, 1, ',');
669
+ sqlite3_str_appendall(want, name);
670
+ return SQLITE_OK;
671
+ }
672
+
673
+ /* Reads what `cursor_open` checks of a table: its columns as the list the
674
+ * program must name, the INTEGER PRIMARY KEY column, and the column count.
675
+ * SQLITE_SCHEMA for a table this adapter cannot read: a hidden or generated
676
+ * column, or a column name the list cannot spell (`columns_add`). */
677
+ static int table_shape(nishsqlite_conn *c, const char *table, sqlite3_str *want, int32_t *ncol,
678
+ int32_t *alias) {
679
+ sqlite3_stmt *st = NULL;
680
+ int rc = internal_prepare(c, "SELECT name, hidden, pk FROM pragma_table_xinfo(?1, 'main')", table, &st);
681
+ int32_t n = 0, npk = 0, pk = -1;
682
+ while (rc == SQLITE_OK && (rc = internal_step(c, st)) == SQLITE_ROW) {
683
+ if (sqlite3_column_int(st, 1) != 0) rc = SQLITE_SCHEMA;
684
+ else {
685
+ if (sqlite3_column_int(st, 2) != 0) npk++, pk = n;
686
+ rc = columns_add(want, (const char *)sqlite3_column_text(st, 0), n == 0);
687
+ n++;
688
+ }
689
+ }
690
+ sqlite3_finalize(st);
691
+ if (rc != SQLITE_DONE) return rc == SQLITE_OK ? SQLITE_SCHEMA : rc;
692
+ if (n == 0) return SQLITE_SCHEMA;
693
+ /* One primary-key column is a rowid alias unless the table made an index
694
+ * for it, which only a primary key that is not INTEGER PRIMARY KEY does. */
695
+ int32_t has_pk_index = 0;
696
+ rc = internal_prepare(c, "SELECT 1 FROM pragma_index_list(?1, 'main') WHERE origin = 'pk'", table, &st);
697
+ if (rc == SQLITE_OK) {
698
+ rc = internal_step(c, st);
699
+ has_pk_index = rc == SQLITE_ROW;
700
+ rc = rc == SQLITE_ROW || rc == SQLITE_DONE ? SQLITE_OK : rc;
701
+ }
702
+ sqlite3_finalize(st);
703
+ if (rc != SQLITE_OK) return rc;
704
+ *ncol = n;
705
+ *alias = npk == 1 && !has_pk_index ? pk : -1;
706
+ return SQLITE_OK;
707
+ }
708
+
709
+ /* Reads what `cursor_open` checks of an index: its key columns, each with
710
+ * " DESC" when descending, then "rowid", and the key's width. SQLITE_SCHEMA
711
+ * for an index this adapter cannot read: one on an expression, with a
712
+ * collation that is not BINARY, on a column name the list cannot spell, or
713
+ * whose record is not the key and a rowid. */
714
+ static int index_shape(nishsqlite_conn *c, const char *index, sqlite3_str *want, int32_t *nkey,
715
+ KeyInfo *ki) {
716
+ sqlite3_stmt *st = NULL;
717
+ int rc = internal_prepare(c, "SELECT cid, name, desc, coll, key FROM pragma_index_xinfo(?1, 'main')",
718
+ index, &st);
719
+ int32_t n = 0, naux = 0;
720
+ while (rc == SQLITE_OK && (rc = internal_step(c, st)) == SQLITE_ROW) {
721
+ rc = SQLITE_OK;
722
+ int cid = sqlite3_column_int(st, 0);
723
+ const char *name = (const char *)sqlite3_column_text(st, 1);
724
+ if (sqlite3_column_int(st, 4) != 0) {
725
+ const char *coll = (const char *)sqlite3_column_text(st, 3);
726
+ if (naux != 0 || cid < 0 || name == NULL || coll == NULL || strcmp(coll, "BINARY") != 0) {
727
+ rc = SQLITE_SCHEMA;
728
+ break;
729
+ }
730
+ if (ki) {
731
+ if (n >= ki->nKeyField) {
732
+ rc = SQLITE_SCHEMA;
733
+ break;
734
+ }
735
+ if (sqlite3_column_int(st, 2) != 0) ki->aSortFlags[n] = KEYINFO_ORDER_DESC;
736
+ }
737
+ if ((rc = columns_add(want, name, n == 0)) != SQLITE_OK) break;
738
+ if (sqlite3_column_int(st, 2) != 0) sqlite3_str_appendall(want, " DESC");
739
+ n++;
740
+ } else if (cid != -1 || naux++ != 0) {
741
+ rc = SQLITE_SCHEMA;
742
+ break;
743
+ }
744
+ }
745
+ sqlite3_finalize(st);
746
+ if (rc != SQLITE_DONE) return rc == SQLITE_OK || rc == SQLITE_ROW ? SQLITE_SCHEMA : rc;
747
+ if (n == 0 || naux != 1) return SQLITE_SCHEMA;
748
+ (void)columns_add(want, "rowid", 0);
749
+ *nkey = n;
750
+ return SQLITE_OK;
751
+ }
752
+
753
+ /* Looks `name` up in main's schema: whether it is a table or an index, its
754
+ * root page, and the table it belongs to (written to `table`, which the
755
+ * caller frees with sqlite3_free). Anything but an ordinary table of rowids
756
+ * or an index of one is SQLITE_SCHEMA. */
757
+ static int object_of(nishsqlite_conn *c, const char *name, int32_t *is_index, Pgno *root, char **table) {
758
+ sqlite3_stmt *st = NULL;
759
+ int rc = internal_prepare(c, "SELECT type, rootpage, tbl_name FROM main.sqlite_schema WHERE name = ?1",
760
+ name, &st);
761
+ if (rc == SQLITE_OK) {
762
+ rc = internal_step(c, st);
763
+ if (rc == SQLITE_ROW) {
764
+ const char *type = (const char *)sqlite3_column_text(st, 0);
765
+ sqlite3_int64 page = sqlite3_column_int64(st, 1);
766
+ const char *tbl = (const char *)sqlite3_column_text(st, 2);
767
+ int idx = type && strcmp(type, "index") == 0;
768
+ if ((idx || (type && strcmp(type, "table") == 0)) && page > 0 && page <= 0xffffffffLL && tbl) {
769
+ *is_index = idx;
770
+ *root = (Pgno)page;
771
+ *table = sqlite3_mprintf("%s", tbl);
772
+ rc = *table ? SQLITE_OK : SQLITE_NOMEM;
773
+ } else {
774
+ rc = SQLITE_SCHEMA;
775
+ }
776
+ } else if (rc == SQLITE_DONE) {
777
+ rc = SQLITE_SCHEMA;
778
+ }
779
+ }
780
+ sqlite3_finalize(st);
781
+ if (rc != SQLITE_OK) return rc;
782
+ /* A WITHOUT ROWID table, a virtual table or a view is not a table of rowids;
783
+ * `wr` is 1 for WITHOUT ROWID. */
784
+ rc = internal_prepare(c, "SELECT type, wr FROM pragma_table_list WHERE schema = 'main' AND name = ?1", *table, &st);
785
+ if (rc == SQLITE_OK) {
786
+ rc = internal_step(c, st);
787
+ if (rc == SQLITE_ROW) {
788
+ const char *type = (const char *)sqlite3_column_text(st, 0);
789
+ rc = type && strcmp(type, "table") == 0 && sqlite3_column_int(st, 1) == 0 ? SQLITE_OK : SQLITE_SCHEMA;
790
+ } else if (rc == SQLITE_DONE) {
791
+ rc = SQLITE_SCHEMA;
792
+ }
793
+ }
794
+ sqlite3_finalize(st);
795
+ if (rc != SQLITE_OK) {
796
+ sqlite3_free(*table);
797
+ *table = NULL;
798
+ }
799
+ return rc;
800
+ }
801
+
802
+ /* The encoding of `main` is UTF-8: the cursor's reads answer the stored bytes
803
+ * as they are, so text in any other encoding is refused at open. */
804
+ static int main_is_utf8(nishsqlite_conn *c) {
805
+ sqlite3_stmt *st = NULL;
806
+ int rc = internal_prepare(c, "PRAGMA main.encoding", NULL, &st);
807
+ if (rc == SQLITE_OK) {
808
+ rc = internal_step(c, st);
809
+ const char *enc = rc == SQLITE_ROW ? (const char *)sqlite3_column_text(st, 0) : NULL;
810
+ rc = rc == SQLITE_ROW ? (enc && strcmp(enc, "UTF-8") == 0 ? SQLITE_OK : SQLITE_SCHEMA) : rc;
811
+ }
812
+ sqlite3_finalize(st);
813
+ return rc;
814
+ }
815
+
816
+ /* Builds a cursor on `name`, a table or index of `main`, once its columns are
817
+ * the ones `columns` names, in order, joined by ",": a table's columns, or an
818
+ * index's key columns (each followed by " DESC" when descending) and then
819
+ * "rowid". Answers its handle, or SQLITE_MISUSE outside a read transaction,
820
+ * SQLITE_SCHEMA when the object is not there, is not one a cursor reads, or
821
+ * has other columns, and SQLITE_NOMEM, all negated. */
822
+ static int32_t cursor_build(nishsqlite_conn *c, const char *name, const char *columns) {
823
+ sqlite3 *db = c->db;
824
+ int32_t is_index = 0, ncol = 0, alias = -1, nkey = 0;
825
+ Pgno root = 0;
826
+ char *table = NULL;
827
+ KeyInfo *ki = NULL;
828
+ /* A read transaction's cookie, and a shape checked under it. */
829
+ u32 cookie = 0;
830
+ int cacheable = sqlite3_txn_state(db, "main") == SQLITE_TXN_READ;
831
+ if (cacheable) sqlite3BtreeGetMeta(sqlite3DbNameToBtree(db, "main"), BTREE_SCHEMA_VERSION, &cookie);
832
+ for (int32_t i = 0; cacheable && i < NISH_SQLITE_SHAPES; i++) {
833
+ nishsqlite_shape *s = &c->shapes[i];
834
+ if (s->name && s->cookie == cookie && strcmp(s->name, name) == 0 && strcmp(s->columns, columns) == 0) {
835
+ is_index = s->is_index;
836
+ ncol = s->ncol;
837
+ nkey = s->nkey;
838
+ alias = s->alias;
839
+ root = s->root;
840
+ ki = sqlite3KeyInfoRef(s->ki);
841
+ goto build;
842
+ }
843
+ }
844
+ int rc = main_is_utf8(c);
845
+ if (rc == SQLITE_OK) rc = object_of(c, name, &is_index, &root, &table);
846
+ sqlite3_str *want = sqlite3_str_new(db);
847
+ if (rc == SQLITE_OK && !is_index) {
848
+ rc = table_shape(c, table, want, &ncol, &alias);
849
+ if (rc == SQLITE_OK && (ki = sqlite3KeyInfoAlloc(db, ncol, 0)) == NULL) rc = SQLITE_NOMEM;
850
+ } else if (rc == SQLITE_OK) {
851
+ /* The width first, so the KeyInfo can be made to it; then again into it. */
852
+ rc = index_shape(c, name, want, &nkey, NULL);
853
+ if (rc == SQLITE_OK) {
854
+ sqlite3_str_reset(want);
855
+ ki = sqlite3KeyInfoAlloc(db, nkey, 1);
856
+ rc = ki ? index_shape(c, name, want, &nkey, ki) : SQLITE_NOMEM;
857
+ ncol = nkey + 1;
858
+ }
859
+ }
860
+ sqlite3_free(table);
861
+ if (rc == SQLITE_OK && sqlite3_str_errcode(want) != SQLITE_OK) rc = SQLITE_NOMEM;
862
+ if (rc == SQLITE_OK && strcmp(sqlite3_str_value(want) ? sqlite3_str_value(want) : "", columns) != 0)
863
+ rc = SQLITE_SCHEMA;
864
+ sqlite3_free(sqlite3_str_finish(want));
865
+ if (rc == SQLITE_OK && !main_in_read(db)) rc = SQLITE_MISUSE;
866
+ if (rc != SQLITE_OK) {
867
+ sqlite3KeyInfoUnref(ki);
868
+ return -rc;
869
+ }
870
+ if (cacheable) {
871
+ nishsqlite_shape *s = &c->shapes[c->shape_next];
872
+ char *n = sqlite3_mprintf("%s", name), *cols = sqlite3_mprintf("%s", columns);
873
+ if (n && cols) {
874
+ sqlite3_free(s->name);
875
+ sqlite3_free(s->columns);
876
+ sqlite3KeyInfoUnref(s->ki);
877
+ *s = (nishsqlite_shape){n, cols, cookie, is_index, ncol, nkey, alias, root, sqlite3KeyInfoRef(ki)};
878
+ c->shape_next = (c->shape_next + 1) % NISH_SQLITE_SHAPES;
879
+ } else {
880
+ sqlite3_free(n);
881
+ sqlite3_free(cols);
882
+ }
883
+ }
884
+
885
+ build:;
886
+ int32_t nkeyfields = is_index ? nkey : ncol;
887
+ size_t head = ROUND8(sizeof(nishsqlite_cursor));
888
+ size_t btsz = ROUND8((size_t)sqlite3BtreeCursorSize());
889
+ nishsqlite_cursor *cur = sqlite3_malloc64(head + btsz + (size_t)nkeyfields * sizeof(Mem));
890
+ if (cur == NULL) {
891
+ sqlite3KeyInfoUnref(ki);
892
+ return -SQLITE_NOMEM;
893
+ }
894
+ memset(cur, 0, head);
895
+ cur->conn = c;
896
+ cur->btree = sqlite3DbNameToBtree(db, "main");
897
+ cur->bt = (BtCursor *)((u8 *)cur + head);
898
+ sqlite3BtreeCursorZero(cur->bt);
899
+ cur->ki = ki;
900
+ cur->key = (Mem *)((u8 *)cur + head + btsz);
901
+ cur->nkeyfields = nkeyfields;
902
+ for (int32_t i = 0; i < nkeyfields; i++) sqlite3VdbeMemInit(&cur->key[i], db, MEM_Null);
903
+ cur->ncol = ncol;
904
+ cur->alias = alias;
905
+ cur->is_index = is_index;
906
+ cur->row = sqlite3VdbeAllocUnpackedRecord(ki);
907
+ rc = cur->row ? SQLITE_OK : SQLITE_NOMEM;
908
+ if (rc == SQLITE_OK) rc = sqlite3BtreeCursor(cur->btree, root, 0, is_index ? ki : NULL, cur->bt);
909
+ int32_t hc = rc == SQLITE_OK ? slot_take(&nishsqlite_cursors, cur, c->self) : 0;
910
+ if (hc == 0) {
911
+ cursor_free(cur);
912
+ return -(rc == SQLITE_OK ? SQLITE_NOMEM : rc);
913
+ }
914
+ c->ncursors++;
915
+ return hc;
916
+ }
917
+
918
+ static int32_t unlocked_cursor_open(int32_t h, const char *name, const char *columns) {
919
+ nishsqlite_conn *c = conn_of(h);
920
+ if (c == NULL || !main_in_read(c->db)) return -SQLITE_MISUSE;
921
+ return cursor_build(c, name, columns);
922
+ }
923
+
924
+ static int32_t unlocked_cursor_close(int32_t h) {
925
+ nishsqlite_cursor *cur = cursor_of(h);
926
+ if (cur == NULL) return SQLITE_MISUSE;
927
+ cur->conn->ncursors--;
928
+ cursor_free(cur);
929
+ slot_give(&nishsqlite_cursors, h);
930
+ return SQLITE_OK;
931
+ }
932
+
933
+ /* ---- Moves -------------------------------------------------------------- */
934
+
935
+ /* A move answers 1 when the cursor is on a row, 0 when there is none, and the
936
+ * negated code when SQLite fails (a corrupt page, an I/O error). */
937
+ static int32_t moved(nishsqlite_cursor *cur, int rc, int row) {
938
+ cur->unpacked = 0;
939
+ cur->has_row = rc == SQLITE_OK && row;
940
+ return rc == SQLITE_OK ? cur->has_row : -rc;
941
+ }
942
+
943
+ static int32_t unlocked_cursor_first(int32_t h) {
944
+ nishsqlite_cursor *cur = cursor_of(h);
945
+ if (cur == NULL) return -SQLITE_MISUSE;
946
+ int empty = 1;
947
+ int rc = sqlite3BtreeFirst(cur->bt, &empty);
948
+ return moved(cur, rc, !empty);
949
+ }
950
+
951
+ static int32_t unlocked_cursor_last(int32_t h) {
952
+ nishsqlite_cursor *cur = cursor_of(h);
953
+ if (cur == NULL) return -SQLITE_MISUSE;
954
+ int empty = 1;
955
+ int rc = sqlite3BtreeLast(cur->bt, &empty);
956
+ return moved(cur, rc, !empty);
957
+ }
958
+
959
+ /* SQLITE_DONE from a step is the end of the table, not a failure. */
960
+ static int32_t stepped(nishsqlite_cursor *cur, int rc) {
961
+ return rc == SQLITE_DONE ? moved(cur, SQLITE_OK, 0) : moved(cur, rc, 1);
962
+ }
963
+
964
+ /* Next and previous need a row to move from: with none they are
965
+ * SQLITE_MISUSE, so a loop cannot run past its end and restart. */
966
+ static int32_t unlocked_cursor_next(int32_t h) {
967
+ nishsqlite_cursor *cur = cursor_of(h);
968
+ if (cur == NULL || !cur->has_row) return -SQLITE_MISUSE;
969
+ return stepped(cur, sqlite3BtreeNext(cur->bt, 0));
970
+ }
971
+
972
+ static int32_t unlocked_cursor_previous(int32_t h) {
973
+ nishsqlite_cursor *cur = cursor_of(h);
974
+ if (cur == NULL || !cur->has_row) return -SQLITE_MISUSE;
975
+ return stepped(cur, sqlite3BtreePrevious(cur->bt, 0));
976
+ }
977
+
978
+ /* Moves a table cursor to the row `rowid`: 1 when it is there, 0 when not.
979
+ * An index cursor is SQLITE_MISUSE. */
980
+ static int32_t unlocked_cursor_seek_rowid(int32_t h, int64_t rowid) {
981
+ nishsqlite_cursor *cur = cursor_of(h);
982
+ if (cur == NULL || cur->is_index) return -SQLITE_MISUSE;
983
+ int res = -1;
984
+ int rc = sqlite3BtreeTableMoveto(cur->bt, rowid, 0, &res);
985
+ return moved(cur, rc, res == 0);
986
+ }
987
+
988
+ /* ---- Seek keys ---------------------------------------------------------- */
989
+
990
+ /* The index cursor `h` with room for one more key part, or NULL with `*rc`
991
+ * saying why. The caller sets `cur->key[cur->nkeyparts]` and counts it only
992
+ * when the set succeeds, so a failed part leaves the key as it was. */
993
+ static nishsqlite_cursor *key_next(int32_t h, int32_t *rc) {
994
+ nishsqlite_cursor *cur = cursor_of(h);
995
+ *rc = cur == NULL || !cur->is_index ? SQLITE_MISUSE : SQLITE_RANGE;
996
+ if (cur == NULL || !cur->is_index || cur->nkeyparts >= cur->nkeyfields) return NULL;
997
+ *rc = SQLITE_OK;
998
+ return cur;
999
+ }
1000
+
1001
+ static int32_t unlocked_key_reset(int32_t h) {
1002
+ nishsqlite_cursor *cur = cursor_of(h);
1003
+ if (cur == NULL || !cur->is_index) return SQLITE_MISUSE;
1004
+ for (int32_t i = 0; i < cur->nkeyparts; i++) sqlite3VdbeMemSetNull(&cur->key[i]);
1005
+ cur->nkeyparts = 0;
1006
+ return SQLITE_OK;
1007
+ }
1008
+
1009
+ static int32_t unlocked_key_i64(int32_t h, int64_t v) {
1010
+ int32_t rc;
1011
+ nishsqlite_cursor *cur = key_next(h, &rc);
1012
+ if (cur) sqlite3VdbeMemSetInt64(&cur->key[cur->nkeyparts++], v);
1013
+ return rc;
1014
+ }
1015
+
1016
+ /* Text values are copied into the key (SQLITE_TRANSIENT), as a bind is. */
1017
+ static int32_t unlocked_key_text(int32_t h, const char *text) {
1018
+ int32_t rc;
1019
+ nishsqlite_cursor *cur = key_next(h, &rc);
1020
+ if (cur) rc = sqlite3VdbeMemSetStr(&cur->key[cur->nkeyparts], text, -1, SQLITE_UTF8, SQLITE_TRANSIENT);
1021
+ if (cur && rc == SQLITE_OK) cur->nkeyparts++;
1022
+ return rc;
1023
+ }
1024
+
1025
+ /* `buf[off, off + len)` as text, `n` the buffer's length; a window outside
1026
+ * the buffer is SQLITE_MISUSE, as `nishsqlite_bind_bytes` answers. */
1027
+ static int32_t unlocked_key_bytes(int32_t h, const uint8_t *buf, uint64_t n, int32_t off, int32_t len) {
1028
+ if (off < 0 || len < 0 || (uint64_t)off + (uint64_t)len > n) return SQLITE_MISUSE;
1029
+ int32_t rc;
1030
+ nishsqlite_cursor *cur = key_next(h, &rc);
1031
+ const char *p = len == 0 ? "" : (const char *)(buf + off);
1032
+ if (cur) rc = sqlite3VdbeMemSetStr(&cur->key[cur->nkeyparts], p, len, SQLITE_UTF8, SQLITE_TRANSIENT);
1033
+ if (cur && rc == SQLITE_OK) cur->nkeyparts++;
1034
+ return rc;
1035
+ }
1036
+
1037
+ /* Moves an index cursor to the first entry at or past the key (`op` GE or
1038
+ * GT), or the last at or before it (LE or LT), comparing only the key's
1039
+ * values, so a key shorter than the index is a prefix. This is the VDBE's
1040
+ * OP_SeekGE/GT/LE/LT: the record's default answer for an equal prefix decides
1041
+ * which side of the equal run the B-tree lands on, and one step corrects it. */
1042
+ static int32_t unlocked_cursor_seek(int32_t h, int32_t op) {
1043
+ nishsqlite_cursor *cur = cursor_of(h);
1044
+ if (cur == NULL || !cur->is_index || cur->nkeyparts < 1 || op < NISH_SQLITE_SEEK_GE ||
1045
+ op > NISH_SQLITE_SEEK_LT)
1046
+ return -SQLITE_MISUSE;
1047
+ UnpackedRecord key;
1048
+ memset(&key, 0, sizeof key);
1049
+ key.pKeyInfo = cur->ki;
1050
+ key.aMem = cur->key;
1051
+ key.nField = (u16)cur->nkeyparts;
1052
+ key.default_rc = op == NISH_SQLITE_SEEK_GT || op == NISH_SQLITE_SEEK_LE ? -1 : 1;
1053
+ int res = 0;
1054
+ int rc = sqlite3BtreeIndexMoveto(cur->bt, &key, &res);
1055
+ if (rc != SQLITE_OK) return moved(cur, rc, 0);
1056
+ if (op == NISH_SQLITE_SEEK_GE || op == NISH_SQLITE_SEEK_GT) {
1057
+ if (res < 0 || (res == 0 && op == NISH_SQLITE_SEEK_GT)) return stepped(cur, sqlite3BtreeNext(cur->bt, 0));
1058
+ return moved(cur, SQLITE_OK, 1);
1059
+ }
1060
+ if (res > 0 || (res == 0 && op == NISH_SQLITE_SEEK_LT)) return stepped(cur, sqlite3BtreePrevious(cur->bt, 0));
1061
+ return moved(cur, SQLITE_OK, !sqlite3BtreeEof(cur->bt));
1062
+ }
1063
+
1064
+ /* ---- Cursor columns ----------------------------------------------------- */
1065
+
1066
+ /* The current row's record decoded into `row`, once per row. A record that
1067
+ * is all on its page is decoded where it lies; one that spills onto overflow
1068
+ * pages is copied whole into the cursor's buffer first, with zeroed slack
1069
+ * past it. SQLITE_MISUSE with no row, SQLITE_CORRUPT for a record longer than
1070
+ * SQLite allows. */
1071
+ static int row_of(nishsqlite_cursor *cur) {
1072
+ if (!cur->has_row) return SQLITE_MISUSE;
1073
+ if (cur->unpacked) return SQLITE_OK;
1074
+ if (sqlite3BtreeCursorHasMoved(cur->bt)) return SQLITE_ABORT;
1075
+ u32 sz = sqlite3BtreePayloadSize(cur->bt);
1076
+ if (sz > SQLITE_MAX_LENGTH) return SQLITE_CORRUPT;
1077
+ cur->nfields = 0;
1078
+ if (sz > 0) {
1079
+ u32 amt = 0;
1080
+ const void *p = sqlite3BtreePayloadFetch(cur->bt, &amt);
1081
+ if (amt < sz) {
1082
+ if (cur->cap < sz + NISH_SQLITE_SLACK) {
1083
+ u64 cap = (u64)cur->cap * 2;
1084
+ if (cap < (u64)sz + NISH_SQLITE_SLACK) cap = (u64)sz + NISH_SQLITE_SLACK;
1085
+ u8 *buf = sqlite3_realloc64(cur->buf, cap);
1086
+ if (buf == NULL) return SQLITE_NOMEM;
1087
+ cur->buf = buf;
1088
+ cur->cap = (u32)cap;
1089
+ }
1090
+ int rc = sqlite3BtreePayload(cur->bt, 0, sz, cur->buf);
1091
+ if (rc != SQLITE_OK) return rc;
1092
+ memset(cur->buf + sz, 0, NISH_SQLITE_SLACK);
1093
+ p = cur->buf;
1094
+ }
1095
+ cur->row->nField = (u16)(cur->nkeyfields + 1);
1096
+ sqlite3VdbeRecordUnpack((int)sz, p, cur->row);
1097
+ cur->nfields = cur->row->nField;
1098
+ }
1099
+ cur->unpacked = 1;
1100
+ return SQLITE_OK;
1101
+ }
1102
+
1103
+ /* Column `n` of the current row: NULL with `*rc` set when it cannot be read.
1104
+ * The INTEGER PRIMARY KEY column is the row's key, not a field of its record,
1105
+ * so it answers NULL with `*alias` set. A row whose record holds fewer fields
1106
+ * than `n` (one written before ALTER TABLE added the column) is SQLITE_SCHEMA. */
1107
+ static Mem *column_mem(int32_t h, int32_t n, nishsqlite_cursor **out, int *alias, int *rc) {
1108
+ nishsqlite_cursor *cur = cursor_of(h);
1109
+ *out = cur;
1110
+ *alias = 0;
1111
+ if (cur == NULL || !cur->has_row) {
1112
+ *rc = SQLITE_MISUSE;
1113
+ return NULL;
1114
+ }
1115
+ if (n < 0 || n >= cur->ncol) {
1116
+ *rc = SQLITE_RANGE;
1117
+ return NULL;
1118
+ }
1119
+ if (n == cur->alias) {
1120
+ *alias = 1;
1121
+ *rc = SQLITE_OK;
1122
+ return NULL;
1123
+ }
1124
+ *rc = row_of(cur);
1125
+ if (*rc != SQLITE_OK) return NULL;
1126
+ if (n >= cur->nfields) {
1127
+ *rc = SQLITE_SCHEMA;
1128
+ return NULL;
1129
+ }
1130
+ return &cur->row->aMem[n];
1131
+ }
1132
+
1133
+ /* The column's type, SQLITE_INTEGER to SQLITE_NULL, or the negated code. The
1134
+ * type is the stored value's: a REAL column holding a whole number stores it
1135
+ * as an integer, and answers SQLITE_INTEGER, where a query would convert it. */
1136
+ static int32_t unlocked_cursor_column_type(int32_t h, int32_t n) {
1137
+ nishsqlite_cursor *cur;
1138
+ int alias, rc;
1139
+ Mem *m = column_mem(h, n, &cur, &alias, &rc);
1140
+ if (alias) return sqlite3BtreeCursorHasMoved(cur->bt) ? -SQLITE_ABORT : SQLITE_INTEGER;
1141
+ return m ? sqlite3_value_type((sqlite3_value *)m) : -rc;
1142
+ }
1143
+
1144
+ /* The column as an integer, converted as `sqlite3_column_int64` converts; 0
1145
+ * when it cannot be read. */
1146
+ static int64_t unlocked_cursor_column_i64(int32_t h, int32_t n) {
1147
+ nishsqlite_cursor *cur;
1148
+ int alias, rc;
1149
+ Mem *m = column_mem(h, n, &cur, &alias, &rc);
1150
+ if (alias) return sqlite3BtreeCursorHasMoved(cur->bt) ? 0 : sqlite3BtreeIntegerKey(cur->bt);
1151
+ return m ? sqlite3_value_int64((sqlite3_value *)m) : 0;
1152
+ }
1153
+
1154
+ /* Copies a TEXT or BLOB column's bytes into `buf` at `at`, `n` the buffer's
1155
+ * length, and answers their length; as `nishsqlite_column_into`, it copies
1156
+ * only when all of them fit. NULL answers 0. An INTEGER or FLOAT column,
1157
+ * the INTEGER PRIMARY KEY column among them, is SQLITE_MISMATCH: the cursor
1158
+ * answers stored bytes and converts no number to text. Codes are negated. */
1159
+ static int32_t unlocked_cursor_column_into(int32_t h, int32_t c, uint8_t *buf, uint64_t n, int32_t at) {
1160
+ if (at < 0 || (uint64_t)at > n) return -SQLITE_MISUSE;
1161
+ nishsqlite_cursor *cur;
1162
+ int alias, rc;
1163
+ Mem *m = column_mem(h, c, &cur, &alias, &rc);
1164
+ if (alias) return -SQLITE_MISMATCH;
1165
+ if (m == NULL) return -rc;
1166
+ int type = sqlite3_value_type((sqlite3_value *)m);
1167
+ if (type == SQLITE_NULL) return 0;
1168
+ if (type != SQLITE_TEXT && type != SQLITE_BLOB) return -SQLITE_MISMATCH;
1169
+ const void *p = sqlite3_value_blob((sqlite3_value *)m);
1170
+ int32_t len = sqlite3_value_bytes((sqlite3_value *)m);
1171
+ if (p != NULL && (uint64_t)len <= n - (uint64_t)at) memcpy(buf + at, p, (size_t)len);
1172
+ return len;
1173
+ }
1174
+
1175
+ /* The current row's rowid: a table row's key, or an index entry's last
1176
+ * field. 0 when there is no row or it cannot be read. */
1177
+ static int64_t unlocked_cursor_rowid(int32_t h) {
1178
+ nishsqlite_cursor *cur = cursor_of(h);
1179
+ if (cur == NULL || !cur->has_row) return 0;
1180
+ if (!cur->is_index) return sqlite3BtreeCursorHasMoved(cur->bt) ? 0 : sqlite3BtreeIntegerKey(cur->bt);
1181
+ if (row_of(cur) != SQLITE_OK || cur->nfields < cur->ncol) return 0;
1182
+ return sqlite3_value_int64((sqlite3_value *)&cur->row->aMem[cur->ncol - 1]);
1183
+ }
1184
+
1185
+ /* ---- Locking ------------------------------------------------------------ */
1186
+
1187
+ /* Every cursor entry point holds its connection's `db->mutex` around the
1188
+ * work, as SQLite's own API functions do: the internal functions the cursors
1189
+ * call (the allocator, the decoder, the B-tree) expect it held. The mutex is
1190
+ * recursive, and NULL (a no-op) when the build or the open asks for none. */
1191
+ static sqlite3_mutex *conn_mutex(int32_t h) {
1192
+ nishsqlite_conn *c = conn_of(h);
1193
+ return c ? sqlite3_db_mutex(c->db) : NULL;
1194
+ }
1195
+
1196
+ static sqlite3_mutex *cur_mutex(int32_t h) {
1197
+ nishsqlite_slot *s = slot_of(&nishsqlite_cursors, h);
1198
+ return s ? sqlite3_db_mutex(((nishsqlite_cursor *)s->p)->conn->db) : NULL;
1199
+ }
1200
+
1201
+ #define NISH_SQLITE_LOCKED(type, mutex, call) \
1202
+ sqlite3_mutex *mx_ = (mutex); \
1203
+ sqlite3_mutex_enter(mx_); \
1204
+ type r_ = (call); \
1205
+ sqlite3_mutex_leave(mx_); \
1206
+ return r_
1207
+
1208
+ int32_t nishsqlite_cursor_open(int32_t h, const char *name, const char *columns) {
1209
+ NISH_SQLITE_LOCKED(int32_t, conn_mutex(h), unlocked_cursor_open(h, name, columns));
1210
+ }
1211
+
1212
+ int32_t nishsqlite_cursor_close(int32_t h) {
1213
+ NISH_SQLITE_LOCKED(int32_t, cur_mutex(h), unlocked_cursor_close(h));
1214
+ }
1215
+
1216
+ int32_t nishsqlite_cursor_first(int32_t h) {
1217
+ NISH_SQLITE_LOCKED(int32_t, cur_mutex(h), unlocked_cursor_first(h));
1218
+ }
1219
+
1220
+ int32_t nishsqlite_cursor_last(int32_t h) {
1221
+ NISH_SQLITE_LOCKED(int32_t, cur_mutex(h), unlocked_cursor_last(h));
1222
+ }
1223
+
1224
+ int32_t nishsqlite_cursor_next(int32_t h) {
1225
+ NISH_SQLITE_LOCKED(int32_t, cur_mutex(h), unlocked_cursor_next(h));
1226
+ }
1227
+
1228
+ int32_t nishsqlite_cursor_previous(int32_t h) {
1229
+ NISH_SQLITE_LOCKED(int32_t, cur_mutex(h), unlocked_cursor_previous(h));
1230
+ }
1231
+
1232
+ int32_t nishsqlite_cursor_seek_rowid(int32_t h, int64_t rowid) {
1233
+ NISH_SQLITE_LOCKED(int32_t, cur_mutex(h), unlocked_cursor_seek_rowid(h, rowid));
1234
+ }
1235
+
1236
+ int32_t nishsqlite_key_reset(int32_t h) {
1237
+ NISH_SQLITE_LOCKED(int32_t, cur_mutex(h), unlocked_key_reset(h));
1238
+ }
1239
+
1240
+ int32_t nishsqlite_key_i64(int32_t h, int64_t v) {
1241
+ NISH_SQLITE_LOCKED(int32_t, cur_mutex(h), unlocked_key_i64(h, v));
1242
+ }
1243
+
1244
+ int32_t nishsqlite_key_text(int32_t h, const char *text) {
1245
+ NISH_SQLITE_LOCKED(int32_t, cur_mutex(h), unlocked_key_text(h, text));
1246
+ }
1247
+
1248
+ int32_t nishsqlite_key_bytes(int32_t h, const uint8_t *buf, uint64_t n, int32_t off, int32_t len) {
1249
+ NISH_SQLITE_LOCKED(int32_t, cur_mutex(h), unlocked_key_bytes(h, buf, n, off, len));
1250
+ }
1251
+
1252
+ int32_t nishsqlite_cursor_seek(int32_t h, int32_t op) {
1253
+ NISH_SQLITE_LOCKED(int32_t, cur_mutex(h), unlocked_cursor_seek(h, op));
1254
+ }
1255
+
1256
+ int32_t nishsqlite_cursor_column_type(int32_t h, int32_t n) {
1257
+ NISH_SQLITE_LOCKED(int32_t, cur_mutex(h), unlocked_cursor_column_type(h, n));
1258
+ }
1259
+
1260
+ int64_t nishsqlite_cursor_column_i64(int32_t h, int32_t n) {
1261
+ NISH_SQLITE_LOCKED(int64_t, cur_mutex(h), unlocked_cursor_column_i64(h, n));
1262
+ }
1263
+
1264
+ int32_t nishsqlite_cursor_column_into(int32_t h, int32_t c, uint8_t *buf, uint64_t n, int32_t at) {
1265
+ NISH_SQLITE_LOCKED(int32_t, cur_mutex(h), unlocked_cursor_column_into(h, c, buf, n, at));
1266
+ }
1267
+
1268
+ int64_t nishsqlite_cursor_rowid(int32_t h) {
1269
+ NISH_SQLITE_LOCKED(int64_t, cur_mutex(h), unlocked_cursor_rowid(h));
1270
+ }