@noego/sqlego 0.1.2-dev.1 → 0.1.2-dev.3

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.
package/README.md CHANGED
@@ -9,23 +9,74 @@ been idle.
9
9
  Why: SQLite's write lock is per-process. Two processes (an app, a log host, a
10
10
  retention job, a debugging CLI) writing the same file contend, time out, and
11
11
  freeze each other. With a single owner there is nothing to contend: statements
12
- from all clients run in arrival order on one connection, and a reader from any
13
- process just asks the owner.
12
+ from all clients use one writer, and a reader from any process just asks the
13
+ owner. WAL files also have a readonly connection for opted-in plain reads.
14
14
 
15
15
  ## Pieces
16
16
 
17
17
  | Piece | Runtime | Role |
18
18
  | --- | --- | --- |
19
- | `bin/sqlego[.exe]`, `bin/sqlego-<platform>-<arch>[.exe]` | Bun, compiled single binary | CLI **and** server (`sqlego serve <file>` is what clients spawn) |
19
+ | `@noego/sqlego-<platform>-<arch>` (`npm/<platform>/`) | Bun, compiled single binary | CLI **and** server (`sqlego serve <file>` is what clients spawn); one package per platform, one binary each |
20
20
  | `bin/sqlego.cjs` | Node | The `sqlego` command npm installs: runs the binary for this platform (npm shims cannot launch a native `.exe` on Windows) |
21
- | `@noego/sqlego` (`src/client.ts`) | Node or Bun; `node:net` only | Protocol-only client — no SQLite dependency, no native addon |
22
- | `src/server.ts` | Bun (`bun:sqlite`) | The owner: per file one `Database` and one socket; many files per process; idle release |
21
+ | `@noego/sqlego` (`src/client.ts`) | Node or Bun; `node:net` only | Protocol-only client — no SQLite dependency, no native addon, no binary |
22
+ | `src/server.ts` | Bun (`bun:sqlite`) | The owner: per file one writer, a readonly connection for WAL files, and one socket; many files per process; idle release |
23
23
 
24
- Platforms: macOS (arm64, x64), Linux (x64, arm64), Windows x64. `bun run
25
- build` compiles the binary for the host; `bun run build:all` compiles one per
26
- platform into `bin/` (what the publish workflow ships). The Windows build is
27
- cross-compiled and exercised by CI only as a build; it has not been run on a
28
- Windows machine yet.
24
+ Platforms: macOS (arm64, x64), Linux (x64, arm64, glibc), Windows x64. The
25
+ Windows build is cross-compiled and exercised only as a build; it has not been
26
+ run on a Windows machine yet.
27
+
28
+ ## Install
29
+
30
+ ```
31
+ npm install @noego/sqlego
32
+ ```
33
+
34
+ `@noego/sqlego` is the client and the `sqlego` command; it carries no binary.
35
+ It lists the five platform packages as `optionalDependencies`, pinned to its
36
+ own exact version, and npm installs only the one whose `os`/`cpu` match the
37
+ machine (about 60–110 MB unpacked, instead of every platform's binary):
38
+
39
+ | Package | Platform |
40
+ | --- | --- |
41
+ | `@noego/sqlego-darwin-arm64` | macOS, Apple silicon |
42
+ | `@noego/sqlego-darwin-x64` | macOS, Intel |
43
+ | `@noego/sqlego-linux-x64` | Linux x64 (glibc) |
44
+ | `@noego/sqlego-linux-arm64` | Linux arm64 (glibc) |
45
+ | `@noego/sqlego-win32-x64` | Windows x64 |
46
+
47
+ Installing with `--omit=optional` (or `--no-optional`) skips the platform
48
+ package; `connect` then fails with code `binary-missing`, and the message
49
+ names the package to install and `SQLEGO_BIN`. Installing on one machine and
50
+ copying `node_modules` to another platform has the same effect.
51
+
52
+ ### Where the server binary comes from
53
+
54
+ In order, and nothing else:
55
+
56
+ 1. `SQLEGO_BIN`, the path of a `sqlego` binary, when set. Use it for an
57
+ install without optional dependencies, a platform without a package, or a
58
+ binary you ship yourself.
59
+ 2. Under Bun only: the running process when it is the compiled `sqlego`, or
60
+ `bun src/cli.ts` when running from source.
61
+ 3. The installed platform package for this machine, resolved the way Node
62
+ resolves an import (`require.resolve`).
63
+ 4. A local build next to the package: `bin/sqlego-<platform>-<arch>[.exe]`.
64
+
65
+ Only the host's platform is ever looked up, so a binary built for another
66
+ platform is never chosen. (Before 0.1.2-dev.2 the package shipped an
67
+ unqualified `bin/sqlego`, the publisher's macOS arm64 build, and picked it on
68
+ every host.) `serverCommand` on `connect` bypasses all of this.
69
+
70
+ ### Electron
71
+
72
+ Electron packs `node_modules` into `app.asar`, and no executable can start
73
+ from inside that archive. When the resolved binary's path runs through
74
+ `app.asar`, sqlego uses the same path under `app.asar.unpacked`. Tell the
75
+ packager to unpack the platform package, e.g. electron-builder
76
+ `"asarUnpack": ["node_modules/@noego/sqlego-*/**"]`, or Electron Forge
77
+ `packagerConfig.asar.unpack: "**/node_modules/@noego/sqlego-*/**"`. Build the
78
+ app on (or for) each target platform so its platform package is the one
79
+ installed; otherwise set `SQLEGO_BIN` to a binary you bundle.
29
80
 
30
81
  ## Lifecycle
31
82
 
@@ -82,8 +133,11 @@ share one process instead of starting 40.
82
133
 
83
134
  An owner applies, in order, `auto_vacuum = INCREMENTAL`, `journal_mode = WAL`,
84
135
  `busy_timeout = 5000`, `foreign_keys = ON` (foreign keys are per connection in
85
- SQLite and off by default; the owner holds the only connection). `--pragma`
136
+ SQLite and off by default; enabled on the writer). `--pragma`
86
137
  on `serve`, or `serverPragmas` on the client, replaces the whole list.
138
+ After applying them, a WAL file gets a second connection opened readonly with
139
+ safe integers, the writer's busy timeout, and `query_only = ON`. Non-WAL files
140
+ keep one connection and do not advertise detached-read support.
87
141
 
88
142
  ## Protocol
89
143
 
@@ -138,10 +192,11 @@ trusted to.
138
192
  `SAVEPOINT` and `RELEASE` (`bad-request`): the server must always know
139
193
  whether the file is inside a transaction.
140
194
 
141
- While one is open, that client's statements run at once and every other
142
- client's `query` / `run` / `statement` / `exec` / `batch` / `begin` wait in arrival order (`status`
143
- reports how many); `hello`, `status` and `stop` never wait. It is rolled back
144
- by the server, and later requests for it fail with `tx-expired`, when:
195
+ Without the detached-plain opt-in below, the owning client's statements run at
196
+ once (plain statements implicitly join its transaction), and every other
197
+ client's `query` / `run` / `statement` / `exec` / `batch` / `begin` waits in arrival
198
+ order (`status` reports how many). `hello`, `status` and `stop` never wait.
199
+ It is rolled back by the server, and later requests for it fail with `tx-expired`, when:
145
200
 
146
201
  | Trigger | Server flag | Default |
147
202
  | --- | --- | --- |
@@ -150,10 +205,44 @@ by the server, and later requests for it fail with `tx-expired`, when:
150
205
  | Open longer than the hard cap, renewed or not | `--tx-max-ms` | 60 s |
151
206
  | SQLite itself aborted it (e.g. `SQLITE_FULL`) | — | immediate |
152
207
 
153
- A waiting request from another client fails with `tx-busy` after
208
+ A waiting request fails with `tx-busy` after
154
209
  `--tx-queue-ms` (default 30 s) rather than hanging. The idle exit never fires
155
210
  while a transaction is open.
156
211
 
212
+ ### Detached plain statements (opt-in)
213
+
214
+ WAL owners advertise `capabilities: ['detached-plain']` in `hello` and `status`.
215
+ Missing capabilities parse as `[]`. A socket opts in by sending
216
+ `hello { clientVersion, protocol: 3, features: ['detached-plain'] }`, or by
217
+ calling `await client.enableDetachedPlain()` after connecting (returns false
218
+ when unsupported). Opt-in is sticky for that socket. Other sockets, including
219
+ older clients using the same owner, retain their existing transaction semantics.
220
+
221
+ For an opted-in socket:
222
+ - A single plain statement (no `txId`) starting with `SELECT`, `WITH`,
223
+ `VALUES` or `EXPLAIN`, after comments, runs on the readonly connection,
224
+ irrespective of whether its op is `query`, `run` or `statement`.
225
+ - Only `SQLITE_READONLY` retries on the writer under normal queueing rules
226
+ (for example, a CTE-prefixed write). Every other error is returned as-is.
227
+ - All `PRAGMA`s, other SQL keywords, `exec`, `batch` and transaction operations
228
+ stay on the writer. Statements with a `txId` always use the writer.
229
+ - Plain writer-path requests wait for **any** open transaction, including one
230
+ owned by this same socket. They never implicitly join it. Requests carrying
231
+ its `txId`, including commit/rollback, still run without waiting.
232
+ - Plain reads see the last committed snapshot, not uncommitted writes.
233
+ Reads that accidentally escape a transaction's scope therefore return
234
+ committed data rather than blocking.
235
+ - Standalone `SELECT last_insert_rowid()` / `changes()` reports the reader's
236
+ values, not the writer's. Reader reply metadata is `changes: 0` and
237
+ `lastInsertRowid: 0`.
238
+ - Plain reads of a TEMP table created on the writer fail. Use the transaction
239
+ handle for transaction-local state; audit any existing TEMP-table use.
240
+ - Queued plain writes may now fail with `tx-busy` after the default 30 seconds,
241
+ rather than waiting indefinitely in a client's local gate.
242
+
243
+ Both connections close when the file is stopped; adopted WAL files get the
244
+ same reader automatically.
245
+
157
246
  ## CLI
158
247
 
159
248
  ```
@@ -198,9 +287,8 @@ A `SqlegoClientError` with code `tx-expired` means the server rolled the
198
287
  transaction back (lease, hard cap, or disconnect); `tx-busy` means another
199
288
  client's transaction kept the request waiting too long.
200
289
 
201
- Server location: `SQLEGO_BIN`, else the compiled binary for this platform in
202
- `bin/` next to the package (`sqlego[.exe]`, then `sqlego-<platform>-<arch>[.exe]`),
203
- else `sqlego` on `PATH`; pass `serverCommand` to override.
290
+ Server location: see [Where the server binary comes from](#where-the-server-binary-comes-from);
291
+ pass `serverCommand` to override.
204
292
 
205
293
  Other `connect` options: `serverPragmas` (the owner must have these pragmas,
206
294
  see above), `maxOwners` (owner processes, see above), `idleTimeoutMs`, `connectTimeoutMs`,
@@ -211,17 +299,28 @@ see above), `maxOwners` (owner processes, see above), `idleTimeoutMs`, `connectT
211
299
  ```
212
300
  bun install
213
301
  bun test
214
- bun run build # → dist/ and bin/sqlego (host executable)
302
+ bun run build # → dist/ and bin/sqlego-<host platform>-<arch> (host executable)
215
303
  bun run build:bin:all # → bin/sqlego-{darwin,linux}-{arm64,x64}, bin/sqlego-win32-x64.exe
304
+ bun scripts/release.ts --channel dev --pack ./out # build + stage + check all six packages, write tarballs, publish nothing
216
305
  ```
217
306
 
218
307
  `bun run build` runs the fresh binary with `--version` and fails unless it
219
- reports `<package.json version>+<build id>`, so a stale `bin/sqlego` cannot
220
- be mistaken for the current one.
308
+ reports `<package.json version>+<build id>`, so a stale binary cannot be
309
+ mistaken for the current one.
310
+
311
+ ### Releasing
312
+
313
+ `.github/workflows/release.yml` runs `scripts/release.ts` on every push to
314
+ `release-candidate` (next `<base>-dev.N`, dist-tag `dev`) and `main`
315
+ (`package.json`'s version, dist-tag `latest`, only when npm does not have it,
316
+ then tagged `v<version>`). It builds every platform once, copies each binary
317
+ into `npm/<platform>/` (binaries are gitignored), sets all six packages to one
318
+ version, fails if a platform package lacks its binary or the main package
319
+ carries one, and publishes the five platform packages before the main package.
221
320
 
222
321
  ### Versions
223
322
 
224
- `package.json` is the only version source: the publish workflow publishes it
225
- to npm and tags the commit `v<version>`. The stray tag `v0.1.1` predates npm
226
- (the first publish reset to 0.0.1); 0.1.2 moves past it so git tags and npm
227
- versions order the same way from here on.
323
+ `package.json` is the only version source; the release workflow stamps it
324
+ into the platform packages. The stray tag `v0.1.1` predates npm (the first
325
+ publish reset to 0.0.1); 0.1.2 moves past it so git tags and npm versions
326
+ order the same way from here on.
package/bin/sqlego.cjs CHANGED
@@ -2,25 +2,63 @@
2
2
  'use strict';
3
3
  /**
4
4
  * The `sqlego` command npm installs. It runs the compiled server binary for
5
- * this platform from the same directory: `sqlego` / `sqlego.exe` (the host
6
- * build) or `sqlego-<platform>-<arch>[.exe]` (a `build:bin:all` build). npm's
7
- * command shims cannot launch a native executable directly on Windows, which
8
- * is why this launcher exists; clients spawn the binary itself, not this.
5
+ * this platform; npm's command shims cannot launch a native executable
6
+ * directly on Windows, which is why this launcher exists. Clients spawn the
7
+ * binary itself, not this.
8
+ *
9
+ * Lookup (the same as src/binary.ts, which this CommonJS file cannot import):
10
+ * 1. SQLEGO_BIN;
11
+ * 2. the platform package @noego/sqlego-<platform>-<arch>;
12
+ * 3. a local build, bin/sqlego-<platform>-<arch>[.exe], beside this file.
13
+ * Only the host's platform is looked for; a path through Electron's app.asar
14
+ * is rewritten to app.asar.unpacked.
9
15
  */
10
16
  const { spawnSync } = require('node:child_process');
11
17
  const { existsSync } = require('node:fs');
12
18
  const path = require('node:path');
13
19
 
14
- const suffix = process.platform === 'win32' ? '.exe' : '';
15
- const candidates = [`sqlego${suffix}`, `sqlego-${process.platform}-${process.arch}${suffix}`].map((name) => path.join(__dirname, name));
16
- const binary = candidates.find((candidate) => existsSync(candidate));
17
- if (!binary) {
18
- process.stderr.write(`sqlego: no server binary for ${process.platform}-${process.arch} in ${__dirname} (looked for ${candidates.map((c) => path.basename(c)).join(', ')}); run \`bun run build:bin\`\n`);
20
+ const SUPPORTED = ['darwin-arm64', 'darwin-x64', 'linux-x64', 'linux-arm64', 'win32-x64'];
21
+ const key = `${process.platform}-${process.arch}`;
22
+ const packageName = `@noego/sqlego-${key}`;
23
+ const exe = process.platform === 'win32' ? '.exe' : '';
24
+ const unpacked = (file) => file.replace(/([\\/])app\.asar(?=[\\/])/, '$1app.asar.unpacked');
25
+
26
+ function locate() {
27
+ const configured = process.env.SQLEGO_BIN;
28
+ if (configured) return { binary: configured };
29
+ const looked = [];
30
+ let manifest = null;
31
+ try {
32
+ manifest = require.resolve(`${packageName}/package.json`);
33
+ } catch {
34
+ manifest = null;
35
+ }
36
+ if (manifest) {
37
+ const fromPackage = unpacked(path.join(path.dirname(manifest), `sqlego${exe}`));
38
+ if (existsSync(fromPackage)) return { binary: fromPackage };
39
+ looked.push(fromPackage);
40
+ }
41
+ const local = unpacked(path.join(__dirname, `sqlego-${key}${exe}`));
42
+ if (existsSync(local)) return { binary: local };
43
+ looked.push(local);
44
+ const reason = !SUPPORTED.includes(key)
45
+ ? `sqlego publishes no server binary for ${key} (supported: ${SUPPORTED.join(', ')})`
46
+ : manifest
47
+ ? `the package ${packageName} is installed but has no binary`
48
+ : `the package ${packageName} is not installed (npm installs it as an optional dependency of @noego/sqlego; it is skipped by --omit=optional / --no-optional, and on a platform that does not match)`;
49
+ return {
50
+ error: `no sqlego server binary for ${key}: ${reason}; looked in ${looked.join(', ')}. Reinstall without --omit=optional, or set SQLEGO_BIN to the path of a sqlego binary.`,
51
+ };
52
+ }
53
+
54
+ const found = locate();
55
+ if (found.error) {
56
+ process.stderr.write(`sqlego: ${found.error}\n`);
19
57
  process.exit(1);
20
58
  }
21
- const result = spawnSync(binary, process.argv.slice(2), { stdio: 'inherit', windowsHide: true });
59
+ const result = spawnSync(found.binary, process.argv.slice(2), { stdio: 'inherit', windowsHide: true });
22
60
  if (result.error) {
23
- process.stderr.write(`sqlego: cannot run ${binary}: ${result.error.message}\n`);
61
+ process.stderr.write(`sqlego: cannot run ${found.binary}: ${result.error.message}\n`);
24
62
  process.exit(1);
25
63
  }
26
64
  process.exit(result.status === null ? 1 : result.status);
@@ -0,0 +1,47 @@
1
+ import { Result } from '@noego/trust';
2
+ /**
3
+ * Where the compiled `sqlego` server binary lives. Pure: every input that
4
+ * touches the outside world (environment, module resolution, the file
5
+ * system) is passed in, so the lookup order can be tested for any platform.
6
+ *
7
+ * Order:
8
+ * 1. `SQLEGO_BIN`, when set.
9
+ * 2. The platform package `@noego/sqlego-<platform>-<arch>`, an optional
10
+ * dependency of `@noego/sqlego` that npm installs only on its own os/cpu.
11
+ * 3. A local build, `bin/sqlego-<platform>-<arch>[.exe]` next to the package
12
+ * (a source checkout after `bun run build`).
13
+ * Only the host's platform name is ever looked for, so a binary built for
14
+ * another platform is never chosen. A path inside an Electron `app.asar`
15
+ * archive is rewritten to `app.asar.unpacked`, where an executable can run.
16
+ */
17
+ /** The platforms a server binary is published for, as Node names them. */
18
+ export declare const SUPPORTED_PLATFORMS: readonly string[];
19
+ export type BinaryLookup = Readonly<{
20
+ platform: string;
21
+ arch: string;
22
+ /** `process.env.SQLEGO_BIN`. */
23
+ configured: string | undefined;
24
+ /** Absolute path of a package's `package.json`, or null when it is not installed. */
25
+ resolvePackageJson: (name: string) => string | null;
26
+ exists: (file: string) => boolean;
27
+ /** The package's own `bin/` directory, or null when it cannot be located. */
28
+ localBinDirectory: string | null;
29
+ }>;
30
+ export type BinaryMissing = Readonly<{
31
+ kind: 'binary-missing';
32
+ message: string;
33
+ }>;
34
+ /** `@noego/sqlego-<platform>-<arch>`: the package holding this platform's binary. */
35
+ export declare function platformPackageName(platform?: string, arch?: string): string;
36
+ /** The binary's file name inside its platform package. */
37
+ export declare function binaryFileName(platform?: string): string;
38
+ /** The binary's file name in a local `bin/` build: platform-qualified, so a foreign build is never mistaken for the host's. */
39
+ export declare function localBinaryName(platform?: string, arch?: string): string;
40
+ /**
41
+ * Electron packs `node_modules` into `app.asar`, a read-only archive no
42
+ * executable can be started from; packaging tools unpack native files to
43
+ * `app.asar.unpacked` beside it. A path through `app.asar` is rewritten to
44
+ * the unpacked twin; any other path is returned unchanged.
45
+ */
46
+ export declare function unpackedAsarPath(file: string): string;
47
+ export declare function locateServerBinary(lookup: BinaryLookup): Result<string, BinaryMissing>;
package/dist/client.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { Result } from '@noego/trust';
2
+ import { type BinaryMissing } from './binary.ts';
1
3
  import { type BatchResult, type BeginResult, type ExecResult, type HelloResult, type RunResult, type SqlParams, type SqlRow, type Statement, type StatementResult, type StatusResult, type TransactionMode } from './protocol.ts';
2
4
  import { type FilePaths } from './paths.ts';
3
5
  /**
@@ -69,6 +71,8 @@ export declare class SqlegoClient {
69
71
  private constructor();
70
72
  static connect(file: string, options?: ClientOptions): Promise<SqlegoClient>;
71
73
  get server(): HelloResult;
74
+ /** Opt this socket into committed-snapshot plain reads and queued plain writes. */
75
+ enableDetachedPlain(): Promise<boolean>;
72
76
  query<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<Row[]>;
73
77
  run(sql: string, params?: SqlParams): Promise<RunResult>;
74
78
  /**
@@ -191,15 +195,17 @@ export declare class SqlegoTransaction {
191
195
  rollback(): Promise<void>;
192
196
  }
193
197
  /**
194
- * File names the compiled server binary may have in `bin/`, most specific
195
- * last: the host build (`sqlego`, `sqlego.exe`) and the per-platform build
196
- * (`sqlego-<platform>-<arch>[.exe]`, from `bun run build:bin:all`).
197
- */
198
- export declare function platformBinaryNames(platform?: NodeJS.Platform, arch?: string): readonly string[];
199
- /**
200
- * How to start a server: SQLEGO_BIN if set; the compiled `sqlego` binary when
201
- * running as one; the dev entry (`bun src/cli.ts`) when running from source
202
- * under Bun; the binary for this platform in the package's `bin/`; else
203
- * `sqlego` on PATH.
198
+ * How to start a server, or why there is no way to:
199
+ * 1. `SQLEGO_BIN`, when set;
200
+ * 2. under Bun only — this very process when it is the compiled `sqlego`
201
+ * binary, or the source entry (`bun src/cli.ts`) when running from
202
+ * source; both run on the host by definition;
203
+ * 3. the platform package `@noego/sqlego-<platform>-<arch>`;
204
+ * 4. a local `bin/sqlego-<platform>-<arch>[.exe]` build.
205
+ * Nothing else: not an unqualified `bin/sqlego` (in 0.1.2-dev.0 and earlier
206
+ * that was the publisher's darwin-arm64 build, wrong on every other host),
207
+ * not `sqlego` on PATH. See `locateServerBinary` for 1, 3 and 4.
204
208
  */
209
+ export declare function resolveServerCommand(): Result<readonly string[], BinaryMissing>;
210
+ /** Public, exception-based form of `resolveServerCommand`: throws an Error naming what to install or set. */
205
211
  export declare function defaultServerCommand(): readonly string[];
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- export { DEFAULT_MAX_OWNERS, SqlegoClient, SqlegoClientError, SqlegoTransaction, defaultServerCommand, platformBinaryNames, type BeginOptions, type ClientOptions, } from './client.ts';
1
+ export { DEFAULT_MAX_OWNERS, SqlegoClient, SqlegoClientError, SqlegoTransaction, defaultServerCommand, type BeginOptions, type ClientOptions, } from './client.ts';
2
+ export { SUPPORTED_PLATFORMS, binaryFileName, localBinaryName, locateServerBinary, platformPackageName, unpackedAsarPath, type BinaryLookup, } from './binary.ts';
2
3
  export { USES_NAMED_PIPES, isNamedPipe, pathsFor, runtimeDirectory, canonicalFile, type FilePaths, type ServerMeta } from './paths.ts';
3
4
  export { PROTOCOL_VERSION, type SqlParams, type SqlRow, type SqlValue, type Statement, type RunResult, type QueryResult, type BatchResult, type StatementResult, type ExecResult, type BeginResult, type StatusResult, type HelloResult, type TransactionMode, type TransactionStatus, } from './protocol.ts';
4
5
  export { VERSION } from './version.ts';