@primate/sqlite 0.1.3 → 0.3.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.
@@ -0,0 +1,15 @@
1
+ import type PrimitiveParam from "@rcompat/sqlite/PrimitiveParam";
2
+ import type TypedArray from "@rcompat/type/TypedArray";
3
+ type Validate<T extends {
4
+ [K in keyof T]: PrimitiveParam;
5
+ }> = T;
6
+ type ColumnTypes = Validate<{
7
+ BLOB: TypedArray;
8
+ INTEGER: bigint | number;
9
+ "INTEGER PRIMARY KEY": number;
10
+ NULL: null;
11
+ REAL: number;
12
+ TEXT: string;
13
+ }>;
14
+ export type { ColumnTypes as default };
15
+ //# sourceMappingURL=ColumnTypes.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ColumnTypes.js.map
@@ -0,0 +1,42 @@
1
+ import Database from "@primate/core/Database";
2
+ import type As from "@primate/core/database/As";
3
+ import type DataDict from "@primate/core/database/DataDict";
4
+ import type TypeMap from "@primate/core/database/TypeMap";
5
+ import type Dict from "@rcompat/type/Dict";
6
+ import type StoreSchema from "pema/StoreSchema";
7
+ declare const schema: import("pema").ObjectType<{
8
+ database: import("pema").DefaultType<import("pema/string").StringType, ":memory:">;
9
+ }>;
10
+ export default class SQLiteDatabase extends Database {
11
+ #private;
12
+ static config: typeof schema.input;
13
+ constructor(config?: typeof schema.input);
14
+ close(): void;
15
+ get typemap(): TypeMap<Dict>;
16
+ get schema(): {
17
+ create: (name: string, store: StoreSchema) => void;
18
+ delete: (name: string) => void;
19
+ };
20
+ create<O extends Dict>(as: As, args: {
21
+ record: DataDict;
22
+ }): Promise<O>;
23
+ read(as: As, args: {
24
+ count: true;
25
+ criteria: DataDict;
26
+ }): Promise<number>;
27
+ read(as: As, args: {
28
+ criteria: DataDict;
29
+ fields?: string[];
30
+ limit?: number;
31
+ sort?: Dict<"asc" | "desc">;
32
+ }): Promise<Dict[]>;
33
+ update(as: As, args: {
34
+ changes: DataDict;
35
+ criteria: DataDict;
36
+ }): Promise<number>;
37
+ delete(as: As, args: {
38
+ criteria: DataDict;
39
+ }): Promise<number>;
40
+ }
41
+ export {};
42
+ //# sourceMappingURL=Database.d.ts.map
@@ -0,0 +1,104 @@
1
+ import typemap from "#typemap";
2
+ import Database from "@primate/core/Database";
3
+ import assert from "@rcompat/assert";
4
+ import Client from "@rcompat/sqlite";
5
+ import pema from "pema";
6
+ import string from "pema/string";
7
+ const schema = pema({
8
+ database: string.default(":memory:"),
9
+ });
10
+ const options = { safeIntegers: true };
11
+ export default class SQLiteDatabase extends Database {
12
+ #factory;
13
+ #client;
14
+ static config;
15
+ constructor(config) {
16
+ super("$");
17
+ const parsed = schema.parse(config);
18
+ this.#factory = () => new Client(parsed.database, options);
19
+ }
20
+ #get() {
21
+ if (this.#client === undefined) {
22
+ this.#client = this.#factory();
23
+ }
24
+ return this.#client;
25
+ }
26
+ close() {
27
+ this.#get().close();
28
+ }
29
+ get typemap() {
30
+ return typemap;
31
+ }
32
+ #new(name, store) {
33
+ const body = Object.entries(store)
34
+ .map(([key, value]) => `${this.ident(key)} ${this.column(value.datatype)}`)
35
+ .join(",");
36
+ const query = `CREATE TABLE IF NOT EXISTS ${this.ident(name)} (${body})`;
37
+ this.#get().prepare(query).run();
38
+ }
39
+ #drop(name) {
40
+ const query = `DROP TABLE IF EXISTS ${this.ident(name)}`;
41
+ this.#get().prepare(query).run();
42
+ }
43
+ get schema() {
44
+ return {
45
+ create: this.#new.bind(this),
46
+ delete: this.#drop.bind(this),
47
+ };
48
+ }
49
+ async create(as, args) {
50
+ const keys = Object.keys(args.record);
51
+ const columns = keys.map(k => this.ident(k));
52
+ const values = keys.map(key => `$${key}`).join(",");
53
+ const payload = columns.length > 0
54
+ ? `(${columns.join(",")}) VALUES (${values})`
55
+ : "DEFAULT VALUES";
56
+ const query = `INSERT INTO ${this.table(as)} ${payload} RETURNING id;`;
57
+ const binds = await this.bind(as.types, args.record);
58
+ const statement = this.#get().prepare(query);
59
+ const changes = statement.run(binds);
60
+ const id = BigInt(changes.lastInsertRowid);
61
+ return this.unbind(as.types, { ...args.record, id });
62
+ }
63
+ async read(as, args) {
64
+ const where = this.toWhere(as.types, args.criteria);
65
+ const binds = await this.bindCriteria(as.types, args.criteria);
66
+ if (args.count === true) {
67
+ const query = `SELECT COUNT(*) AS n FROM ${this.table(as)} ${where};`;
68
+ const [{ n }] = this.#get().prepare(query).all(binds);
69
+ return Number(n);
70
+ }
71
+ const select = this.toSelect(as.types, args.fields);
72
+ const sort = this.toSort(as.types, args.sort);
73
+ const limit = this.toLimit(args.limit);
74
+ const query = `SELECT
75
+ ${select} FROM ${this.table(as)} ${where}${sort}${limit};`;
76
+ const records = this.#get().prepare(query).all(binds);
77
+ return records.map(record => this.unbind(as.types, record));
78
+ }
79
+ async update(as, args) {
80
+ assert(Object.keys(args.criteria).length > 0, "update: no criteria");
81
+ const where = this.toWhere(as.types, args.criteria);
82
+ const criteria = await this.bindCriteria(as.types, args.criteria);
83
+ const { set, binds: set_binds } = await this.toSet(as.types, args.changes);
84
+ const binds = { ...criteria, ...set_binds };
85
+ const query = `
86
+ WITH to_update AS (
87
+ SELECT id FROM ${this.table(as)}
88
+ ${where}
89
+ )
90
+ UPDATE ${this.table(as)}
91
+ ${set}
92
+ WHERE id IN (SELECT id FROM to_update)
93
+ `;
94
+ return Number(this.#get().prepare(`${query};`).run(binds).changes);
95
+ }
96
+ async delete(as, args) {
97
+ assert(Object.keys(args.criteria).length > 0, "delete: no criteria");
98
+ const where = this.toWhere(as.types, args.criteria);
99
+ const binds = await this.bindCriteria(as.types, args.criteria);
100
+ const query = `DELETE FROM ${this.table(as)} ${where}`;
101
+ return Number(this.#get().prepare(query).run(binds).changes);
102
+ }
103
+ }
104
+ //# sourceMappingURL=Database.js.map
@@ -0,0 +1,5 @@
1
+ import type ColumnTypes from "#ColumnTypes";
2
+ import type TypeMap from "@primate/core/database/TypeMap";
3
+ declare const typemap: TypeMap<ColumnTypes>;
4
+ export default typemap;
5
+ //# sourceMappingURL=typemap.d.ts.map
@@ -0,0 +1,114 @@
1
+ import numeric from "@rcompat/is/numeric";
2
+ function identity(column) {
3
+ return {
4
+ bind: value => value,
5
+ column,
6
+ unbind: value => value,
7
+ };
8
+ }
9
+ function number(column) {
10
+ return {
11
+ bind: (value) => value,
12
+ column,
13
+ unbind: (value) => Number(value),
14
+ };
15
+ }
16
+ const typemap = {
17
+ blob: {
18
+ async bind(value) {
19
+ const arrayBuffer = await value.arrayBuffer();
20
+ return new Uint8Array(arrayBuffer);
21
+ },
22
+ column: "BLOB",
23
+ unbind(value) {
24
+ return new Blob([value], { type: "application/octet-stream" });
25
+ },
26
+ },
27
+ boolean: {
28
+ bind(value) {
29
+ return value === true ? 1 : 0;
30
+ },
31
+ column: "INTEGER",
32
+ unbind(value) {
33
+ return Number(value) === 1;
34
+ },
35
+ },
36
+ datetime: {
37
+ bind(value) {
38
+ return value.toJSON();
39
+ },
40
+ column: "TEXT",
41
+ unbind(value) {
42
+ return new Date(value);
43
+ },
44
+ },
45
+ f32: identity("REAL"),
46
+ f64: identity("REAL"),
47
+ i128: {
48
+ bind(value) {
49
+ return String(value);
50
+ },
51
+ column: "TEXT",
52
+ unbind(value) {
53
+ return BigInt(value);
54
+ },
55
+ },
56
+ i16: number("INTEGER"),
57
+ i32: number("INTEGER"),
58
+ i64: {
59
+ bind(value) {
60
+ return value;
61
+ },
62
+ column: "INTEGER",
63
+ unbind(value) {
64
+ return BigInt(value);
65
+ },
66
+ },
67
+ i8: number("INTEGER"),
68
+ primary: {
69
+ bind(value) {
70
+ if (numeric(value)) {
71
+ return Number(value);
72
+ }
73
+ throw new Error(`\`${value}\` is not a valid primary key value`);
74
+ },
75
+ column: "INTEGER PRIMARY KEY",
76
+ unbind(value) {
77
+ return String(value);
78
+ },
79
+ },
80
+ string: identity("TEXT"),
81
+ time: identity("TEXT"),
82
+ u128: {
83
+ bind(value) {
84
+ return String(value);
85
+ },
86
+ column: "TEXT",
87
+ unbind(value) {
88
+ return BigInt(value);
89
+ },
90
+ },
91
+ u16: number("INTEGER"),
92
+ u32: number("INTEGER"),
93
+ u64: {
94
+ bind(value) {
95
+ return String(value);
96
+ },
97
+ column: "TEXT",
98
+ unbind(value) {
99
+ return BigInt(value);
100
+ },
101
+ },
102
+ u8: number("INTEGER"),
103
+ url: {
104
+ bind(value) {
105
+ return value.toString();
106
+ },
107
+ column: "TEXT",
108
+ unbind(value) {
109
+ return new URL(value);
110
+ },
111
+ },
112
+ };
113
+ export default typemap;
114
+ //# sourceMappingURL=typemap.js.map
@@ -0,0 +1,4 @@
1
+ import Database from "#Database";
2
+ declare const _default: (config?: typeof Database.config) => Database;
3
+ export default _default;
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,3 @@
1
+ import Database from "#Database";
2
+ export default (config) => new Database(config);
3
+ //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,35 +1,50 @@
1
1
  {
2
2
  "name": "@primate/sqlite",
3
- "version": "0.1.3",
3
+ "version": "0.3.0",
4
4
  "description": "Primate SQLite database",
5
- "homepage": "https://primatejs.com/modules/sqlite",
6
- "bugs": "https://github.com/primatejs/primate/issues",
5
+ "homepage": "https://primate.run/docs/database/sqlite",
6
+ "bugs": "https://github.com/primate-run/primate/issues",
7
7
  "license": "MIT",
8
8
  "files": [
9
- "src/**/*.js",
10
- "!src/**/*.spec.js"
9
+ "/lib/**/*.js",
10
+ "/lib/**/*.d.ts",
11
+ "!/**/*.spec.*"
11
12
  ],
12
13
  "repository": {
13
14
  "type": "git",
14
- "url": "https://github.com/primatejs/primate",
15
+ "url": "https://github.com/primate-run/primate",
15
16
  "directory": "packages/sqlite"
16
17
  },
17
18
  "dependencies": {
18
- "@rcompat/invariant": "^0.5.0",
19
- "@rcompat/object": "^0.5.0",
20
- "@rcompat/runtime": "^0.1.0",
21
- "better-sqlite3": "^11.2.1",
22
- "@primate/core": "^0.1.9",
23
- "@primate/store": "^0.25.4"
19
+ "@rcompat/assert": "^0.3.1",
20
+ "@rcompat/async": "^0.9.0",
21
+ "@rcompat/is": "^0.1.4",
22
+ "@rcompat/record": "^0.9.1",
23
+ "@rcompat/sqlite": "^0.4.0",
24
+ "@primate/core": "^0.3.0"
25
+ },
26
+ "devDependencies": {
27
+ "pema": "^0.3.0"
24
28
  },
25
29
  "type": "module",
26
30
  "imports": {
27
31
  "#*": {
28
- "livetypes": "./src/private/*.js",
29
- "default": "./src/private/*.js"
32
+ "apekit": "./src/private/*.ts",
33
+ "default": "./lib/private/*.js"
30
34
  }
31
35
  },
32
36
  "exports": {
33
- ".": "./src/default.js"
37
+ ".": {
38
+ "apekit": "./src/public/index.ts",
39
+ "default": "./lib/public/index.js"
40
+ }
41
+ },
42
+ "scripts": {
43
+ "build": "npm run clean && tsc",
44
+ "clean": "rm -rf ./lib",
45
+ "lint": "eslint .",
46
+ "test": "npm run build && npx proby",
47
+ "test:bun": "npm run build && bun x --bun proby",
48
+ "test:deno": "npm run build && deno run -A npm:proby"
34
49
  }
35
50
  }
package/src/default.js DELETED
@@ -1,8 +0,0 @@
1
- import defaults from "#defaults";
2
- import serve from "#serve";
3
-
4
- export default ({
5
- database = defaults.database,
6
- } = {}) => ({
7
- serve: serve({ database }),
8
- });
@@ -1,115 +0,0 @@
1
- import typemap from "#typemap";
2
- import make_sort from "@primate/store/sql/make-sort";
3
- import filter from "@rcompat/object/filter";
4
- import keymap from "@rcompat/object/keymap";
5
- import valmap from "@rcompat/object/valmap";
6
- import runtime from "@rcompat/runtime";
7
-
8
- const is_bun = runtime === "bun";
9
-
10
- const filter_null = results =>
11
- results.map(result => filter(result, ([, value]) => value !== null));
12
-
13
- const predicate = criteria => {
14
- const keys = Object.keys(criteria);
15
- if (keys.length === 0) {
16
- return { where: "", bindings: {} };
17
- }
18
-
19
- const where = `where ${keys.map(key => `"${key}"=$${key}`).join(" and ")}`;
20
-
21
- return { where, bindings: criteria };
22
- };
23
-
24
- const change = delta => {
25
- const keys = Object.keys(delta);
26
- const set = keys.map(field => `"${field}"=$s_${field}`).join(",");
27
- return {
28
- set: `set ${set}`,
29
- bindings: keymap(delta, key => `s_${key}`),
30
- };
31
- };
32
-
33
- export default class Connection {
34
- schema = {
35
- create: async (name, description) => {
36
- const body =
37
- Object.entries(valmap(description, value => typemap(value.base)))
38
- .map(([column, dataType]) => `"${column}" ${dataType}`).join(",");
39
- const query = `create table if not exists ${name} (${body})`;
40
- this.connection.prepare(query).run();
41
- },
42
- delete: async name => {
43
- const query = `drop table if exists ${name}`;
44
- return this.connection.prepare(query).run();
45
- },
46
- };
47
-
48
- constructor(connection) {
49
- this.connection = connection;
50
- }
51
-
52
- find(collection, criteria = {}, projection = [], options = {}) {
53
- const rest = make_sort(options);
54
- const { where, bindings } = predicate(criteria);
55
- const select = projection.length === 0 ? "*" : projection.join(", ");
56
- const query = `select ${select} from ${collection} ${where} ${rest};`;
57
- const statement = this.connection.prepare(query);
58
- if (!is_bun) {
59
- statement.safeIntegers(true);
60
- }
61
- return filter_null(statement.all(bindings));
62
- }
63
-
64
- count(collection, criteria = {}) {
65
- const { where, bindings } = predicate(criteria);
66
- const query = `select count(*) from ${collection} ${where}`;
67
- const prepared = this.connection.prepare(query);
68
- if (is_bun) {
69
- const [count] = Object.values(prepared.get(bindings));
70
- return count;
71
- }
72
-
73
- return prepared.pluck(true).get(bindings);
74
- }
75
-
76
- get(collection, primary, value) {
77
- const query = `select * from ${collection} where ${primary}=$primary`;
78
- const statement = this.connection.prepare(query);
79
- if (!is_bun) {
80
- statement.safeIntegers(true);
81
- }
82
- const result = statement.get({ primary: value });
83
- return result === undefined
84
- ? result
85
- : filter(result, ([, $value]) => $value !== null);
86
- }
87
-
88
- insert(collection, primary, document) {
89
- const keys = Object.keys(document);
90
- const columns = keys.map(key => `"${key}"`);
91
- const values = keys.map(key => `$${key}`).join(",");
92
- const $predicate = columns.length > 0
93
- ? `(${columns.join(",")}) values (${values})`
94
- : "default values";
95
- const query = `insert into ${collection} ${$predicate} returning id`;
96
- const prepared = this.connection.prepare(query);
97
- const $document = is_bun ? keymap(document, key => `$${key}`) : document;
98
- const { id } = prepared.get($document);
99
- return { ...document, id };
100
- }
101
-
102
- update(collection, criteria = {}, delta = {}) {
103
- const { where, bindings } = predicate(criteria);
104
- const { set, bindings: bindings2 } = change(delta);
105
- const query = `update ${collection} ${set} ${where}`;
106
- return this.connection.prepare(query).run({ ...bindings, ...bindings2 })
107
- .changes;
108
- }
109
-
110
- delete(collection, criteria = {}) {
111
- const { where, bindings } = predicate(criteria);
112
- const query = `delete from ${collection} ${where}`;
113
- return this.connection.prepare(query).run({ ...bindings }).changes;
114
- }
115
- }
@@ -1,9 +0,0 @@
1
- import Pool from "@primate/store/core/pool";
2
- import Database from "@rcompat/sql/sqlite";
3
-
4
- export default ({ database }) => new Pool({
5
- manager: {
6
- new: () => new Database(database, { create: true }),
7
- kill: connection => connection.close(),
8
- },
9
- });
@@ -1,3 +0,0 @@
1
- export default {
2
- database: ":memory:",
3
- };
@@ -1,88 +0,0 @@
1
- import Facade from "#Facade";
2
- import connect from "#connect";
3
- import ident from "@primate/store/core/ident";
4
- import wrap from "@primate/store/core/wrap";
5
- import numeric from "@rcompat/invariant/numeric";
6
-
7
- export default options => async () => {
8
- const client = await connect(options);
9
-
10
- const types = {
11
- primary: {
12
- validate(value) {
13
- if (typeof value === "number" || numeric(value)) {
14
- return Number(value);
15
- }
16
- throw new Error(`\`${value}\` is not a valid primary key value`);
17
- },
18
- ...ident,
19
- out(value) {
20
- // bigint
21
- return Number(value);
22
- },
23
- },
24
- object: {
25
- in(value) {
26
- return JSON.stringify(value);
27
- },
28
- out(value) {
29
- return JSON.parse(value);
30
- },
31
- },
32
- number: {
33
- in(value) {
34
- return value;
35
- },
36
- out(value) {
37
- return Number(value);
38
- },
39
- },
40
- // in: driver accepts both number and bigint
41
- // out: find/get currently set statement.safeIntegers(true);
42
- bigint: ident,
43
- boolean: {
44
- in(value) {
45
- return value === true ? 1 : 0;
46
- },
47
- out(value) {
48
- // out: find/get currently set statement.safeIntegers(true);
49
- return Number(value) === 1;
50
- },
51
- },
52
- date: {
53
- in(value) {
54
- return value.toJSON();
55
- },
56
- out(value) {
57
- return new Date(value);
58
- },
59
- },
60
- string: ident,
61
- };
62
-
63
- return {
64
- name: "@primate/sqlite",
65
- types,
66
- async transact(stores) {
67
- return async (others, next) => {
68
- const connection = await client.acquire();
69
- const facade = new Facade(connection);
70
- try {
71
- connection.prepare("begin transaction").run();
72
- const response = await next([...others, ...stores.map(([_, store]) =>
73
- [_, wrap(store, facade, types)]),
74
- ]);
75
- connection.prepare("commit transaction").run();
76
- return response;
77
- } catch (error) {
78
- connection.prepare("rollback transaction").run();
79
- // bubble up
80
- throw error;
81
- } finally {
82
- // noop, no end transaction
83
- client.release(connection);
84
- }
85
- };
86
- },
87
- };
88
- };
@@ -1,21 +0,0 @@
1
- const types = {
2
- /* array */
3
- blob: "blob",
4
- boolean: "integer",
5
- datetime: "text",
6
- embedded: "text",
7
- f64: "real",
8
- i8: "integer",
9
- i16: "integer",
10
- i32: "integer",
11
- i64: "integer",
12
- json: "text",
13
- primary: "integer primary key",
14
- string: "text",
15
- time: "text",
16
- u8: "integer",
17
- u16: "integer",
18
- u32: "integer",
19
- };
20
-
21
- export default value => types[value];