diff --git a/.changeset/20054-turso-remote-no-native-driver.md b/.changeset/20054-turso-remote-no-native-driver.md new file mode 100644 index 00000000000..98e2dd7d797 --- /dev/null +++ b/.changeset/20054-turso-remote-no-native-driver.md @@ -0,0 +1,32 @@ +--- +"@objectstack/driver-turso": minor +--- + +fix(driver-turso)!: a REMOTE `TursoDriver` no longer needs `better-sqlite3` installed, and the two inherited calls that answered from its private in-memory database now reject (#20054) + +Clause-②: no (narrowing) + +`package.json` declares `better-sqlite3` an optional peer, and the README tells a remote-only deployment (Vercel, an Edge runtime) that it does not need it. The code did not keep that promise. With `better-sqlite3` absent, `new TursoDriver({ url: 'libsql://…' })` threw knex's `Knex: run $ npm install better-sqlite3 --save` error at construction, before any remote call. + +The cause: remote mode handed the `SqlDriver` base a `better-sqlite3` Knex config on `:memory:`, and knex loads a dialect's native driver whenever the config carries a `connection`. Remote mode now builds that Knex instance with no `connection`. It loads no native module, opens no pool and holds no private in-memory database. With `better-sqlite3` absent, a remote driver constructs, connects and runs CRUD through `@libsql/client`. + +**BREAKING** — two calls on a remote driver that resolved before now reject. This is an accept-set narrowing on a published driver, shipped as `minor` under the repo's launch-window convention for breaking changes (`scripts/check-changeset-no-major.mjs`). The calls are `SqlDriver` methods that remote mode does not override, and they now reject with knex's `Unable to acquire a connection` error: + +- `introspectSchema()` used to resolve `{ tables: {} }`, "no tables", whatever the remote database held; +- `reclaimSpace()` used to resolve. + +Both old answers came from the private in-memory database, not from the remote one. The per-method answer or refusal for these inherited calls is carried by #20055. + +**Error wording only, not the narrowing.** On a remote driver: + +- `findWithWindowFunctions()` still rejects. The error is now knex's `Unable to acquire a connection` instead of a missing-table error from the in-memory database. +- `analyzeQuery()` and `explain()` still resolve the compiled SQL with an `error` field. That field now carries knex's message instead of a missing-table error. +- `distinct()` answers the same `DATABASE_ERROR` / 500 as before. + +**Unchanged:** + +- **Local and embedded-replica modes.** Their `toKnexConfig` arms are untouched and still run on `better-sqlite3`, so a local driver (`:memory:` or a `file:` url) still fails at construction without it. +- **Every call remote mode sends to `RemoteTransport` behaves as before**, including raw SQL through `execute()`. None of them used the Knex instance. +- **The `NOT_IMPLEMENTED` / 501 refusals of `detectManagedDrift()` and `planMediaColumnMove()` on a remote driver** still refuse, with the same code and status. Their messages no longer say that remote mode's Knex connection is a placeholder in-memory database; they say that remote mode has no Knex connection. + + diff --git a/packages/drivers/driver-turso/src/turso-driver.ts b/packages/drivers/driver-turso/src/turso-driver.ts index 9919ee7a80b..227df64b304 100644 --- a/packages/drivers/driver-turso/src/turso-driver.ts +++ b/packages/drivers/driver-turso/src/turso-driver.ts @@ -450,13 +450,16 @@ function refuseRemoteDeferredDdl(): never { * * `SqlDriver.detectManagedDrift` reads the physical schema through Knex: a * `hasTable` probe per table, then column and index introspection fed to the - * shared differ. In remote mode that Knex instance is the placeholder - * `:memory:` database {@link TursoDriver.toKnexConfig} hands the base - * constructor. It holds none of this datasource's tables, so every table was + * shared differ. In remote mode that Knex instance was then the placeholder + * `:memory:` database {@link TursoDriver.toKnexConfig} handed the base + * constructor. It held none of this datasource's tables, so every table was * skipped as absent and the answer was `[]` whatever the remote database held. * The no-argument call had a second reason to answer `[]`: it iterates * `managedObjectFields`, which only the Knex `initObjects` fills and no remote - * schema door reaches. Measured on the transport's SQLite-backed double + * schema door reaches. [#20054] Remote mode's Knex has no connection at all + * now, so an explicit-objects call would fail on its first `hasTable`; the + * no-argument call would still answer `[]` from the empty registry, which is + * why the refusal stays. Measured on the transport's SQLite-backed double * (`turso-remote-drift-detection-refusal.test.ts`): a synced table carrying an * extra physical column the declaration omits reads `unmapped_column` / * `drop_column` on the local face and `[]` on the remote one, with or without @@ -473,7 +476,7 @@ function refuseRemoteDeferredDdl(): never { * the NULL-safe duplicate probe), so a remote implementation is a second copy * of each of those SQLite arms. It also needs a remote answer for * `applyMigrationEntries`, which the gate calls on whatever it finds and which - * runs on the same placeholder. Until that exists the refusal is the honest + * runs through the same `this.knex`. Until that exists the refusal is the honest * answer, in the envelope and for the reason {@link refuseRemoteDeferredDdl} * records for its sibling gap on this transport: the call is spelled correctly * and the base class declares it, so the gap is the backend's. @@ -494,9 +497,11 @@ function refuseRemoteDriftDetection(): never { 'Schema drift detection is not supported by the Turso REMOTE transport (this datasource\'s ' + 'transport mode is `remote`), so this driver cannot say whether the database\'s physical ' + 'schema matches the declared objects. Drift detection reads the physical schema through the ' + - 'SQL driver\'s Knex connection, and in remote mode that connection is a placeholder in-memory ' + - 'database holding none of this datasource\'s tables. Answering from it would report "no drift" ' + - 'for every remote database, whatever its tables hold, so the call refuses. The call is spelled ' + + 'SQL driver\'s Knex connection, which remote mode does not have: every statement goes to the ' + + 'remote database through the libSQL client instead. The objects it compares by default are the ' + + 'ones the SQL driver\'s own schema sync registers, and remote mode registers none there, so ' + + 'answering would report "no drift" for every remote database, whatever its tables hold; the ' + + 'call refuses instead. The call is spelled ' + 'correctly and `SqlDriver` declares it, so this is a capability gap of the remote transport ' + 'rather than a mistake in the request, which is why it answers NOT_IMPLEMENTED/501 and not a ' + '400. To check this database for drift, run `os migrate plan` against a local SQLite copy of it ' + @@ -520,9 +525,12 @@ function refuseRemoteDriftDetection(): never { * `os migrate files-to-references --apply`. It walks `managedObjectFields`, * which the Knex `initObjects` fills (through `registerObjectMetadata`) and no * remote schema door reaches, and it probes each table with `hasTable` and - * column introspection through `this.knex`, which in remote mode is the - * placeholder `:memory:` database {@link TursoDriver.toKnexConfig} hands the - * base constructor. Either reason alone empties the answer. Measured on the + * column introspection through `this.knex`, which in remote mode was then the + * placeholder `:memory:` database {@link TursoDriver.toKnexConfig} handed the + * base constructor. Either reason alone empties the answer. [#20054] Remote + * mode's Knex has no connection at all now, and the walk over the empty + * registry still answers an empty scan without reaching it, which is why the + * refusal stays. Measured on the * transport's SQLite-backed double * (`turso-remote-media-column-move-refusal.test.ts`): a table `m` with a `file` * and an `image` field, synced through each of the three remote schema doors, @@ -564,8 +572,8 @@ function refuseRemoteMediaColumnMove(): never { 'Planning the ADR-0104 media column move is not supported by the Turso REMOTE transport ' + '(this datasource\'s transport mode is `remote`), so this driver cannot say which single-value ' + 'media columns the database holds or how their values are encoded. The planner reads the ' + - 'physical columns through the SQL driver\'s Knex connection, and in remote mode that connection ' + - 'is a placeholder in-memory database holding none of this datasource\'s tables; the objects it ' + + 'physical columns through the SQL driver\'s Knex connection, which remote mode does not have: ' + + 'every statement goes to the remote database through the libSQL client instead. The objects it ' + 'walks are the ones the SQL driver\'s own schema sync registers, and remote mode registers its ' + 'objects another way. Answering from them would report "nothing to move" for every remote ' + 'database, whatever media columns it holds, so the call refuses: nothing was planned and nothing ' + @@ -1357,17 +1365,43 @@ export class TursoDriver extends SqlDriver { /** * Convert TursoDriverConfig to a Knex-compatible SqlDriverConfig. * Extracts the file path from the URL for local/embedded modes. - * In remote mode, uses a dummy :memory: config (Knex is not used). + * In remote mode, hands the base a Knex with NO connection: the SQLite + * dialect's compiler and nothing else (see the remote arm below). */ private static toKnexConfig(config: TursoDriverConfig, mode: TursoTransportMode): SqlDriverConfig { - // Remote mode: All CRUD/schema operations delegate to RemoteTransport - // (via @libsql/client). Knex is never used for queries, but the SqlDriver - // base class constructor requires a valid config. We provide a minimal - // :memory: config that initializes Knex without side effects. + // [#20054] Remote mode: every CRUD and schema door delegates to + // RemoteTransport (`@libsql/client`), and none of them reads `this.knex`. + // Measured with the Knex instance wrapped to record every access after + // construction, across connect, the CRUD and bulk doors, aggregate, + // execute, the three schema doors and disconnect: zero reads. The + // `SqlDriver` constructor still builds a Knex instance, so this arm only + // decides WHICH one. + // + // It is built WITHOUT a `connection`, and that is the whole fix. knex's + // `Client` constructor loads the dialect's native driver + // (`initializeDriver` → `require('better-sqlite3')`) and builds a pool only + // when the config carries a `connection`. This arm used to pass + // `{ filename: ':memory:' }`, but loading the native module is a side + // effect: with `better-sqlite3` absent — the install this package's + // manifest (an OPTIONAL peer) and README give remote mode, e.g. on Vercel + // or an Edge runtime — construction threw knex's `npm install + // better-sqlite3` error before any remote call was made. + // + // What stays the same: the client is still spelled `better-sqlite3`, so + // `isSqlite` and every dialect-keyed rule the remote arms borrow from the + // base (`temporalFilterColumnSql`, the canonical-time SQL) answer exactly + // as before, and so does anything that reads the dialect name off + // `config.client`. + // + // What changes for a path that still reaches `this.knex` (only `SqlDriver` + // methods this class does not override for remote mode): it used to RUN + // against a private, empty `:memory:` database and could answer from it, + // as `introspectSchema()` did with "no tables". Now knex refuses to run it + // (`Unable to acquire a connection`), because there is no connection to + // run it on. That failure is loud; it never adds a silent answer. if (mode === 'remote') { return { client: 'better-sqlite3', - connection: { filename: ':memory:' }, useNullAsDefault: true, }; } @@ -2551,10 +2585,11 @@ export class TursoDriver extends SqlDriver { /** * Detect managed-schema drift — refused on the REMOTE face, see * {@link refuseRemoteDriftDetection}. The inherited detector reads the - * physical schema through the placeholder Knex connection remote mode is - * built with, so its remote answer was always `[]`. Refused with or without - * explicit `objects`, because both read the same placeholder. Local and - * replica modes inherit the Knex detector unchanged. + * physical schema through `this.knex`, which remote mode builds with no + * connection; with no `objects` it walks a registry no remote schema door + * fills and answers `[]`. Refused with or without explicit `objects`, because + * neither can judge the remote database. Local and replica modes inherit the + * Knex detector unchanged. * * The parameter repeats the base's declared shape key for key rather than * deriving it (`check:object-def-param-keys` arm C), so the keys a caller may @@ -2571,9 +2606,9 @@ export class TursoDriver extends SqlDriver { * Plan the ADR-0104 media column move — refused on the REMOTE face, see * {@link refuseRemoteMediaColumnMove}. The inherited planner walks * `managedObjectFields`, which no remote schema door fills, and probes each - * table through the placeholder Knex connection remote mode is built with, - * so its remote answer was always an empty scan. Local and replica modes - * inherit the Knex planner unchanged. + * table through `this.knex`, which remote mode builds with no connection, so + * its remote answer is an empty scan. Local and replica modes inherit the + * Knex planner unchanged. */ override async planMediaColumnMove(): ReturnType { if (this.isRemote) refuseRemoteMediaColumnMove(); diff --git a/packages/drivers/driver-turso/src/turso-remote-drift-detection-refusal.test.ts b/packages/drivers/driver-turso/src/turso-remote-drift-detection-refusal.test.ts index 5c0374c5cb2..bb891b962ce 100644 --- a/packages/drivers/driver-turso/src/turso-remote-drift-detection-refusal.test.ts +++ b/packages/drivers/driver-turso/src/turso-remote-drift-detection-refusal.test.ts @@ -5,9 +5,10 @@ * answering "no drift". * * `SqlDriver.detectManagedDrift` reads the physical schema through Knex, and a - * remote `TursoDriver` is built with a placeholder `:memory:` Knex connection - * that holds none of the datasource's tables. Before the refusal, the remote - * answer was `[]` for every database. That is the answer the artifact-pinned + * remote `TursoDriver` was then built with a placeholder `:memory:` Knex + * connection that held none of the datasource's tables (since #20054 it is + * built with no Knex connection at all). Before the refusal, the remote answer + * was `[]` for every database. That is the answer the artifact-pinned * boot gate of `os serve` reads as "never drifted", so a gate whose job is to * refuse a boot on destructive drift let every remote-Turso boot through. * diff --git a/packages/drivers/driver-turso/src/turso-remote-media-column-move-refusal.test.ts b/packages/drivers/driver-turso/src/turso-remote-media-column-move-refusal.test.ts index 88020914a2b..044f0c2560f 100644 --- a/packages/drivers/driver-turso/src/turso-remote-media-column-move-refusal.test.ts +++ b/packages/drivers/driver-turso/src/turso-remote-media-column-move-refusal.test.ts @@ -7,8 +7,9 @@ * `SqlDriver.planMediaColumnMove` walks `managedObjectFields` and probes each * table through Knex. A remote `TursoDriver` fills neither: no remote schema * door reaches the Knex `initObjects` that fills the map, and its Knex - * connection is a placeholder `:memory:` database holding none of the - * datasource's tables. `os migrate files-to-references` mapped the resulting + * connection was then a placeholder `:memory:` database holding none of the + * datasource's tables (since #20054 there is no Knex connection at all). + * `os migrate files-to-references` mapped the resulting * empty scan to "nothing to move — this datastore declares no single-value * media column". * diff --git a/packages/drivers/driver-turso/src/turso-remote-no-native-driver.test.ts b/packages/drivers/driver-turso/src/turso-remote-no-native-driver.test.ts new file mode 100644 index 00000000000..d1814bef23d --- /dev/null +++ b/packages/drivers/driver-turso/src/turso-remote-no-native-driver.test.ts @@ -0,0 +1,243 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #20054 — remote mode constructs and runs without `better-sqlite3`. + * + * `package.json` declares `better-sqlite3` an OPTIONAL peer, and the README's + * "Dependencies by Mode" table gives remote mode `@libsql/client` only + * ("Vercel/Edge compatible — no native dependencies"). The code did not keep + * that promise: `toKnexConfig`'s remote arm handed the `SqlDriver` base a + * `better-sqlite3` Knex config on `:memory:`, and knex's `Client` constructor + * loads a dialect's native driver whenever the config carries a `connection`. + * So with the module absent, `new TursoDriver({ url: 'libsql://…' })` threw + * knex's `npm install better-sqlite3` error before any remote call was made. + * + * The remote arm now builds the base's Knex with no `connection`: the SQLite + * dialect's compiler, no native driver, no pool, no private database. + * + * ## How "absent" is staged + * + * `better-sqlite3` is installed here (local mode and the test doubles need it), + * so each case below runs with `Module._load` refusing it as a missing module, + * the way Node answers when the package is not installed. `_load` rather than + * `_resolveFilename`: every CommonJS `require` passes through `_load`, and a + * resolution cache can short-circuit `_resolveFilename` for a module some + * earlier code in the process already loaded. The hook counts the load + * attempts it refuses, so each case says HOW OFTEN the native module was + * reached, not only whether something threw. + * + * ## What is pinned + * + * 1. The control: a local `:memory:` driver and a local `file:` driver still + * cannot be constructed without the module, and the failure names it. This + * also proves the hook is live; without it, the remote cases below would + * pass for the wrong reason. + * 2. A remote driver constructs without the module, with zero load attempts. + * 3. Remote CRUD through a real `@libsql/client` `file:` client works without + * the module, with zero load attempts, and the rows land in that file. + * 4. `SqlDriver` methods the remote face does not override, and which still + * reach `this.knex`, never answer from a database that is not the remote + * one: each either fails or answers from the remote database. Which of the + * two, and with which envelope, is the inherited-methods card's decision. + * What this card owes is that removing the private `:memory:` database adds + * no silent answer. `introspectSchema()` used to answer "no tables" from it. + * + * Reverse verification, with the old `connection: { filename: ':memory:' }` + * restored in the remote arm: 6 of 10 go red. Cases 2 and 3 fail on knex's + * install error, as does every case-4 test with the module absent, because + * construction fails first. With the module installed, `introspectSchema()` + * goes red on `expected [] to include 'probe_t'`, the silent answer this card + * removes. The two controls stay green, and so do `distinct()` and + * `findWithWindowFunctions()` with the module installed, which failed loudly + * against the private database too. + */ + +import Module from 'node:module'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterAll, afterEach, describe, expect, it } from 'vitest'; +import { createClient, type Client } from '@libsql/client'; +import { TursoDriver } from './index.js'; + +const NATIVE = 'better-sqlite3'; + +type ModuleLoad = (this: unknown, request: string, parent: unknown, isMain: boolean) => unknown; +const loader = Module as unknown as { _load: ModuleLoad }; + +/** + * Run `body` with every load of `better-sqlite3` refused as a missing module. + * `attempts()` reads how many loads were refused so far. The original loader + * is restored whatever `body` does. + */ +async function withoutNativeDriver(body: (attempts: () => number) => Promise | T): Promise { + const original = loader._load; + let attempts = 0; + loader._load = function (this: unknown, request, parent, isMain) { + if (request === NATIVE || request.startsWith(`${NATIVE}/`)) { + attempts += 1; + const err = new Error(`Cannot find module '${request}'`) as Error & { code?: string }; + err.code = 'MODULE_NOT_FOUND'; + throw err; + } + return original.call(this, request, parent, isMain); + }; + try { + return await body(() => attempts); + } finally { + loader._load = original; + } +} + +const scratch = mkdtempSync(join(tmpdir(), 'turso-no-native-')); +afterAll(() => rmSync(scratch, { recursive: true, force: true })); + +const open: Array<{ driver?: TursoDriver; client?: Client }> = []; +afterEach(async () => { + while (open.length) { + const { driver, client } = open.pop()!; + await driver?.disconnect().catch(() => {}); + client?.close(); + } +}); + +const OBJECT = { + name: 'probe_t', + fields: { + name: { type: 'text' }, + n: { type: 'number' }, + }, +}; + +describe('the control: local mode still needs better-sqlite3', () => { + it('a local `:memory:` driver is not constructed without it, and the failure names it', async () => { + await withoutNativeDriver((attempts) => { + expect(() => new TursoDriver({ url: ':memory:' })).toThrow(NATIVE); + expect(attempts()).toBeGreaterThan(0); + }); + }); + + it('a local `file:` driver is not constructed without it, and the failure names it', async () => { + await withoutNativeDriver((attempts) => { + expect(() => new TursoDriver({ url: `file:${join(scratch, 'local.db')}` })).toThrow(NATIVE); + expect(attempts()).toBeGreaterThan(0); + }); + }); +}); + +describe('remote mode does not need better-sqlite3', () => { + it('constructs without it, never trying to load it', async () => { + await withoutNativeDriver((attempts) => { + const driver = new TursoDriver({ url: 'libsql://probe-db.example.turso.io', authToken: 'x' }); + open.push({ driver }); + expect(driver.transportMode).toBe('remote'); + expect(attempts()).toBe(0); + }); + }); + + it('runs CRUD through a real @libsql/client `file:` client without it, never trying to load it', async () => { + await withoutNativeDriver(async (attempts) => { + const client = createClient({ url: `file:${join(scratch, 'remote-crud.db')}` }); + const driver = new TursoDriver({ url: 'libsql://probe.turso.io', client }); + open.push({ driver, client }); + expect(driver.transportMode).toBe('remote'); + + await driver.connect(); + await driver.initObjects([OBJECT]); + await driver.create('probe_t', { id: 'a', name: 'x', n: 1 }); + await driver.bulkCreate('probe_t', [{ id: 'b', name: 'y', n: 2 }]); + await driver.update('probe_t', 'a', { name: 'xx' }); + expect(await driver.count('probe_t', {})).toBe(2); + const rows = await driver.find('probe_t', { orderBy: [{ field: 'id', order: 'asc' }] }); + expect(rows.map((r: Record) => [r.id, r.name, r.n])).toEqual([ + ['a', 'xx', 1], + ['b', 'y', 2], + ]); + await driver.delete('probe_t', 'b'); + + // The rows are in the libsql file, not in some other database. + const landed = await client.execute('select id, name from probe_t order by id'); + expect(landed.rows.map((r) => [r.id, r.name])).toEqual([['a', 'xx']]); + + await driver.disconnect(); + expect(attempts()).toBe(0); + }); + }); +}); + +/** + * Run `body` in one of the two installs: with `better-sqlite3` present (the + * only install the old placeholder could run in, and the one where it + * answered from its private database), or absent. `attempts()` is 0 when the + * module is present, since nothing refuses it. + */ +async function inInstall(absent: boolean, body: (attempts: () => number) => Promise): Promise { + return absent ? withoutNativeDriver(body) : body(() => 0); +} + +describe.each([ + { install: 'with better-sqlite3 installed', absent: false }, + { install: 'with better-sqlite3 absent', absent: true }, +])('inherited methods that still reach Knex add no silent answer ($install)', ({ absent }) => { + /** + * A remote face over a real libsql `file:` client holding two rows in + * `probe_t`. Each method below is a `SqlDriver` method `TursoDriver` does + * not override for remote mode. + */ + async function remoteWithRows() { + const client = createClient({ url: `file:${join(scratch, `inherited-${absent}-${open.length}-${Date.now()}.db`)}` }); + const driver = new TursoDriver({ url: 'libsql://probe.turso.io', client }); + open.push({ driver, client }); + await driver.connect(); + await driver.initObjects([OBJECT]); + await driver.bulkCreate('probe_t', [ + { id: 'a', name: 'x', n: 1 }, + { id: 'b', name: 'y', n: 2 }, + ]); + return driver; + } + + /** Settle a call into what it answered, or that it failed. */ + const settle = (p: Promise) => + p.then( + (value) => ({ answered: true as const, value }), + (error: unknown) => ({ answered: false as const, error }), + ); + + it('`introspectSchema()` fails, or lists the remote table — never "no tables"', async () => { + await inInstall(absent, async (attempts) => { + const driver = await remoteWithRows(); + const outcome = await settle(driver.introspectSchema()); + if (outcome.answered) expect(Object.keys(outcome.value.tables)).toContain('probe_t'); + else expect(outcome.error).toBeInstanceOf(Error); + expect(attempts()).toBe(0); + }); + }); + + it('`distinct()` fails, or answers the remote values', async () => { + await inInstall(absent, async (attempts) => { + const driver = await remoteWithRows(); + const outcome = await settle(driver.distinct('probe_t', 'name')); + if (outcome.answered) expect([...outcome.value].sort()).toEqual(['x', 'y']); + else expect(outcome.error).toBeInstanceOf(Error); + expect(attempts()).toBe(0); + }); + }); + + it('`findWithWindowFunctions()` fails, or answers the remote rows', async () => { + await inInstall(absent, async (attempts) => { + const driver = await remoteWithRows(); + const outcome = await settle( + driver.findWithWindowFunctions('probe_t', { + fields: ['id'], + windowFunctions: [ + { function: 'row_number', alias: 'rn', over: { orderBy: [{ field: 'id', order: 'asc' }] } }, + ], + } as never), + ); + if (outcome.answered) expect(outcome.value).toHaveLength(2); + else expect(outcome.error).toBeInstanceOf(Error); + expect(attempts()).toBe(0); + }); + }); +});