@expressive/sql 0.6.0 → 0.8.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 (40) hide show
  1. package/README.md +3 -3
  2. package/dist/codecs.d.ts +16 -0
  3. package/dist/codecs.js +104 -0
  4. package/dist/codecs.js.map +1 -0
  5. package/dist/connection/Connection.d.ts +5 -0
  6. package/dist/connection/Connection.js +39 -24
  7. package/dist/connection/Connection.js.map +1 -1
  8. package/dist/connection/Generator.js +1 -1
  9. package/dist/connection/Generator.js.map +1 -1
  10. package/dist/datatypes.d.ts +5 -25
  11. package/dist/datatypes.js +0 -4
  12. package/dist/datatypes.js.map +1 -1
  13. package/dist/index.d.ts +2 -6
  14. package/dist/index.js +2 -6
  15. package/dist/sqlite/SQLiteConnection.d.ts +9 -4
  16. package/dist/sqlite/SQLiteConnection.js +51 -29
  17. package/dist/sqlite/SQLiteConnection.js.map +1 -1
  18. package/dist/sqlite/SQLiteGenerator.d.ts +2 -2
  19. package/dist/sqlite/SQLiteGenerator.js +0 -3
  20. package/dist/sqlite/SQLiteGenerator.js.map +1 -1
  21. package/dist/sqlite/engine.d.ts +40 -1
  22. package/dist/sqlite/engine.js +58 -6
  23. package/dist/sqlite/engine.js.map +1 -1
  24. package/package.json +5 -3
  25. package/skills/expressive-sql/SKILL.md +48 -30
  26. package/dist/columns/Bool.d.ts +0 -37
  27. package/dist/columns/Bool.js +0 -28
  28. package/dist/columns/Bool.js.map +0 -1
  29. package/dist/columns/Num.d.ts +0 -59
  30. package/dist/columns/Num.js +0 -42
  31. package/dist/columns/Num.js.map +0 -1
  32. package/dist/columns/One.d.ts +0 -25
  33. package/dist/columns/One.js +0 -15
  34. package/dist/columns/One.js.map +0 -1
  35. package/dist/columns/Str.d.ts +0 -36
  36. package/dist/columns/Str.js +0 -21
  37. package/dist/columns/Str.js.map +0 -1
  38. package/dist/columns/Time.d.ts +0 -52
  39. package/dist/columns/Time.js +0 -45
  40. package/dist/columns/Time.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"engine.js","names":[],"sources":["../../src/sqlite/engine.ts"],"sourcesContent":["/**\n * A SQLite host - what `SQLiteConnection` runs statements on.\n *\n * Pass one in place of a filename for a SQLite the built-in loader cannot open.\n * It is used as given - foreign keys are not switched on, and the connection's `close()` leaves it open.\n */\nexport interface Engine extends Engine.Statements {\n /** Release the database. Called only on an engine the connection opened. */\n close(): Promise<void>;\n /**\n * Open a transaction on its own session.\n *\n * Without it the connection issues `BEGIN`, `COMMIT` and `ROLLBACK` through `exec`.\n */\n transaction?(): Promise<Engine.Session>;\n /**\n * Run statements atomically.\n *\n * `sync` applies through it when present; a table rebuild then needs foreign keys off.\n */\n batch?(sql: string[]): Promise<void>;\n}\n\nexport declare namespace Engine {\n /** Statement methods an engine and a session share. Parameters are positional. */\n interface Statements {\n /** Run a statement, resolving every row. */\n all(sql: string, params?: any[]): Promise<any[]>;\n /** Run a statement, resolving the first row. */\n get(sql: string, params?: any[]): Promise<any>;\n /** Run a statement, resolving how many rows changed. */\n run(sql: string, params?: any[]): Promise<{ changes: number }>;\n /** Run one or more statements without parameters. */\n exec(sql: string): Promise<void>;\n }\n\n /** A transaction's own handle - statements inside `db.transaction(fn)` run on it. */\n interface Session extends Statements {\n commit(): Promise<void>;\n rollback(): Promise<void>;\n }\n}\n\nconst DRIVERS = [bunSqlite, nodeSqlite, betterSqlite3, sqlite3, libsql];\n\nexport async function createEngine(filename: string): Promise<Engine> {\n for (const load of DRIVERS) {\n const engine = await load(filename).catch(() => null);\n\n if (engine) {\n await engine.exec(\"PRAGMA foreign_keys = ON\");\n return engine;\n }\n }\n\n throw new Error(\n \"No compatible SQLite driver found. Run under Bun or Node >=24, \" +\n \"or install one of: better-sqlite3, sqlite3, @libsql/client.\"\n );\n}\n\nfunction optional(name: string): Promise<any> {\n return import(name);\n}\n\nasync function bunSqlite(file: string): Promise<Engine | null> {\n if (typeof (globalThis as any).Bun === \"undefined\")\n return null;\n\n const { Database } = await optional(\"bun:sqlite\");\n\n return syncEngine(new Database(file));\n}\n\nasync function nodeSqlite(file: string): Promise<Engine | null> {\n const { DatabaseSync } = await optional(\"node:sqlite\");\n\n return syncEngine(new DatabaseSync(file));\n}\n\nasync function betterSqlite3(file: string): Promise<Engine | null> {\n const { default: Database } = await optional(\"better-sqlite3\");\n\n return syncEngine(new Database(file));\n}\n\nasync function sqlite3(file: string): Promise<Engine | null> {\n const { default: { Database } } = await optional(\"sqlite3\");\n\n return asyncEngine(new Database(file));\n}\n\nasync function libsql(file: string): Promise<Engine | null> {\n const { createClient } = await optional(\"@libsql/client\");\n const url = file === \":memory:\" ? \":memory:\" : `file:${file}`;\n\n return libsqlEngine(createClient({ url }));\n}\n\nfunction syncEngine(db: any): Engine {\n return {\n async all(sql, params = []) {\n return db.prepare(sql).all(...params);\n },\n async get(sql, params = []) {\n return db.prepare(sql).get(...params);\n },\n async run(sql, params = []) {\n return { changes: db.prepare(sql).run(...params).changes };\n },\n async exec(sql) {\n db.exec(sql);\n },\n async close() {\n db.close();\n }\n };\n}\n\nfunction asyncEngine(db: any): Engine {\n const call = (method: string, sql: string, params: any[]) =>\n new Promise<any>((resolve, reject) => {\n db[method](sql, params, function (this: any, err: any, rows: any) {\n if (err) reject(err);\n else resolve(method === \"run\" ? this : rows);\n });\n });\n\n const done = (resolve: () => void, reject: (err: any) => void) =>\n (err: any) => err ? reject(err) : resolve();\n\n return {\n all: (sql, params = []) => call(\"all\", sql, params),\n get: (sql, params = []) => call(\"get\", sql, params),\n run: (sql, params = []) => call(\"run\", sql, params).then(ctx => ({ changes: ctx.changes })),\n exec: sql => new Promise((resolve, reject) => db.exec(sql, done(resolve, reject))),\n close: () => new Promise((resolve, reject) => db.close(done(resolve, reject)))\n };\n}\n\nfunction libsqlEngine(client: any): Engine {\n const execute = (sql: string, args: any[]) => client.execute({ sql, args });\n\n return {\n async all(sql, params = []) {\n return (await execute(sql, params)).rows;\n },\n async get(sql, params = []) {\n return (await execute(sql, params)).rows[0];\n },\n async run(sql, params = []) {\n return { changes: Number((await execute(sql, params)).rowsAffected) };\n },\n async exec(sql) {\n await client.executeMultiple(sql);\n },\n async close() {\n client.close();\n }\n };\n}\n"],"mappings":";AA2CA,MAAM,UAAU;CAAC;CAAW;CAAY;CAAe;CAAS;CAAO;AAEvE,eAAsB,aAAa,UAAmC;AACpE,MAAK,MAAM,QAAQ,SAAS;EAC1B,MAAM,SAAS,MAAM,KAAK,SAAS,CAAC,YAAY,KAAK;AAErD,MAAI,QAAQ;AACV,SAAM,OAAO,KAAK,2BAA2B;AAC7C,UAAO;;;AAIX,OAAM,IAAI,MACR,6HAED;;AAGH,SAAS,SAAS,MAA4B;AAC5C,QAAO,OAAO;;AAGhB,eAAe,UAAU,MAAsC;AAC7D,KAAI,OAAQ,WAAmB,QAAQ,YACrC,QAAO;CAET,MAAM,EAAE,aAAa,MAAM,SAAS,aAAa;AAEjD,QAAO,WAAW,IAAI,SAAS,KAAK,CAAC;;AAGvC,eAAe,WAAW,MAAsC;CAC9D,MAAM,EAAE,iBAAiB,MAAM,SAAS,cAAc;AAEtD,QAAO,WAAW,IAAI,aAAa,KAAK,CAAC;;AAG3C,eAAe,cAAc,MAAsC;CACjE,MAAM,EAAE,SAAS,aAAa,MAAM,SAAS,iBAAiB;AAE9D,QAAO,WAAW,IAAI,SAAS,KAAK,CAAC;;AAGvC,eAAe,QAAQ,MAAsC;CAC3D,MAAM,EAAE,SAAS,EAAE,eAAe,MAAM,SAAS,UAAU;AAE3D,QAAO,YAAY,IAAI,SAAS,KAAK,CAAC;;AAGxC,eAAe,OAAO,MAAsC;CAC1D,MAAM,EAAE,iBAAiB,MAAM,SAAS,iBAAiB;AAGzD,QAAO,aAAa,aAAa,EAAE,KAFvB,SAAS,aAAa,aAAa,QAAQ,QAEf,CAAC,CAAC;;AAG5C,SAAS,WAAW,IAAiB;AACnC,QAAO;EACL,MAAM,IAAI,KAAK,SAAS,EAAE,EAAE;AAC1B,UAAO,GAAG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MAAM,QAAQ,KAAK,OAAO,EAAE;;EAEtC,MAAM,IAAI,KAAK,SAAS,EAAE,EAAE;AAC1B,WAAQ,MAAM,QAAQ,KAAK,OAAO,EAAE,KAAK;;EAE3C,MAAM,IAAI,KAAK,SAAS,EAAE,EAAE;AAC1B,UAAO,EAAE,SAAS,QAAQ,MAAM,QAAQ,KAAK,OAAO,EAAE,aAAa,EAAE;;EAEvE,MAAM,KAAK,KAAK;AACd,SAAM,OAAO,gBAAgB,IAAI;;EAEnC,MAAM,QAAQ;AACZ,UAAO,OAAO;;EAEjB"}
1
+ {"version":3,"file":"engine.js","names":[],"sources":["../../src/sqlite/engine.ts"],"sourcesContent":["/**\n * A SQLite host - what `SQLiteConnection` runs statements on.\n *\n * Pass one in place of a filename for a SQLite the built-in loader cannot open.\n * It is used as given - foreign keys are not switched on, and the connection's `close()` leaves it open.\n */\nexport interface Engine extends Engine.Statements {\n /** Release the database. Called only on an engine the connection opened. */\n close(): Promise<void>;\n /**\n * Open a transaction on its own session.\n *\n * Without it the connection issues `BEGIN`, `COMMIT` and `ROLLBACK` through `exec`.\n */\n transaction?(): Promise<Engine.Session>;\n /**\n * Run statements atomically.\n *\n * `sync` applies through it when present; a table rebuild then needs foreign keys off.\n */\n batch?(sql: string[]): Promise<void>;\n}\n\nexport declare namespace Engine {\n /** Statement methods an engine and a session share. Parameters are positional. */\n interface Statements {\n /** Run a statement, resolving every row. */\n all(sql: string, params?: any[]): Promise<any[]>;\n /** Run a statement, resolving the first row. */\n get(sql: string, params?: any[]): Promise<any>;\n /** Run a statement, resolving how many rows changed. */\n run(sql: string, params?: any[]): Promise<{ changes: number }>;\n /** Run one or more statements without parameters. */\n exec(sql: string): Promise<void>;\n }\n\n /** A transaction's own handle - statements inside `db.transaction(fn)` run on it. */\n interface Session extends Statements {\n commit(): Promise<void>;\n rollback(): Promise<void>;\n }\n}\n\nconst DRIVERS = [bunSqlite, nodeSqlite, betterSqlite3, sqlite3, libsql];\n\nconst REMOTE = /^(libsql|https?|wss?):\\/\\//;\n\nexport async function createEngine(filename: string): Promise<Engine> {\n if (REMOTE.test(filename))\n return libsql(filename, filename);\n\n for (const load of DRIVERS) {\n const engine = await load(filename).catch(() => null);\n\n if (engine) {\n await engine.exec(\"PRAGMA foreign_keys = ON\");\n return engine;\n }\n }\n\n throw new Error(\n \"No compatible SQLite driver found. Run under Bun or Node >=24, \" +\n \"or install one of: better-sqlite3, sqlite3, @libsql/client.\"\n );\n}\n\nfunction optional(name: string): Promise<any> {\n return import(name);\n}\n\nasync function bunSqlite(file: string): Promise<Engine | null> {\n if (typeof (globalThis as any).Bun === \"undefined\")\n return null;\n\n const { Database } = await optional(\"bun:sqlite\");\n\n return syncEngine(new Database(file));\n}\n\nasync function nodeSqlite(file: string): Promise<Engine | null> {\n const { DatabaseSync } = await optional(\"node:sqlite\");\n\n return syncEngine(new DatabaseSync(file));\n}\n\nasync function betterSqlite3(file: string): Promise<Engine | null> {\n const { default: Database } = await optional(\"better-sqlite3\");\n\n return syncEngine(new Database(file));\n}\n\nasync function sqlite3(file: string): Promise<Engine | null> {\n const { default: { Database } } = await optional(\"sqlite3\");\n\n return asyncEngine(new Database(file));\n}\n\nasync function libsql(file: string, url = file === \":memory:\" ? file : `file:${file}`): Promise<Engine> {\n const { createClient } = await optional(\"@libsql/client\");\n\n return libsqlEngine(createClient({ url }));\n}\n\nfunction syncEngine(db: any): Engine {\n return {\n async all(sql, params = []) {\n return db.prepare(sql).all(...params);\n },\n async get(sql, params = []) {\n return db.prepare(sql).get(...params);\n },\n async run(sql, params = []) {\n return { changes: db.prepare(sql).run(...params).changes };\n },\n async exec(sql) {\n db.exec(sql);\n },\n async close() {\n db.close();\n }\n };\n}\n\nfunction asyncEngine(db: any): Engine {\n const call = (method: string, sql: string, params: any[]) =>\n new Promise<any>((resolve, reject) => {\n db[method](sql, params, function (this: any, err: any, rows: any) {\n if (err) reject(err);\n else resolve(method === \"run\" ? this : rows);\n });\n });\n\n const done = (resolve: () => void, reject: (err: any) => void) =>\n (err: any) => err ? reject(err) : resolve();\n\n return {\n all: (sql, params = []) => call(\"all\", sql, params),\n get: (sql, params = []) => call(\"get\", sql, params),\n run: (sql, params = []) => call(\"run\", sql, params).then(ctx => ({ changes: ctx.changes })),\n exec: sql => new Promise((resolve, reject) => db.exec(sql, done(resolve, reject))),\n close: () => new Promise((resolve, reject) => db.close(done(resolve, reject)))\n };\n}\n\nexport function host(source: Engine | D1Database | LibSQLClient): Engine {\n const has = (key: string) => source && typeof source == \"object\" && key in source;\n\n if (has(\"all\"))\n return source as Engine;\n\n if (has(\"execute\"))\n return libsqlEngine(source as LibSQLClient);\n\n if (has(\"prepare\") && has(\"batch\"))\n return d1Engine(source as D1Database);\n\n throw new TypeError(\"Unknown SQLite source. Pass a filename, a libSQL address, a D1 binding, a libSQL client or an Engine.\");\n}\n\nexport const migrations = new WeakMap<Engine, (sql: string[]) => Promise<unknown>>();\n\n/** A libSQL client from `@libsql/client` 0.18 or later - local, Turso or any libSQL server. */\nexport interface LibSQLClient extends LibSQLStatements {\n batch(sql: string[], mode: \"write\"): Promise<unknown>;\n migrate(sql: string[]): Promise<unknown>;\n transaction(mode: \"write\"): Promise<LibSQLStatements & { commit(): Promise<void>; rollback(): Promise<void> }>;\n close(): void;\n}\n\ninterface LibSQLStatements {\n execute(statement: { sql: string, args: any[] }): Promise<{ rows: any[], rowsAffected: number }>;\n executeMultiple(sql: string): Promise<void>;\n}\n\nfunction libsqlEngine(client: LibSQLClient): Engine {\n const engine: Engine = {\n ...libsqlStatements(client),\n async batch(sql) {\n await client.batch(sql, \"write\");\n },\n async transaction() {\n const tx = await client.transaction(\"write\");\n\n return {\n ...libsqlStatements(tx),\n commit: () => tx.commit(),\n rollback: () => tx.rollback()\n };\n },\n async close() {\n client.close();\n }\n };\n\n migrations.set(engine, sql => client.migrate(sql));\n\n return engine;\n}\n\nfunction libsqlStatements(client: LibSQLStatements): Engine.Statements {\n const execute = (sql: string, args: any[]) => client.execute({ sql, args });\n\n return {\n async all(sql, params = []) {\n return (await execute(sql, params)).rows;\n },\n async get(sql, params = []) {\n return (await execute(sql, params)).rows[0];\n },\n async run(sql, params = []) {\n return { changes: Number((await execute(sql, params)).rowsAffected) };\n },\n async exec(sql) {\n await client.executeMultiple(sql);\n }\n };\n}\n\n/** A Cloudflare D1 binding, such as a Worker's `env.DB`. */\nexport interface D1Database {\n prepare(sql: string): D1Statement;\n batch(statements: D1Statement[]): Promise<unknown>;\n}\n\ninterface D1Statement {\n bind(...values: any[]): D1Statement;\n all(): Promise<{ results: any[] }>;\n first(): Promise<any>;\n run(): Promise<{ meta: { changes: number } }>;\n}\n\nfunction d1Engine(db: D1Database): Engine {\n const statement = (sql: string, params: any[] = []) => db.prepare(sql).bind(...params);\n\n return {\n async all(sql, params) {\n return (await statement(sql, params).all()).results;\n },\n async get(sql, params) {\n return await statement(sql, params).first() ?? undefined;\n },\n async run(sql, params) {\n return { changes: (await statement(sql, params).run()).meta.changes };\n },\n async exec(sql) {\n await db.prepare(sql).run();\n },\n async batch(sql) {\n await db.batch(sql.map(sql => db.prepare(sql)));\n },\n async transaction(): Promise<never> {\n throw new Error(\"D1 has no interactive transactions.\");\n },\n async close() {}\n };\n}\n"],"mappings":";AA2CA,MAAM,UAAU;CAAC;CAAW;CAAY;CAAe;CAAS;CAAO;AAEvE,MAAM,SAAS;AAEf,eAAsB,aAAa,UAAmC;AACpE,KAAI,OAAO,KAAK,SAAS,CACvB,QAAO,OAAO,UAAU,SAAS;AAEnC,MAAK,MAAM,QAAQ,SAAS;EAC1B,MAAM,SAAS,MAAM,KAAK,SAAS,CAAC,YAAY,KAAK;AAErD,MAAI,QAAQ;AACV,SAAM,OAAO,KAAK,2BAA2B;AAC7C,UAAO;;;AAIX,OAAM,IAAI,MACR,6HAED;;AAGH,SAAS,SAAS,MAA4B;AAC5C,QAAO,OAAO;;AAGhB,eAAe,UAAU,MAAsC;AAC7D,KAAI,OAAQ,WAAmB,QAAQ,YACrC,QAAO;CAET,MAA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0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "Expressive ORM on SQL: entities, Query and an embedded SQLite store from one import.",
5
5
  "keywords": [
6
6
  "orm",
@@ -56,16 +56,18 @@
56
56
  "test": "bun run typecheck && bun run coverage"
57
57
  },
58
58
  "dependencies": {
59
- "@expressive/orm": "^0.14.0",
59
+ "@expressive/orm": "^0.15.0",
60
60
  "sql-formatter": "^10.7.2"
61
61
  },
62
62
  "devDependencies": {
63
63
  "@expressive/mvc": "^0.94.2",
64
+ "@libsql/client": "^0.18.0",
65
+ "miniflare": "^4.20260730.0",
64
66
  "tsdown": "^0.20.1"
65
67
  },
66
68
  "peerDependencies": {
67
69
  "@expressive/mvc": "^0.94.0",
68
- "@libsql/client": ">=0.5.0",
70
+ "@libsql/client": ">=0.18.0",
69
71
  "better-sqlite3": ">=11.0.0",
70
72
  "sqlite3": ">=5.0.0"
71
73
  },
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: expressive-sql
3
- description: Expressive ORM on SQL (@expressive/sql) - SQLiteConnection with a built-in or custom Engine, sync and plan, the expressive sql CLI, the sql.* datatype vocabulary and validation, and the SQL Connection and Generator base for dialects. Use when connecting entities to SQLite, choosing column datatypes, syncing or checking a schema, plugging in a SQLite host, or writing a SQL driver.
3
+ description: Expressive ORM on SQL (@expressive/sql) - SQLiteConnection with a built-in or custom Engine, sync and plan, the expressive sql CLI, the sql.* datatype shorthand and codecs, and the SQL Connection and Generator base for dialects. Use when connecting entities to SQLite, Cloudflare D1 or libSQL and Turso, choosing column datatypes, syncing or checking a schema, plugging in a SQLite host, or writing a SQL driver.
4
4
  ---
5
5
 
6
6
  # @expressive/sql
@@ -11,7 +11,7 @@ Expressive ORM on SQL, with embedded SQLite. Re-exports `@expressive/orm` - enti
11
11
  npm install @expressive/sql @expressive/mvc
12
12
  ```
13
13
 
14
- SQLite is built into Bun (`bun:sqlite`) and Node 24 (`node:sqlite`). Elsewhere add one of `better-sqlite3`, `sqlite3` or `@libsql/client`; the first found is used. For Postgres and live rows install `@expressive/postgres` (skill `expressive-postgres`), which re-exports this package.
14
+ SQLite is built into Bun (`bun:sqlite`) and Node 24 (`node:sqlite`). Elsewhere add one of `better-sqlite3`, `sqlite3` or `@libsql/client` (0.18 or later); the first found is used. For Postgres and live rows install `@expressive/postgres` (skill `expressive-postgres`), which re-exports this package.
15
15
 
16
16
  ## Connect
17
17
 
@@ -56,6 +56,38 @@ Two optional members, for hosts without `BEGIN` and `COMMIT` on one connection:
56
56
  - `transaction()` - resolves a session, the four statements plus `commit()` and `rollback()`. Every statement inside `db.transaction(fn)` runs on it.
57
57
  - `batch(sql: string[])` - runs statements atomically; `sync` applies through it. A table rebuild in a batch needs foreign keys off, or dropping the old table cascades; an engine that keeps them on refuses it.
58
58
 
59
+ ### Hosts
60
+
61
+ In place of the filename, `new` also takes a D1 binding, a libSQL `Client` or a libSQL address, told apart by shape. A given binding or client is used as is; `close()` leaves it open.
62
+
63
+ On Workers, open once from the first request's binding, and drop it when `sync` fails - a second `new` while entities hold a connection throws:
64
+
65
+ ```ts
66
+ let ready: Promise<unknown> | undefined;
67
+
68
+ function open(DB: D1Database){
69
+ const db = SQLiteConnection.new([User], DB);
70
+
71
+ return Promise.resolve(db).catch(async error => {
72
+ ready = undefined;
73
+ await db.close();
74
+ throw error;
75
+ });
76
+ }
77
+
78
+ export default {
79
+ async fetch(request: Request, env: { DB: D1Database }) {
80
+ await (ready ??= open(env.DB));
81
+ return Response.json(await User.find({}));
82
+ }
83
+ };
84
+ ```
85
+
86
+ - D1 - `sync` applies as one batch, a few round trips per table each cold start. `transaction` throws. Foreign keys stay on, so `sync(true, true)` refuses a rebuild.
87
+ - libSQL address - `libsql:`, `https:`, `http:`, `ws:` or `wss:` opens `@libsql/client` 0.18+; token as `?authToken=`. Loaded at runtime, so under a bundler (Workers) pass a `createClient` client instead. An `undefined` or empty source opens in memory - check an address from the environment first.
88
+ - Every libSQL client - each `transaction` is a libSQL write transaction (`BEGIN IMMEDIATE`) holding the connection's lock, so transactions run one at a time app-wide. `sync` is one batch; a rebuild runs through `client.migrate`, foreign keys off for it alone. Local libSQL enforces foreign keys by default; remote gets the server's setting.
89
+ - A `migrate` rebuild refuses dangling rows (`foreign_key_check`) even where foreign keys are off, and leaves them on.
90
+
59
91
  ## Sync
60
92
 
61
93
  Awaiting a connection runs `sync`:
@@ -79,26 +111,26 @@ The entry is the module that creates the connections - imported with `sync` held
79
111
 
80
112
  ## Datatypes
81
113
 
82
- `sql.*` picks a column's type; a factory takes its size. A config is portable - the same class syncs on SQLite and Postgres.
114
+ Datatypes are portable - orm declares them, and each connection maps them to its storage. `sql.*` is shorthand for the declaration: `str(sql.varchar(40))` is `str({ type: "varchar", length: 40 })`. A schema module importing only `@expressive/orm` writes the object form and binds here unchanged.
83
115
 
84
116
  | Helper | `sql.*` | SQLite |
85
117
  |---|---|---|
86
118
  | `str` | `text` (default), `varchar(n)`, `char(n)`, `uuid` | TEXT |
87
- | `num` | `integer` (default), `smallint`, `bigint`, `real`, `float`, `double`, `numeric(p, s)`, `decimal(p, s)` | INTEGER, REAL, NUMERIC |
88
- | `bool` | `boolean` (default), `integer` (1/0), `text` / `varchar(n)` with `either` | INTEGER, TEXT |
89
- | `date` | `timestamp` (default), `date`, `time`, `ms` (epoch ms), `seconds` or `integer` (epoch s), `text` | TEXT, INTEGER |
90
- | `one` | `integer` (default), `bigint` | INTEGER |
119
+ | `num` | `integer` (default), `smallint`, `bigint`, `real`, `double`, `numeric(p, s)`, `decimal(p, s)` | INTEGER, REAL, NUMERIC |
120
+ | `bool` | - (boolean) | INTEGER, 1 or 0 |
121
+ | `date` | `timestamp` (default), `date`, `time` | TEXT - ISO 8601 UTC to the ms; `date` as the local day `YYYY-MM-DD`; `time` as UTC `HH:MM:SS` |
122
+ | `json` | - | TEXT |
123
+ | `one` | - (the related key's) | the key's |
91
124
 
92
125
  ```ts
93
- import { Type, bool, date, key, num, sql, str } from '@expressive/sql';
126
+ import { Type, date, key, num, sql, str } from '@expressive/sql';
94
127
 
95
128
  class Product extends Type {
96
129
  id = key(sql.uuid); // UUIDv7 on insert
97
130
  code = str(sql.char(3));
98
131
  price = num(sql.numeric(10, 2));
99
- listed = bool(sql.text, { either: ["yes", "no"] });
100
- seen = date(sql.ms, null);
101
- edited = date.updated(sql.ms);
132
+ seen = date(null);
133
+ edited = date.updated();
102
134
  }
103
135
  ```
104
136
 
@@ -106,26 +138,12 @@ class Product extends Type {
106
138
  - A datatype of another helper, like `num(sql.text)`, is a type error.
107
139
  - Options a factory doesn't take go in an object - `date({ type: "timestamp", precision: 3 })`.
108
140
  - `sql.now` is the database's current time in the column's storage - as a `fallback`, in a statics write or comparison (`lessThan(sql.now)`), or in a `Query`. Statics read it from the app's clock. `"NOW"` is a deprecated alias.
109
- - Writes are validated - `varchar` and `char` length, integer ranges, `numeric` precision and scale. Importing `@expressive/sql` turns this on for every connection, `memory()` included.
110
-
111
- Add a datatype by augmenting the helper's `Types`:
112
-
113
- ```ts
114
- import { StringColumn, Type, str } from '@expressive/sql';
115
-
116
- declare module '@expressive/orm' {
117
- namespace str {
118
- interface Inet extends StringColumn { type: "inet" }
119
- interface Types { inet: Inet }
120
- }
121
- }
122
-
123
- class Device extends Type {
124
- address = str({ type: "inet" });
125
- }
126
- ```
141
+ - Writes are checked by the field on every connection - `varchar` and `char` length, integer ranges, decimal precision and scale. The SQL floor checks again before storing, so rows forwarded from a client meet the same rules.
142
+ - `Connection.new` throws for a datatype the connection can't store - `SQLiteConnection can't store json type 'blob' (Doc.blob).`
143
+ - A `date` type is a calendar day: a Date gives its local day, `"YYYY-MM-DD"` is that day, and it reads back as local midnight. It crosses the floor and is stored as `YYYY-MM-DD`, so zones never shift it. `sql.now` on it is the database's UTC day. A `time` is a UTC time of day, crossing as a Date on 1970-01-01 UTC.
144
+ - Storage-only types are gone: store epoch time as `num(sql.bigint)`, yes/no text as `str`.
127
145
 
128
- `StringColumn`, `NumericColumn`, `BooleanColumn`, `TimeColumn`, `ForeignColumn` are the column classes behind `str`, `num`, `bool`, `date` and `one`.
146
+ `codecs` maps each base helper to how SQL stores it (`Connection.Codec`). A dialect extends it - `new Map([...codecs, [date, myDateCodec]])` - and returns it from a protected `codecs` getter.
129
147
 
130
148
  ## SQL drivers
131
149
 
@@ -1,37 +0,0 @@
1
- import { bool } from "@expressive/orm";
2
-
3
- //#region src/columns/Bool.d.ts
4
- declare module '@expressive/orm' {
5
- namespace bool {
6
- interface Boolean extends BooleanColumn {
7
- type: "boolean";
8
- }
9
- interface Integer extends BooleanColumn {
10
- type: "integer";
11
- }
12
- interface Text extends BooleanColumn {
13
- type: "text";
14
- either: readonly [true: string, false: string];
15
- }
16
- interface VarChar extends BooleanColumn {
17
- type: "varchar";
18
- either: readonly [true: string, false: string];
19
- }
20
- interface Types {
21
- default: Boolean;
22
- boolean: Boolean;
23
- integer: Integer;
24
- text: Text;
25
- varchar: VarChar;
26
- }
27
- }
28
- }
29
- /** Column class behind `bool()` on SQL - `boolean`, `integer`, or `text` / `varchar` with `either`. */
30
- declare class BooleanColumn extends bool.Type {
31
- type: bool.DataType;
32
- get datatype(): string;
33
- set(value: unknown): string | number | boolean | null | undefined;
34
- }
35
- //#endregion
36
- export { BooleanColumn };
37
- //# sourceMappingURL=Bool.d.ts.map
@@ -1,28 +0,0 @@
1
- import { bool } from "@expressive/orm";
2
-
3
- //#region src/columns/Bool.ts
4
- /** Column class behind `bool()` on SQL - `boolean`, `integer`, or `text` / `varchar` with `either`. */
5
- var BooleanColumn = class extends bool.Type {
6
- constructor(..._args) {
7
- super(..._args);
8
- this.type = "boolean";
9
- }
10
- get datatype() {
11
- const { type, either } = this;
12
- if (type === "varchar" && either) {
13
- const [TRUE, FALSE] = either.map(String);
14
- return `varchar(${Math.max(TRUE.length, FALSE.length)})`;
15
- }
16
- return type;
17
- }
18
- set(value) {
19
- const out = super.set(value);
20
- if (out == null || this.either || this.type !== "boolean") return out;
21
- return value;
22
- }
23
- };
24
- bool.Type = BooleanColumn;
25
-
26
- //#endregion
27
- export { BooleanColumn };
28
- //# sourceMappingURL=Bool.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"Bool.js","names":[],"sources":["../../src/columns/Bool.ts"],"sourcesContent":["import { bool } from '@expressive/orm';\n\ndeclare module '@expressive/orm' {\n namespace bool {\n interface Boolean extends BooleanColumn {\n type: \"boolean\";\n }\n\n interface Integer extends BooleanColumn {\n type: \"integer\";\n }\n\n interface Text extends BooleanColumn {\n type: \"text\";\n either: readonly [true: string, false: string];\n }\n\n interface VarChar extends BooleanColumn {\n type: \"varchar\";\n either: readonly [true: string, false: string];\n }\n\n interface Types {\n default: Boolean;\n boolean: Boolean;\n integer: Integer;\n text: Text;\n varchar: VarChar;\n }\n }\n}\n\n/** Column class behind `bool()` on SQL - `boolean`, `integer`, or `text` / `varchar` with `either`. */\nexport class BooleanColumn extends bool.Type {\n type: bool.DataType = \"boolean\";\n\n get datatype() {\n const { type, either } = this;\n\n if (type === \"varchar\" && either) {\n const [TRUE, FALSE] = either.map(String);\n return `varchar(${Math.max(TRUE.length, FALSE.length)})`;\n }\n\n return type;\n }\n\n set(value: unknown) {\n const out = super.set(value);\n\n if (out == null || this.either || this.type !== \"boolean\")\n return out;\n\n return value as boolean;\n }\n}\n\nbool.Type = BooleanColumn;\n"],"mappings":";;;;AAiCA,IAAa,gBAAb,cAAmC,KAAK,KAAK;;;cACrB;;CAEtB,IAAI,WAAW;EACb,MAAM,EAAE,MAAM,WAAW;AAEzB,MAAI,SAAS,aAAa,QAAQ;GAChC,MAAM,CAAC,MAAM,SAAS,OAAO,IAAI,OAAO;AACxC,UAAO,WAAW,KAAK,IAAI,KAAK,QAAQ,MAAM,OAAO,CAAC;;AAGxD,SAAO;;CAGT,IAAI,OAAgB;EAClB,MAAM,MAAM,MAAM,IAAI,MAAM;AAE5B,MAAI,OAAO,QAAQ,KAAK,UAAU,KAAK,SAAS,UAC9C,QAAO;AAET,SAAO;;;AAIX,KAAK,OAAO"}
@@ -1,59 +0,0 @@
1
- import { num } from "@expressive/orm";
2
-
3
- //#region src/columns/Num.d.ts
4
- declare module '@expressive/orm' {
5
- namespace num {
6
- interface Integer extends NumericColumn {
7
- type: "integer";
8
- }
9
- interface SmallInt extends NumericColumn {
10
- type: "smallint";
11
- }
12
- interface BigInt extends NumericColumn {
13
- type: "bigint";
14
- }
15
- interface Real extends NumericColumn {
16
- type: "real";
17
- }
18
- interface Float extends NumericColumn {
19
- type: "float";
20
- }
21
- interface Double extends NumericColumn {
22
- type: "double";
23
- }
24
- interface Numeric extends NumericColumn {
25
- type: "numeric";
26
- precision: number;
27
- scale: number;
28
- }
29
- interface Decimal extends NumericColumn {
30
- type: "decimal";
31
- precision: number;
32
- scale: number;
33
- }
34
- interface Types {
35
- default: Integer;
36
- integer: Integer;
37
- smallint: SmallInt;
38
- bigint: BigInt;
39
- real: Real;
40
- float: Float;
41
- double: Double;
42
- numeric: Numeric;
43
- decimal: Decimal;
44
- }
45
- }
46
- }
47
- /**
48
- * Column class behind `num()` on SQL.
49
- *
50
- * Checks integer ranges and `numeric` precision and scale on write.
51
- */
52
- declare class NumericColumn extends num.Type {
53
- type: num.DataType;
54
- get datatype(): string;
55
- set(value: unknown): number | null | undefined;
56
- }
57
- //#endregion
58
- export { NumericColumn };
59
- //# sourceMappingURL=Num.d.ts.map
@@ -1,42 +0,0 @@
1
- import { num } from "@expressive/orm";
2
-
3
- //#region src/columns/Num.ts
4
- const RANGE = {
5
- smallint: [-32768, 32767],
6
- integer: [-2147483648, 2147483647],
7
- bigint: [-Infinity, Infinity]
8
- };
9
- /**
10
- * Column class behind `num()` on SQL.
11
- *
12
- * Checks integer ranges and `numeric` precision and scale on write.
13
- */
14
- var NumericColumn = class extends num.Type {
15
- constructor(..._args) {
16
- super(..._args);
17
- this.type = "integer";
18
- }
19
- get datatype() {
20
- return this.type === "double" ? "double precision" : super.datatype;
21
- }
22
- set(value) {
23
- const out = super.set(value);
24
- if (typeof value != "number") return out;
25
- const { type, precision, scale } = this;
26
- const range = RANGE[type];
27
- if (range) {
28
- const [min, max] = range;
29
- if (value !== Math.floor(value) || value < min || value > max) throw new Error(`Value ${value} out of range for ${type}.`);
30
- } else if (precision !== void 0) {
31
- const [whole, fraction = ""] = Math.abs(value).toString().split(".");
32
- if (whole.length + fraction.length > precision) throw new Error(`Value ${value} exceeds precision of ${precision}.`);
33
- if (scale !== void 0 && fraction.length > scale) throw new Error(`Value ${value} exceeds scale of ${scale}.`);
34
- }
35
- return out;
36
- }
37
- };
38
- num.Type = NumericColumn;
39
-
40
- //#endregion
41
- export { NumericColumn };
42
- //# sourceMappingURL=Num.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"Num.js","names":[],"sources":["../../src/columns/Num.ts"],"sourcesContent":["import { num } from '@expressive/orm';\n\ndeclare module '@expressive/orm' {\n namespace num {\n interface Integer extends NumericColumn {\n type: \"integer\";\n }\n\n interface SmallInt extends NumericColumn {\n type: \"smallint\";\n }\n\n interface BigInt extends NumericColumn {\n type: \"bigint\";\n }\n\n interface Real extends NumericColumn {\n type: \"real\";\n }\n\n interface Float extends NumericColumn {\n type: \"float\";\n }\n\n interface Double extends NumericColumn {\n type: \"double\";\n }\n\n interface Numeric extends NumericColumn {\n type: \"numeric\";\n precision: number;\n scale: number;\n }\n\n interface Decimal extends NumericColumn {\n type: \"decimal\";\n precision: number;\n scale: number;\n }\n\n interface Types {\n default: Integer;\n integer: Integer;\n smallint: SmallInt;\n bigint: BigInt;\n real: Real;\n float: Float;\n double: Double;\n numeric: Numeric;\n decimal: Decimal;\n }\n }\n}\n\nconst RANGE: Record<string, [number, number]> = {\n smallint: [-32768, 32767],\n integer: [-2147483648, 2147483647],\n bigint: [-Infinity, Infinity]\n};\n\n/**\n * Column class behind `num()` on SQL.\n *\n * Checks integer ranges and `numeric` precision and scale on write.\n */\nexport class NumericColumn extends num.Type {\n type: num.DataType = \"integer\";\n\n get datatype() {\n return this.type === \"double\" ? \"double precision\" : super.datatype;\n }\n\n set(value: unknown) {\n const out = super.set(value);\n\n if (typeof value != \"number\")\n return out;\n\n const { type, precision, scale } = this;\n const range = RANGE[type];\n\n if (range) {\n const [min, max] = range;\n\n if (value !== Math.floor(value) || value < min || value > max)\n throw new Error(`Value ${value} out of range for ${type}.`);\n }\n else if (precision !== undefined) {\n const [whole, fraction = \"\"] = Math.abs(value).toString().split('.');\n\n if (whole.length + fraction.length > precision)\n throw new Error(`Value ${value} exceeds precision of ${precision}.`);\n\n if (scale !== undefined && fraction.length > scale)\n throw new Error(`Value ${value} exceeds scale of ${scale}.`);\n }\n\n return out;\n }\n}\n\nnum.Type = NumericColumn;\n"],"mappings":";;;AAsDA,MAAM,QAA0C;CAC9C,UAAU,CAAC,QAAQ,MAAM;CACzB,SAAS,CAAC,aAAa,WAAW;CAClC,QAAQ,CAAC,WAAW,SAAS;CAC9B;;;;;;AAOD,IAAa,gBAAb,cAAmC,IAAI,KAAK;;;cACrB;;CAErB,IAAI,WAAW;AACb,SAAO,KAAK,SAAS,WAAW,qBAAqB,MAAM;;CAG7D,IAAI,OAAgB;EAClB,MAAM,MAAM,MAAM,IAAI,MAAM;AAE5B,MAAI,OAAO,SAAS,SAClB,QAAO;EAET,MAAM,EAAE,MAAM,WAAW,UAAU;EACnC,MAAM,QAAQ,MAAM;AAEpB,MAAI,OAAO;GACT,MAAM,CAAC,KAAK,OAAO;AAEnB,OAAI,UAAU,KAAK,MAAM,MAAM,IAAI,QAAQ,OAAO,QAAQ,IACxD,OAAM,IAAI,MAAM,SAAS,MAAM,oBAAoB,KAAK,GAAG;aAEtD,cAAc,QAAW;GAChC,MAAM,CAAC,OAAO,WAAW,MAAM,KAAK,IAAI,MAAM,CAAC,UAAU,CAAC,MAAM,IAAI;AAEpE,OAAI,MAAM,SAAS,SAAS,SAAS,UACnC,OAAM,IAAI,MAAM,SAAS,MAAM,wBAAwB,UAAU,GAAG;AAEtE,OAAI,UAAU,UAAa,SAAS,SAAS,MAC3C,OAAM,IAAI,MAAM,SAAS,MAAM,oBAAoB,MAAM,GAAG;;AAGhE,SAAO;;;AAIX,IAAI,OAAO"}
@@ -1,25 +0,0 @@
1
- import { Type, one } from "@expressive/orm";
2
-
3
- //#region src/columns/One.d.ts
4
- declare module '@expressive/orm' {
5
- namespace one {
6
- interface Integer<T extends Type = Type> extends ForeignColumn<T> {
7
- type: "integer";
8
- }
9
- interface BigInt<T extends Type = Type> extends ForeignColumn<T> {
10
- type: "bigint";
11
- }
12
- interface Types {
13
- default: Integer;
14
- integer: Integer;
15
- bigint: BigInt;
16
- }
17
- }
18
- }
19
- /** Column class behind `one()` on SQL - an `integer` or `bigint` foreign key. */
20
- declare class ForeignColumn<T extends Type = Type> extends one.Type<T> {
21
- type: one.DataType;
22
- }
23
- //#endregion
24
- export { ForeignColumn };
25
- //# sourceMappingURL=One.d.ts.map
@@ -1,15 +0,0 @@
1
- import { one } from "@expressive/orm";
2
-
3
- //#region src/columns/One.ts
4
- /** Column class behind `one()` on SQL - an `integer` or `bigint` foreign key. */
5
- var ForeignColumn = class extends one.Type {
6
- constructor(..._args) {
7
- super(..._args);
8
- this.type = "integer";
9
- }
10
- };
11
- one.Type = ForeignColumn;
12
-
13
- //#endregion
14
- export { ForeignColumn };
15
- //# sourceMappingURL=One.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"One.js","names":[],"sources":["../../src/columns/One.ts"],"sourcesContent":["import { one, type Type } from '@expressive/orm';\n\ndeclare module '@expressive/orm' {\n namespace one {\n interface Integer<T extends Type = Type> extends ForeignColumn<T> {\n type: \"integer\";\n }\n\n interface BigInt<T extends Type = Type> extends ForeignColumn<T> {\n type: \"bigint\";\n }\n\n interface Types {\n default: Integer;\n integer: Integer;\n bigint: BigInt;\n }\n }\n}\n\n/** Column class behind `one()` on SQL - an `integer` or `bigint` foreign key. */\nexport class ForeignColumn<T extends Type = Type> extends one.Type<T> {\n type: one.DataType = \"integer\";\n}\n\none.Type = ForeignColumn;\n"],"mappings":";;;;AAqBA,IAAa,gBAAb,cAA0D,IAAI,KAAQ;;;cAC/C;;;AAGvB,IAAI,OAAO"}
@@ -1,36 +0,0 @@
1
- import { str } from "@expressive/orm";
2
-
3
- //#region src/columns/Str.d.ts
4
- declare module '@expressive/orm' {
5
- namespace str {
6
- interface Text extends StringColumn {
7
- type: "text";
8
- }
9
- interface VarChar extends StringColumn {
10
- type: "varchar";
11
- length: number;
12
- }
13
- interface Char extends StringColumn {
14
- type: "char";
15
- length: number;
16
- }
17
- interface UUID extends StringColumn {
18
- type: "uuid";
19
- }
20
- interface Types {
21
- default: Text;
22
- text: Text;
23
- varchar: VarChar;
24
- char: Char;
25
- uuid: UUID;
26
- }
27
- }
28
- }
29
- /** Column class behind `str()` on SQL - `text`, `varchar`, `char` or `uuid`. */
30
- declare class StringColumn extends str.Type {
31
- type: str.DataType;
32
- get datatype(): string;
33
- }
34
- //#endregion
35
- export { StringColumn };
36
- //# sourceMappingURL=Str.d.ts.map
@@ -1,21 +0,0 @@
1
- import { str } from "@expressive/orm";
2
-
3
- //#region src/columns/Str.ts
4
- /** Column class behind `str()` on SQL - `text`, `varchar`, `char` or `uuid`. */
5
- var StringColumn = class extends str.Type {
6
- constructor(..._args) {
7
- super(..._args);
8
- this.type = "text";
9
- }
10
- get datatype() {
11
- let { type, length, collate } = this;
12
- if (type.endsWith("char") && length) type += `(${length})`;
13
- if (collate) type += ` COLLATE "${collate}"`;
14
- return type;
15
- }
16
- };
17
- str.Type = StringColumn;
18
-
19
- //#endregion
20
- export { StringColumn };
21
- //# sourceMappingURL=Str.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"Str.js","names":[],"sources":["../../src/columns/Str.ts"],"sourcesContent":["import { str } from '@expressive/orm';\n\ndeclare module '@expressive/orm' {\n namespace str {\n interface Text extends StringColumn {\n type: \"text\";\n }\n\n interface VarChar extends StringColumn {\n type: \"varchar\";\n length: number;\n }\n\n interface Char extends StringColumn {\n type: \"char\";\n length: number;\n }\n\n interface UUID extends StringColumn {\n type: \"uuid\";\n }\n\n interface Types {\n default: Text;\n text: Text;\n varchar: VarChar;\n char: Char;\n uuid: UUID;\n }\n }\n}\n\n/** Column class behind `str()` on SQL - `text`, `varchar`, `char` or `uuid`. */\nexport class StringColumn extends str.Type {\n type: str.DataType = \"text\";\n\n get datatype() {\n let { type, length, collate } = this;\n\n if (type.endsWith(\"char\") && length)\n type += `(${length})`;\n\n if (collate)\n type += ` COLLATE \"${collate}\"`;\n\n return type;\n }\n}\n\nstr.Type = StringColumn;\n"],"mappings":";;;;AAiCA,IAAa,eAAb,cAAkC,IAAI,KAAK;;;cACpB;;CAErB,IAAI,WAAW;EACb,IAAI,EAAE,MAAM,QAAQ,YAAY;AAEhC,MAAI,KAAK,SAAS,OAAO,IAAI,OAC3B,SAAQ,IAAI,OAAO;AAErB,MAAI,QACF,SAAQ,aAAa,QAAQ;AAE/B,SAAO;;;AAIX,IAAI,OAAO"}
@@ -1,52 +0,0 @@
1
- import { date } from "@expressive/orm";
2
-
3
- //#region src/columns/Time.d.ts
4
- declare module '@expressive/orm' {
5
- namespace date {
6
- interface Timestamp extends TimeColumn {
7
- type: "timestamp";
8
- }
9
- interface Day extends TimeColumn {
10
- type: "date";
11
- }
12
- interface Time extends TimeColumn {
13
- type: "time";
14
- }
15
- interface Integer extends TimeColumn {
16
- type: "integer";
17
- }
18
- interface Text extends TimeColumn {
19
- type: "text";
20
- }
21
- interface Ms extends TimeColumn {
22
- type: "ms";
23
- }
24
- interface Seconds extends TimeColumn {
25
- type: "seconds";
26
- }
27
- interface Types {
28
- default: Timestamp;
29
- timestamp: Timestamp;
30
- date: Day;
31
- time: Time;
32
- integer: Integer;
33
- text: Text;
34
- ms: Ms;
35
- seconds: Seconds;
36
- }
37
- }
38
- }
39
- /**
40
- * Column class behind `date()` on SQL.
41
- *
42
- * Stores a Date as `timestamp`, `date`, `time`, `ms`, `seconds`, `integer` or `text`.
43
- */
44
- declare class TimeColumn extends date.Type {
45
- type: date.DataType;
46
- get datatype(): string;
47
- get(value: unknown): Date | undefined;
48
- set(value: unknown): string | number | undefined;
49
- }
50
- //#endregion
51
- export { TimeColumn };
52
- //# sourceMappingURL=Time.d.ts.map
@@ -1,45 +0,0 @@
1
- import { date } from "@expressive/orm";
2
-
3
- //#region src/columns/Time.ts
4
- /**
5
- * Column class behind `date()` on SQL.
6
- *
7
- * Stores a Date as `timestamp`, `date`, `time`, `ms`, `seconds`, `integer` or `text`.
8
- */
9
- var TimeColumn = class extends date.Type {
10
- constructor(..._args) {
11
- super(..._args);
12
- this.type = "timestamp";
13
- }
14
- get datatype() {
15
- const { type } = this;
16
- return type === "ms" ? "bigint" : type === "seconds" ? "integer" : super.datatype;
17
- }
18
- get(value) {
19
- if (value == null) return void 0;
20
- if (this.type === "ms") return new Date(Number(value));
21
- if (typeof value === "number") return /* @__PURE__ */ new Date(value * 1e3);
22
- if (typeof value === "string" && this.type === "date") {
23
- const [year, month, day] = value.split("-").map(Number);
24
- return new Date(year, month - 1, day);
25
- }
26
- if (typeof value === "string" && this.type === "time") return /* @__PURE__ */ new Date(`1970-01-01T${value}Z`);
27
- if (typeof value === "string" && /^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d(\.\d+)?$/.test(value)) return /* @__PURE__ */ new Date(value.replace(" ", "T") + "Z");
28
- return new Date(value);
29
- }
30
- set(value) {
31
- const iso = super.set(value);
32
- if (iso === void 0) return iso;
33
- const date = new Date(iso);
34
- if (this.type === "ms") return date.getTime();
35
- if (this.type === "integer" || this.type === "seconds") return Math.floor(date.getTime() / 1e3);
36
- if (this.type === "date") return date.toISOString().slice(0, 10);
37
- if (this.type === "time") return date.toISOString().slice(11, 19);
38
- return iso;
39
- }
40
- };
41
- date.Type = TimeColumn;
42
-
43
- //#endregion
44
- export { TimeColumn };
45
- //# sourceMappingURL=Time.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"Time.js","names":[],"sources":["../../src/columns/Time.ts"],"sourcesContent":["import { date } from '@expressive/orm';\n\ndeclare module '@expressive/orm' {\n namespace date {\n interface Timestamp extends TimeColumn {\n type: \"timestamp\";\n }\n\n interface Day extends TimeColumn {\n type: \"date\";\n }\n\n interface Time extends TimeColumn {\n type: \"time\";\n }\n\n interface Integer extends TimeColumn {\n type: \"integer\";\n }\n\n interface Text extends TimeColumn {\n type: \"text\";\n }\n\n interface Ms extends TimeColumn {\n type: \"ms\";\n }\n\n interface Seconds extends TimeColumn {\n type: \"seconds\";\n }\n\n interface Types {\n default: Timestamp;\n timestamp: Timestamp;\n date: Day;\n time: Time;\n integer: Integer;\n text: Text;\n ms: Ms;\n seconds: Seconds;\n }\n }\n}\n\n/**\n * Column class behind `date()` on SQL.\n *\n * Stores a Date as `timestamp`, `date`, `time`, `ms`, `seconds`, `integer` or `text`.\n */\nexport class TimeColumn extends date.Type {\n type: date.DataType = \"timestamp\";\n\n get datatype() {\n const { type } = this;\n\n return type === \"ms\" ? \"bigint\" : type === \"seconds\" ? \"integer\" : super.datatype;\n }\n\n get(value: unknown) {\n if (value == null)\n return undefined;\n\n if (this.type === \"ms\")\n return new Date(Number(value));\n\n if (typeof value === 'number')\n return new Date(value * 1000);\n\n if (typeof value === 'string' && this.type === \"date\") {\n const [year, month, day] = value.split('-').map(Number);\n return new Date(year, month - 1, day);\n }\n\n if (typeof value === 'string' && this.type === \"time\")\n return new Date(`1970-01-01T${value}Z`);\n\n if (typeof value === 'string' && /^\\d{4}-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d(\\.\\d+)?$/.test(value))\n return new Date(value.replace(\" \", \"T\") + \"Z\");\n\n return new Date(value as string | Date);\n }\n\n set(value: unknown) {\n const iso = super.set(value);\n\n if (iso === undefined)\n return iso;\n\n const date = new Date(iso);\n\n if (this.type === \"ms\")\n return date.getTime();\n\n if (this.type === \"integer\" || this.type === \"seconds\")\n return Math.floor(date.getTime() / 1000);\n\n if (this.type === \"date\")\n return date.toISOString().slice(0, 10);\n\n if (this.type === \"time\")\n return date.toISOString().slice(11, 19);\n\n return iso;\n }\n}\n\ndate.Type = TimeColumn;\n"],"mappings":";;;;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