@primate/mysql 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/mysql",
3
+ "version": "0.1.0",
4
+ "description": "Primate MySQL database",
5
+ "homepage": "https://primatejs.com/modules/mysql",
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/mysql"
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
+ "mysql2": "^3.11.0"
25
+ },
26
+ "peerDependencies": {
27
+ "mysql2": "3"
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,12 @@
1
+ import defaults from "#defaults";
2
+ import serve from "#serve";
3
+
4
+ export default ({
5
+ host = defaults.host,
6
+ port = defaults.port,
7
+ database,
8
+ username,
9
+ password,
10
+ } = {}) => ({
11
+ serve: serve({ host, port, database, username, password }),
12
+ });
@@ -0,0 +1,105 @@
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
+
7
+ const filter_null = object => filter(object, ([, value]) => value !== null);
8
+ const filter_nulls = objects => objects.map(object => filter_null(object));
9
+
10
+ const predicate = criteria => {
11
+ const keys = Object.keys(criteria);
12
+ if (keys.length === 0) {
13
+ return { where: "", bindings: {} };
14
+ }
15
+
16
+ const where = `where ${keys.map(key => `\`${key}\`=:${key}`).join(" and ")}`;
17
+
18
+ return { where, bindings: criteria };
19
+ };
20
+
21
+ const change = delta => {
22
+ const keys = Object.keys(delta);
23
+ const set = keys.map(field => `\`${field}\`=:s_${field}`).join(",");
24
+ return {
25
+ set: `set ${set}`,
26
+ bindings: keymap(delta, key => `s_${key}`),
27
+ };
28
+ };
29
+
30
+ export default class Connection {
31
+ schema = {
32
+ create: async (name, description) => {
33
+ const { connection } = this;
34
+ const body =
35
+ Object.entries(valmap(description, value => typemap(value.base)))
36
+ .map(([column, dataType]) => `\`${column}\` ${dataType}`).join(",");
37
+ const query = `create table if not exists ${name} (${body})`;
38
+ await connection.query(query);
39
+ },
40
+ delete: async name => {
41
+ const query = `drop table if exists ${name}`;
42
+ await this.connection.query(query);
43
+ },
44
+ };
45
+
46
+ constructor(connection) {
47
+ this.connection = connection;
48
+ }
49
+
50
+ async find(collection, criteria = {}, projection = [], options = {}) {
51
+ const { where, bindings } = predicate(criteria);
52
+ const select = projection.length === 0 ? "*" : projection.join(", ");
53
+ const rest = make_sort(options);
54
+ const query = `select ${select} from ${collection} ${where} ${rest}`;
55
+ const [result] = await this.connection.query(query, bindings);
56
+
57
+ return filter_nulls(result);
58
+ }
59
+
60
+ async count(collection, criteria = {}) {
61
+ const { where, bindings } = predicate(criteria);
62
+ const query = `select count(*) as count from ${collection} ${where}`;
63
+ const [[{ count }]] = await this.connection.query(query, bindings);
64
+ return count;
65
+ }
66
+
67
+ async get(collection, primary, value) {
68
+ const query = `select * from ${collection} where ${primary}=:primary`;
69
+ const [[result]] = await this.connection.query(query, { primary: value });
70
+
71
+ return result === undefined
72
+ ? result
73
+ : filter(result, ([, $value]) => $value !== null);
74
+ }
75
+
76
+ async insert(collection, primary, document) {
77
+ const keys = Object.keys(document);
78
+ const columns = keys.map(key => `\`${key}\``);
79
+ const values = keys.map(key => `:${key}`).join(",");
80
+ const $predicate = `(${columns.join(",")}) values (${values})`;
81
+ const query = `insert into ${collection} ${$predicate}`;
82
+ const [{ insertId: id }] = await this.connection.query(query, document);
83
+
84
+ return { ...document, id };
85
+ }
86
+
87
+ async update(collection, criteria = {}, delta = {}) {
88
+ const { where, bindings } = predicate(criteria);
89
+ const { set, bindings: bindings2 } = change(delta);
90
+ const query = `update ${collection} ${set} ${where}`;
91
+ const params = { ... bindings, ...bindings2 };
92
+ const [{ affectedRows }] = await this.connection.query(query, params);
93
+
94
+ return affectedRows;
95
+ }
96
+
97
+ async delete(collection, criteria = {}) {
98
+ const { where, bindings } = predicate(criteria);
99
+ const query = `delete from ${collection} ${where}`;
100
+
101
+ const [{ affectedRows }] = await this.connection.query(query, bindings);
102
+
103
+ return affectedRows;
104
+ }
105
+ }
@@ -0,0 +1,16 @@
1
+ import mysql from "mysql2/promise";
2
+
3
+ export default ({ host, port, database, username, password }) =>
4
+ mysql.createPool({
5
+ host,
6
+ port,
7
+ database,
8
+ user: username,
9
+ password,
10
+ waitForConnections: true,
11
+ connectionLimit: 10,
12
+ queueLimit: 0,
13
+ enableKeepAlive: true,
14
+ keepAliveInitialDelay: 0,
15
+ namedPlaceholders: true,
16
+ });
@@ -0,0 +1,4 @@
1
+ export default {
2
+ host: "localhost",
3
+ port: 3306,
4
+ };
@@ -0,0 +1,81 @@
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
+ },
20
+ object: {
21
+ in(value) {
22
+ return JSON.stringify(value);
23
+ },
24
+ out(value) {
25
+ return JSON.parse(value);
26
+ },
27
+ },
28
+ number: ident,
29
+ bigint: {
30
+ in(value) {
31
+ return value.toString();
32
+ },
33
+ out(value) {
34
+ return BigInt(value);
35
+ },
36
+ },
37
+ boolean: {
38
+ in(value) {
39
+ return value === true ? 1 : 0;
40
+ },
41
+ out(value) {
42
+ return Number(value) === 1;
43
+ },
44
+ },
45
+ date: {
46
+ in(value) {
47
+ return value;
48
+ },
49
+ out(value) {
50
+ return new Date(value);
51
+ },
52
+ },
53
+ string: ident,
54
+ };
55
+
56
+ return {
57
+ name: "@primate/mysql",
58
+ types,
59
+ async transact(stores) {
60
+ return async (others, next) => {
61
+ const connection = await client.getConnection();
62
+ const facade = new Facade(connection);
63
+ try {
64
+ await connection.query("start transaction");
65
+ const response = await next([...others, ...stores.map(([_, store]) =>
66
+ [_, wrap(store, facade, types)]),
67
+ ]);
68
+ await connection.query("commit");
69
+ return response;
70
+ } catch (error) {
71
+ await connection.query("rollback");
72
+ // bubble up
73
+ throw error;
74
+ } finally {
75
+ // noop, no end transaction
76
+ client.releaseConnection(connection);
77
+ }
78
+ };
79
+ },
80
+ };
81
+ };
@@ -0,0 +1,24 @@
1
+ const types = {
2
+ /* array */
3
+ blob: "blob",
4
+ boolean: "bool",
5
+ datetime: "datetime",
6
+ embedded: "text",
7
+ f64: "double",
8
+ i8: "tinyint",
9
+ i16: "smallint",
10
+ i32: "int",
11
+ i64: "bigint",
12
+ i128: "decimal",
13
+ json: "json",
14
+ primary: "int not null auto_increment primary key",
15
+ string: "text",
16
+ time: "time",
17
+ u8: "tinyint",
18
+ u16: "smallint",
19
+ u32: "int",
20
+ u64: "bigint",
21
+ u128: "decimal",
22
+ };
23
+
24
+ export default value => types[value];