Пример
drizzle-orm 0.45.2: Run drizzle-orm against an in-memory SQLite with no native module and no server, using node:sqlite as the driver
Проверенный пример — npm drizzle-orm 0.45.2: Run drizzle-orm against an in-memory SQLite with no native module and no server, using node:sqlite as the…
sha256:b2121ae40b126706d7f37eb42fe29016cbed772ae0a32001ee2bbaeff49ffcd7
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
MIT-0
Свидетельства выполнения
Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.
- Основа свидетельства
- Подписанный контракт пройден
- Квитанции проверки
- 3
- Ключи подписи, собравшие его
- 3
Заявленная среда
node 22 linux x64 node 22 javascript npm
Среды запусков проверки
| Окружение | Контракт | Этапы | Запуск |
|---|---|---|---|
| node 22 · linux alpine/x64 · docker ed25519:a2ec939a4c60e243 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · npm@1 |
2026-08-14 |
| node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · npm@1 |
2026-08-18 |
| node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · npm@1node:22-alpine@sha256:c610fcdfb1d5… |
2026-09-08 |
Кейс
HOW- Цель
- Run drizzle-orm against an in-memory SQLite with no native module and no server, using node:sqlite as the driver
- Пакеты
- Символы
-
- sqliteTable
- drizzle-orm/sqlite-proxy
- drizzle-orm/sqlite-proxy/migrator
- node:sqlite.DatabaseSync
- StatementSync.setReturnArrays
- sql
- eq
- DrizzleQueryError
- Окружение
- node 22
- Создан
- 2026-08-14T12:07:43Z
Контракт
- apply a hand-written drizzle migration folder to an in-memory node:sqlite database through sqlite-proxy, offline
- assert drizzle-orm's exports map refuses ./package.json, so its own version has to be read off disk rather than required
- assert drizzle-orm 0.45.2 publishes no node-sqlite entry point, so the driver is sqlite-proxy with node:sqlite behind it
- assert the first migrate hands the callback the two DDL statements split on --> statement-breakpoint plus one __drizzle_migrations insert, and a second migrate hands it nothing
- assert the migrator creates and reads __drizzle_migrations through the driver rather than through the callback, and that its SELECT arrives as method values
- assert .returning() gives back the stored row, including the id AUTOINCREMENT assigned and the login_count the insert never named
- assert a select returns rows keyed by the schema's JS names, with the values untouched: mapFromDriverValue on a plain integer column is the identity function, so the JS number came from node:sqlite
- assert .where(eq(...)) filters in SQL with the value bound as a parameter, and .get() on a miss is undefined rather than an empty row
- assert omitting a notNull column, a TypeScript error at build time, is also a runtime NOT NULL constraint failure
- assert drizzle writes a literal null for an omitted column instead of leaving it out, so the column's SQL DEFAULT never applies and only a schema-side .default() helps
- assert a unique violation arrives as DrizzleQueryError whose own message is the failed statement and its parameters and not the SQLite one, with the SQLite message and code on .cause
- assert the extended result codes separate SQLITE_CONSTRAINT_UNIQUE from SQLITE_CONSTRAINT_NOTNULL without parsing English
- assert a quote-carrying value interpolated into sql`` is bound as a parameter, leaving no quote in the statement, so the injected tautology matches no rows
- assert the same value concatenated with sql.raw does fire the tautology and returns every row, so the escaping is what prevented it
- assert a value carrying a statement terminator passed to eq() is one bound parameter and the table it names is still there afterwards
- assert a proxy driver that returns node:sqlite's default object rows silently yields rows with every column undefined, which is why setReturnArrays(true) is required
Файлы
- csx.json
- drizzle/0000_init.sql
- drizzle/meta/_journal.json
- package-lock.json
- package.json
- src/db.mjs
- test/contract.mjs
Исходный код
{"case":{"caseId":"case:sha256:4cc9d3265bf3ee37c2719089d073e0fe9c534d1f60147ffde72835cbe67f08fa","constraints":{"moduleSystem":"esm","runtime":"node"},"contract":["apply a hand-written drizzle migration folder to an in-memory node:sqlite database through sqlite-proxy, offline","assert drizzle-orm's exports map refuses ./package.json, so its own version has to be read off disk rather than required","assert drizzle-orm 0.45.2 publishes no node-sqlite entry point, so the driver is sqlite-proxy with node:sqlite behind it","assert the first migrate hands the callback the two DDL statements split on --\u003e statement-breakpoint plus one __drizzle_migrations insert, and a second migrate hands it nothing","assert the migrator creates and reads __drizzle_migrations through the driver rather than through the callback, and that its SELECT arrives as method values","assert .returning() gives back the stored row, including the id AUTOINCREMENT assigned and the login_count the insert never named","assert a select returns rows keyed by the schema's JS names, with the values untouched: mapFromDriverValue on a plain integer column is the identity function, so the JS number came from node:sqlite","assert .where(eq(...)) filters in SQL with the value bound as a parameter, and .get() on a miss is undefined rather than an empty row","assert omitting a notNull column, a TypeScript error at build time, is also a runtime NOT NULL constraint failure","assert drizzle writes a literal null for an omitted column instead of leaving it out, so the column's SQL DEFAULT never applies and only a schema-side .default() helps","assert a unique violation arrives as DrizzleQueryError whose own message is the failed statement and its parameters and not the SQLite one, with the SQLite message and code on .cause","assert the extended result codes separate SQLITE_CONSTRAINT_UNIQUE from SQLITE_CONSTRAINT_NOTNULL without parsing English","assert a quote-carrying value interpolated into sql`` is bound as a parameter, leaving no quote in the statement, so the injected tautology matches no rows","assert the same value concatenated with sql.raw does fire the tautology and returns every row, so the escaping is what prevented it","assert a value carrying a statement terminator passed to eq() is one bound parameter and the table it names is still there afterwards","assert a proxy driver that returns node:sqlite's default object rows silently yields rows with every column undefined, which is why setReturnArrays(true) is required"],"goal":"Run drizzle-orm against an in-memory SQLite with no native module and no server, using node:sqlite as the driver","kind":"HOW","packages":["pkg:npm/drizzle-orm@0.45.2"],"schemaVersion":1,"symbols":["sqliteTable","drizzle-orm/sqlite-proxy","drizzle-orm/sqlite-proxy/migrator","node:sqlite.DatabaseSync","StatementSync.setReturnArrays","sql","eq","DrizzleQueryError"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"javascript","moduleSystem":"esm","os":"linux","packageManager":"npm","runtime":"node","runtimeVersion":"22","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/drizzle-orm@0.45.2"],"schemaVersion":1,"symbols":["sqliteTable","drizzle-orm/sqlite-proxy","drizzle-orm/sqlite-proxy/migrator","node:sqlite.DatabaseSync","StatementSync.setReturnArrays","sql","eq","DrizzleQueryError"],"verifierAdapter":"npm@1"}
CREATE TABLE `users` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`email` text NOT NULL,
`display_name` text NOT NULL,
`role` text DEFAULT 'user' NOT NULL,
`login_count` integer DEFAULT 0 NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `users_email_unique` ON `users` (`email`);
{
"version": "7",
"dialect": "sqlite",
"entries": [
{
"idx": 0,
"version": "6",
"when": 1749000000000,
"tag": "0000_init",
"breakpoints": true
}
]
}
{
"name": "csx-drizzle-sqlite-migration",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "csx-drizzle-sqlite-migration",
"version": "1.0.0",
"dependencies": {
"drizzle-orm": "0.45.2"
}
},
"node_modules/drizzle-orm": {
"version": "0.45.2",
"resolved": "https://registry.npmjs.org/drizzle-orm/-/drizzle-orm-0.45.2.tgz",
"integrity": "sha512-kY0BSaTNYWnoDMVoyY8uxmyHjpJW1geOmBMdSSicKo9CIIWkSxMIj2rkeSR51b8KAPB7m+qysjuHme5nKP+E5Q==",
"license": "Apache-2.0",
"peerDependencies": {
"@aws-sdk/client-rds-data": ">=3",
"@cloudflare/workers-types": ">=4",
"@electric-sql/pglite": ">=0.2.0",
"@libsql/client": ">=0.10.0",
"@libsql/client-wasm": ">=0.10.0",
"@neondatabase/serverless": ">=0.10.0",
"@op-engineering/op-sqlite": ">=2",
"@opentelemetry/api": "^1.4.1",
"@planetscale/database": ">=1.13",
"@prisma/client": "*",
"@tidbcloud/serverless": "*",
"@types/better-sqlite3": "*",
"@types/pg": "*",
"@types/sql.js": "*",
"@upstash/redis": ">=1.34.7",
"@vercel/postgres": ">=0.8.0",
"@xata.io/client": "*",
"better-sqlite3": ">=7",
"bun-types": "*",
"expo-sqlite": ">=14.0.0",
"gel": ">=2",
"knex": "*",
"kysely": "*",
"mysql2": ">=2",
"pg": ">=8",
"postgres": ">=3",
"sql.js": ">=1",
"sqlite3": ">=5"
},
"peerDependenciesMeta": {
"@aws-sdk/client-rds-data": {
"optional": true
},
"@cloudflare/workers-types": {
"optional": true
},
"@electric-sql/pglite": {
"optional": true
},
"@libsql/client": {
"optional": true
},
"@libsql/client-wasm": {
"optional": true
},
"@neondatabase/serverless": {
"optional": true
},
"@op-engineering/op-sqlite": {
"optional": true
},
"@opentelemetry/api": {
"optional": true
},
"@planetscale/database": {
"optional": true
},
"@prisma/client": {
"optional": true
},
"@tidbcloud/serverless": {
"optional": true
},
"@types/better-sqlite3": {
"optional": true
},
"@types/pg": {
"optional": true
},
"@types/sql.js": {
"optional": true
},
"@upstash/redis": {
"optional": true
},
"@vercel/postgres": {
"optional": true
},
"@xata.io/client": {
"optional": true
},
"better-sqlite3": {
"optional": true
},
"bun-types": {
"optional": true
},
"expo-sqlite": {
"optional": true
},
"gel": {
"optional": true
},
"knex": {
"optional": true
},
"kysely": {
"optional": true
},
"mysql2": {
"optional": true
},
"pg": {
"optional": true
},
"postgres": {
"optional": true
},
"prisma": {
"optional": true
},
"sql.js": {
"optional": true
},
"sqlite3": {
"optional": true
}
}
}
}
}
{
"name": "csx-drizzle-sqlite-migration",
"version": "1.0.0",
"private": true,
"type": "module",
"dependencies": {
"drizzle-orm": "0.45.2"
}
}
import { fileURLToPath } from "node:url";
import { DatabaseSync } from "node:sqlite";
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
import { drizzle } from "drizzle-orm/sqlite-proxy";
import { migrate } from "drizzle-orm/sqlite-proxy/migrator";
/**
* drizzle-orm on top of node:sqlite, with no native module, no server and no
* network.
*
* The import people reach for first, `drizzle-orm/node-sqlite`, does not
* exist in 0.45.2 — measured against the published exports map, which has
* better-sqlite3, bun-sqlite, expo-sqlite, op-sqlite and sqlite-proxy and no
* node-sqlite. That entry point arrives with the 1.0.0 release candidates:
* 1.0.0-rc.1 already lists ./node-sqlite, ./node-sqlite/driver and
* ./node-sqlite/migrator. So on the current `latest` the way to reach Node's
* built-in SQLite is sqlite-proxy, drizzle's bring-your-own-executor driver,
* with node:sqlite as the executor.
*
* One thing this is NOT is a workaround for better-sqlite3 being
* uninstallable. Measured, because the objection is stale: better-sqlite3
* 13.0.3 installs under the resolve stage's --ignore-scripts on node:22-alpine
* and opens a database, since 13.x ships prebuilds/linuxmusl-x64.node inside
* the tarball and declares no install script. The `install: prebuild-install
* || node-gyp rebuild` that made --ignore-scripts fatal was last seen in 11.x.
* The reason to prefer node:sqlite is that it is not a native addon at all,
* not that the addon cannot be had.
*
* The trap in wiring the two together is the row shape. drizzle reads the
* proxy's answer POSITIONALLY — mapResultRow indexes row[0], row[1] against
* the selected fields and never looks at a key. node:sqlite's
* StatementSync.all() returns objects. Handing those back is not an error at
* any layer: you get the right number of rows, with the right keys, and every
* value undefined. drizzleOverObjectRows below exists so that failure is
* pinned by an assertion instead of described.
*/
export const users = sqliteTable("users", {
id: integer("id").primaryKey({ autoIncrement: true }),
email: text("email").notNull().unique(),
displayName: text("display_name").notNull(),
// The table declares DEFAULT 'user' for this column and the schema
// deliberately does not repeat it. drizzle fills omitted columns with a
// literal null rather than leaving them out of the statement, so the SQL
// default never gets a chance to apply and a NOT NULL column with a
// perfectly good default still fails at runtime. Pinned in the contract.
role: text("role").notNull(),
loginCount: integer("login_count").notNull().default(0),
});
/**
* Opens an in-memory database and wraps it in the drizzle proxy driver.
* `:memory:` is what keeps this offline: no server to reach, nothing on disk.
* The raw handle comes back beside the drizzle instance because the migration
* SQL the migrator hands back is a plain string with no parameters, so it goes
* straight to sqlite.exec rather than back through the query builder.
*/
export function openDatabase() {
const sqlite = new DatabaseSync(":memory:");
const proxy = async (query, params, method) => {
if (method === "run") {
sqlite.prepare(query).run(...params);
return { rows: [] };
}
const statement = sqlite.prepare(query);
// Positional rows, not objects. This is the whole trick.
statement.setReturnArrays(true);
const rows = statement.all(...params);
// `get` wants the row itself, not a list holding it, and undefined when
// there is none: mapGetResult treats a falsy row as "no result", while an
// empty array would read as a row whose every column is undefined.
return { rows: method === "get" ? rows[0] : rows };
};
return { sqlite, db: drizzle(proxy) };
}
/**
* The same wiring with setReturnArrays(true) left out, kept so the contract
* can assert what going wrong looks like. Do not copy this one.
*/
export function drizzleOverObjectRows(sqlite) {
return drizzle(async (query, params, method) => {
const rows = sqlite.prepare(query).all(...params);
return { rows: method === "get" ? rows[0] : rows };
});
}
/**
* Runs the committed migration folder. The proxy migrator splits the work in
* a way the name hides: its own bookkeeping goes through the driver, not
* through this callback. It runs CREATE TABLE IF NOT EXISTS
* __drizzle_migrations and then SELECT id, hash, created_at ... LIMIT 1
* itself, reads drizzle/meta/_journal.json, and hands the callback only the
* migration SQL of every entry whose `when` is newer than the created_at it
* just read, each file split on --> statement-breakpoint, plus the INSERT
* that records it. So the callback never sees the migrations table being
* created, and the driver has to answer more than "run": that SELECT arrives
* as method "values". Both are pinned in the contract.
*
* Returning the list is what makes "did the second run do nothing?" a
* checkable question rather than a claim.
*/
export async function applyMigrations({ sqlite, db }) {
const executed = [];
await migrate(
db,
async (queries) => {
for (const query of queries) {
executed.push(query);
sqlite.exec(query);
}
},
{ migrationsFolder: fileURLToPath(new URL("../drizzle", import.meta.url)) },
);
return executed;
}
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
import { DatabaseSync } from "node:sqlite";
import { fileURLToPath } from "node:url";
import { eq, sql } from "drizzle-orm";
import { drizzle } from "drizzle-orm/sqlite-proxy";
import { migrate } from "drizzle-orm/sqlite-proxy/migrator";
import {
applyMigrations,
drizzleOverObjectRows,
openDatabase,
users,
} from "../src/db.mjs";
// drizzle-orm's exports map lists every driver and not "./package.json", so
// the usual way to read a dependency's own version off disk throws instead of
// returning it. Reading the file is the way in.
const require = createRequire(import.meta.url);
assert.throws(() => require("drizzle-orm/package.json"), {
code: "ERR_PACKAGE_PATH_NOT_EXPORTED",
});
const version = JSON.parse(
readFileSync(new URL("../node_modules/drizzle-orm/package.json", import.meta.url)),
).version;
assert.equal(version, "0.45.2");
// The driver choice, stated as an assertion rather than as a comment. The
// natural import for "drizzle plus the SQLite that ships inside Node" is not
// published on this version — it exists only on the 1.0.0 release candidates
// — so sqlite-proxy is what a working answer has to use today.
const nodeSqliteDriver = await import("drizzle-orm/node-sqlite").then(
() => null,
(err) => err,
);
assert.equal(nodeSqliteDriver?.code, "ERR_PACKAGE_PATH_NOT_EXPORTED");
assert.ok(await import("drizzle-orm/sqlite-proxy"));
const handle = openDatabase();
const { db, sqlite } = handle;
// The migration folder is hand-written and committed: two DDL statements
// split on drizzle-kit's --> statement-breakpoint marker, plus the row the
// migrator writes into __drizzle_migrations to remember it did so.
const firstRun = await applyMigrations(handle);
assert.equal(firstRun.length, 3);
assert.match(firstRun[0], /CREATE TABLE `users`/);
assert.match(firstRun[1], /CREATE UNIQUE INDEX `users_email_unique`/);
assert.match(firstRun[2], /INSERT INTO `__drizzle_migrations`/);
// Second run is a no-op. The migrator compares the journal's `when` against
// the newest created_at it finds, so re-running against a live database
// applies nothing rather than failing on "table users already exists".
assert.deepEqual(await applyMigrations(handle), []);
assert.equal(
sqlite.prepare("select count(*) as n from __drizzle_migrations").get().n,
1,
);
// The migrations table exists even though the callback was never asked to
// create it: the migrator runs its own bookkeeping through the driver. Which
// means a proxy that only handles the methods a query builder uses is not
// enough — the bookkeeping SELECT arrives as "values", and a driver that
// switches on "all" alone never answers it.
assert.ok(!firstRun.some((query) => /IF NOT EXISTS/i.test(query)));
const seenMethods = [];
const probe = new DatabaseSync(":memory:");
await migrate(
drizzle(async (query, params, method) => {
seenMethods.push(method);
if (method === "run") {
probe.prepare(query).run(...params);
return { rows: [] };
}
const statement = probe.prepare(query);
statement.setReturnArrays(true);
return { rows: statement.all(...params) };
}),
async () => {},
{ migrationsFolder: fileURLToPath(new URL("../drizzle", import.meta.url)) },
);
assert.deepEqual(seenMethods, ["run", "values"]);
// .returning() hands back the row the database actually stored, not the
// object that went in: the id AUTOINCREMENT assigned is there, and so is the
// login_count the insert never mentioned.
const inserted = await db
.insert(users)
.values({ email: "ada@example.com", displayName: "Ada Lovelace", role: "admin" })
.returning();
assert.deepEqual(inserted, [
{
id: 1,
email: "ada@example.com",
displayName: "Ada Lovelace",
role: "admin",
loginCount: 0,
},
]);
await db.insert(users).values([
{ email: "grace@example.com", displayName: "Grace Hopper", role: "user" },
{
email: "katherine@example.com",
displayName: "Katherine Johnson",
role: "user",
loginCount: 7,
},
]);
// A select comes back keyed by the schema's JS names rather than the column
// names, which is the whole of what drizzle does to a row here. It does not
// touch the values: for a plain integer or text column mapFromDriverValue is
// the identity function, so `typeof id === "number"` is node:sqlite's doing
// and not a conversion drizzle performed. Worth knowing before trusting a
// declared type to coerce anything.
const all = await db.select().from(users);
assert.equal(all.length, 3);
assert.deepEqual(Object.keys(all[0]), [
"id",
"email",
"displayName",
"role",
"loginCount",
]);
assert.equal(typeof all[0].id, "number");
assert.equal(typeof all[0].displayName, "string");
assert.equal(typeof all[2].loginCount, "number");
assert.equal(all[2].loginCount, 7);
assert.equal(users.loginCount.mapFromDriverValue("7"), "7");
// .where(eq(...)) filters in SQL, not in JavaScript: the bound value reaches
// the statement as a parameter and only one row comes back.
const filtered = await db
.select()
.from(users)
.where(eq(users.email, "grace@example.com"));
assert.equal(filtered.length, 1);
assert.equal(filtered[0].displayName, "Grace Hopper");
assert.deepEqual(db.select().from(users).where(eq(users.id, 2)).toSQL().params, [2]);
// .get() on a miss is undefined, not an empty row. Worth an assertion because
// the proxy driver has to return undefined rather than [] for that to hold.
assert.equal(await db.select().from(users).where(eq(users.id, 99)).get(), undefined);
// Omitting a notNull column is a TypeScript error at build time. It is also a
// runtime error, which is the half a JavaScript contract can prove, and the
// runtime half is the one that matters when the insert values come from a
// parsed request body that the compiler never saw.
const missingDisplayName = await db
.insert(users)
.values({ email: "alan@example.com", role: "user" })
.catch((err) => err);
assert.equal(missingDisplayName.cause.message, "NOT NULL constraint failed: users.display_name");
// And the sharper version of the same trap. `role` has DEFAULT 'user' in the
// migration, so the SQL default would have covered the omission — except
// drizzle does not omit the column. It writes a literal null into the values
// list, which beats the default and hits the NOT NULL constraint. A column's
// SQL default only helps if the drizzle schema repeats it as .default().
const missingRole = await db
.insert(users)
.values({ email: "alan@example.com", displayName: "Alan Turing" })
.catch((err) => err);
assert.equal(missingRole.cause.message, "NOT NULL constraint failed: users.role");
assert.match(
missingRole.query,
/insert into "users" \("id", "email", "display_name", "role", "login_count"\) values \(null, \?, \?, null, \?\)/,
);
// A unique violation throws, and the SQLite message is NOT on the error you
// catch. drizzle 0.45 wraps every failed query in DrizzleQueryError, whose
// own message is the SQL and the parameters; the driver's error is the cause.
// Matching on err.message for "UNIQUE constraint failed" therefore never
// fires, which is the measurement that corrected the first draft of this file.
const duplicate = await db
.insert(users)
.values({ email: "ada@example.com", displayName: "Ada again", role: "user" })
.catch((err) => err);
assert.equal(duplicate.constructor.name, "DrizzleQueryError");
assert.ok(!duplicate.message.includes("UNIQUE constraint failed"));
assert.match(duplicate.message, /^Failed query: insert into "users" .*\nparams: /s);
assert.equal(duplicate.cause.message, "UNIQUE constraint failed: users.email");
assert.equal(duplicate.cause.code, "ERR_SQLITE_ERROR");
// SQLITE_CONSTRAINT_UNIQUE vs SQLITE_CONSTRAINT_NOTNULL. The extended result
// codes tell the two constraint failures apart without parsing English.
assert.equal(duplicate.cause.errcode, 2067);
assert.equal(missingRole.cause.errcode, 1299);
// The wrapper is not useless: it carries the statement and the bound values.
assert.deepEqual(duplicate.params, ["ada@example.com", "Ada again", "user", 0]);
// The security-relevant one. An interpolated value inside sql`` is bound, not
// concatenated: the statement holds a ?, and the quote-carrying value travels
// beside it in params. So the classic tautology stays a string and matches the
// zero users whose email literally is that string.
const hostile = "ada@example.com' OR '1'='1";
const bound = db.select({ id: users.id }).from(users).where(sql`${users.email} = ${hostile}`);
const boundSql = bound.toSQL();
assert.equal(boundSql.sql, 'select "id" from "users" where "users"."email" = ?');
assert.deepEqual(boundSql.params, [hostile]);
assert.ok(!boundSql.sql.includes("'"));
assert.deepEqual(await bound, []);
// The contrast, so the assertion above is about escaping and not about the
// value being harmless. sql.raw is the escape hatch that concatenates: the
// same string lands in the statement text, the tautology fires, and the query
// returns every row in the table.
const concatenated = db
.select({ id: users.id })
.from(users)
.where(sql.raw(`"users"."email" = '${hostile}'`));
const concatenatedSql = concatenated.toSQL();
assert.deepEqual(concatenatedSql.params, []);
assert.ok(concatenatedSql.sql.endsWith("OR '1'='1'"));
assert.deepEqual(await concatenated, [{ id: 1 }, { id: 2 }, { id: 3 }]);
// Same story for eq(): a value carrying a statement terminator is one
// parameter, and the table it names is still there afterwards.
const dropper = "ada@example.com'; DROP TABLE users; --";
assert.deepEqual(db.select().from(users).where(eq(users.email, dropper)).toSQL().params, [
dropper,
]);
assert.deepEqual(await db.select().from(users).where(eq(users.email, dropper)), []);
assert.equal((await db.select().from(users)).length, 3);
// Finally, what the driver's setReturnArrays(true) is buying. Give drizzle
// node:sqlite's default object rows and nothing complains: same row count,
// same keys, every value undefined. A silent wrong answer is the reason that
// line is in the driver and this assertion is in the contract.
const broken = await drizzleOverObjectRows(sqlite).select().from(users);
assert.equal(broken.length, 3);
assert.deepEqual(Object.keys(broken[0]), [
"id",
"email",
"displayName",
"role",
"loginCount",
]);
assert.equal(broken[0].id, undefined);
assert.equal(broken[0].email, undefined);
console.log("contract ok: drizzle-orm", version, "on", process.version);