@primate/sqlite 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,19 @@
1
+ Copyright (c) Terrablue <terrablue@proton.me> and contributors.
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ THE SOFTWARE.
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@primate/sqlite",
3
+ "version": "0.1.0",
4
+ "description": "Primate SQLite database",
5
+ "homepage": "https://primatejs.com/modules/sqlite",
6
+ "bugs": "https://github.com/primatejs/primate/issues",
7
+ "license": "MIT",
8
+ "files": [
9
+ "src/**/*.js",
10
+ "!src/**/*.spec.js"
11
+ ],
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/primatejs/primate",
15
+ "directory": "packages/sqlite"
16
+ },
17
+ "dependencies": {
18
+ "@rcompat/invariant": "^0.5.0",
19
+ "@rcompat/object": "^0.5.0",
20
+ "@primate/core": "^0.1.0",
21
+ "@primate/store": "^0.25.0"
22
+ },
23
+ "devDependencies": {
24
+ "better-sqlite3": "^11.1.2"
25
+ },
26
+ "peerDependencies": {
27
+ "better-sqlite3": "11"
28
+ },
29
+ "type": "module",
30
+ "imports": {
31
+ "#*": {
32
+ "@primate/lt": "./src/private/*.js",
33
+ "default": "./src/private/*.js"
34
+ }
35
+ },
36
+ "exports": {
37
+ ".": "./src/default.js"
38
+ }
39
+ }
package/src/default.js ADDED
@@ -0,0 +1,8 @@
1
+ import defaults from "#defaults";
2
+ import serve from "#serve";
3
+
4
+ export default ({
5
+ database = defaults.database,
6
+ } = {}) => ({
7
+ serve: serve({ database }),
8
+ });
@@ -0,0 +1,115 @@
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 platform from "@rcompat/platform";
7
+
8
+ const is_bun = platform === "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
+ }
@@ -0,0 +1,9 @@
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
+ });
@@ -0,0 +1,3 @@
1
+ export default {
2
+ database: ":memory:",
3
+ };
@@ -0,0 +1,88 @@
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
+ };
@@ -0,0 +1,21 @@
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];