@primate/mysql 0.1.2 → 0.2.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,25 @@
1
+ import type TypedArray from "@rcompat/type/TypedArray";
2
+ type Param = bigint | boolean | Date | null | number | string | TypedArray;
3
+ type Validate<T extends {
4
+ [K in keyof T]: Param;
5
+ }> = T;
6
+ type ColumnTypes = Validate<{
7
+ BIGINT: string;
8
+ "BIGINT UNSIGNED": string;
9
+ BLOB: Uint8Array<ArrayBuffer>;
10
+ BOOL: number;
11
+ "DATETIME(3)": Date;
12
+ "DECIMAL(39, 0)": string;
13
+ DOUBLE: number;
14
+ INT: number;
15
+ "INT NOT NULL AUTO_INCREMENT PRIMARY KEY": number;
16
+ "INT UNSIGNED": number;
17
+ SMALLINT: number;
18
+ "SMALLINT UNSIGNED": number;
19
+ TEXT: string;
20
+ "TIME": string;
21
+ TINYINT: number;
22
+ "TINYINT UNSIGNED": number;
23
+ }>;
24
+ export type { ColumnTypes as default };
25
+ //# sourceMappingURL=ColumnTypes.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ColumnTypes.js.map
@@ -0,0 +1,47 @@
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/string").StringType;
9
+ host: import("pema").DefaultType<import("pema/string").StringType, "localhost">;
10
+ password: import("pema").OptionalType<import("pema/string").StringType>;
11
+ port: import("pema").DefaultType<import("pema/uint").UintType<"u32">, 3306>;
12
+ username: import("pema").OptionalType<import("pema/string").StringType>;
13
+ }>;
14
+ export default class MySQLDatabase extends Database {
15
+ #private;
16
+ static config: typeof schema.input;
17
+ constructor(config?: typeof schema.input);
18
+ get typemap(): TypeMap<Dict>;
19
+ formatBinds(binds: Dict): Dict;
20
+ close(): Promise<void>;
21
+ get schema(): {
22
+ create: (name: string, store: StoreSchema) => Promise<void>;
23
+ delete: (name: string) => Promise<void>;
24
+ };
25
+ create<O extends Dict>(as: As, args: {
26
+ record: DataDict;
27
+ }): Promise<O>;
28
+ read(as: As, args: {
29
+ count: true;
30
+ criteria: DataDict;
31
+ }): Promise<number>;
32
+ read(as: As, args: {
33
+ criteria: DataDict;
34
+ fields?: string[];
35
+ limit?: number;
36
+ sort?: Dict<"asc" | "desc">;
37
+ }): Promise<Dict[]>;
38
+ update(as: As, args: {
39
+ changes: DataDict;
40
+ criteria: DataDict;
41
+ }): Promise<number>;
42
+ delete(as: As, args: {
43
+ criteria: DataDict;
44
+ }): Promise<number>;
45
+ }
46
+ export {};
47
+ //# sourceMappingURL=Database.d.ts.map
@@ -0,0 +1,148 @@
1
+ import typemap from "#typemap";
2
+ import Database from "@primate/core/Database";
3
+ import assert from "@rcompat/assert";
4
+ import mysql from "mysql2/promise";
5
+ import pema from "pema";
6
+ import string from "pema/string";
7
+ import uint from "pema/uint";
8
+ const schema = pema({
9
+ database: string,
10
+ host: string.default("localhost"),
11
+ password: string.optional(),
12
+ port: uint.port().default(3306),
13
+ username: string.optional(),
14
+ });
15
+ export default class MySQLDatabase extends Database {
16
+ #factory;
17
+ #client;
18
+ static config;
19
+ constructor(config) {
20
+ super(":");
21
+ const parsed = schema.parse(config);
22
+ this.#factory = () => mysql.createPool({
23
+ host: parsed.host,
24
+ port: parsed.port,
25
+ database: parsed.database,
26
+ user: parsed.username,
27
+ password: parsed.password,
28
+ connectionLimit: 10,
29
+ queueLimit: 0,
30
+ keepAliveInitialDelay: 0,
31
+ enableKeepAlive: true,
32
+ waitForConnections: true,
33
+ namedPlaceholders: true,
34
+ bigNumberStrings: true,
35
+ supportBigNumbers: true,
36
+ });
37
+ }
38
+ get typemap() {
39
+ return typemap;
40
+ }
41
+ #get() {
42
+ if (this.#client === undefined) {
43
+ this.#client = this.#factory();
44
+ }
45
+ return this.#client;
46
+ }
47
+ formatBinds(binds) {
48
+ return Object.fromEntries(Object.entries(binds).map(([k, v]) => [k.replace(/^[:$]/, ""), v]));
49
+ }
50
+ async close() {
51
+ await this.#get().end();
52
+ }
53
+ async #with(executor) {
54
+ const connection = await this.#get().getConnection();
55
+ try {
56
+ return await executor(connection);
57
+ }
58
+ finally {
59
+ connection.release();
60
+ }
61
+ }
62
+ async #new(name, store) {
63
+ const body = Object.entries(store)
64
+ .map(([key, value]) => `${this.ident(key)} ${this.column(value.datatype)}`)
65
+ .join(",");
66
+ const query = `CREATE TABLE IF NOT EXISTS ${this.ident(name)} (${body})`;
67
+ await this.#with(async (connection) => {
68
+ await connection.query(query);
69
+ });
70
+ }
71
+ async #drop(name) {
72
+ const query = `DROP TABLE IF EXISTS ${this.ident(name)}`;
73
+ await this.#with(async (connection) => {
74
+ await connection.query(query);
75
+ });
76
+ }
77
+ get schema() {
78
+ return {
79
+ create: this.#new.bind(this),
80
+ delete: this.#drop.bind(this),
81
+ };
82
+ }
83
+ async create(as, args) {
84
+ const keys = Object.keys(args.record);
85
+ const columns = keys.map(k => this.ident(k));
86
+ const values = keys.map(key => `:${key}`).join(",");
87
+ const payload = `(${columns.join(",")}) VALUES (${values})`;
88
+ const query = `INSERT INTO ${this.table(as)} ${payload};`;
89
+ const binds = await this.bind(as.types, args.record);
90
+ return this.#with(async (connection) => {
91
+ const [{ insertId }] = await connection.query(query, binds);
92
+ return this.unbind(as.types, { ...args.record, id: insertId });
93
+ });
94
+ }
95
+ async read(as, args) {
96
+ const where = this.toWhere(as.types, args.criteria);
97
+ const binds = await this.bindCriteria(as.types, args.criteria);
98
+ if (args.count === true) {
99
+ return this.#with(async (connection) => {
100
+ const query = `SELECT COUNT(*) AS n FROM ${this.table(as)} ${where}`;
101
+ const [[{ n }]] = await connection.query(query, binds);
102
+ return Number(n);
103
+ });
104
+ }
105
+ const select = this.toSelect(as.types, args.fields);
106
+ const sort = this.toSort(as.types, args.sort);
107
+ const limit = this.toLimit(args.limit);
108
+ const query = `SELECT ${select}
109
+ FROM ${this.table(as)} ${where}${sort}${limit};`;
110
+ return this.#with(async (connection) => {
111
+ const [records] = await connection.query(query, binds);
112
+ return records.map(record => this.unbind(as.types, record));
113
+ });
114
+ }
115
+ async update(as, args) {
116
+ assert(Object.keys(args.criteria).length > 0, "update: no criteria");
117
+ const where = this.toWhere(as.types, args.criteria);
118
+ const criteria = await this.bindCriteria(as.types, args.criteria);
119
+ const { set, binds: set_binds } = await this.toSet(as.types, args.changes);
120
+ const binds = { ...criteria, ...set_binds };
121
+ const query = `
122
+ UPDATE ${this.table(as)}
123
+ ${set}
124
+ WHERE id IN (
125
+ SELECT id FROM (
126
+ SELECT id FROM ${this.table(as)}
127
+ ${where}
128
+ ) AS to_update
129
+ );
130
+ `;
131
+ return this.#with(async (connection) => {
132
+ const [{ affectedRows }] = await connection.query(query, binds);
133
+ return affectedRows;
134
+ });
135
+ }
136
+ async delete(as, args) {
137
+ assert(Object.keys(args.criteria).length > 0, "delete: no criteria");
138
+ const where = this.toWhere(as.types, args.criteria);
139
+ const binds = await this.bindCriteria(as.types, args.criteria);
140
+ const query = `DELETE FROM ${this.table(as)} ${where}`;
141
+ return this.#with(async (connection) => {
142
+ const [{ affectedRows }] = await connection.query(query, binds);
143
+ return affectedRows;
144
+ });
145
+ }
146
+ ;
147
+ }
148
+ //# 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,106 @@
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: "BOOL",
32
+ unbind(value) {
33
+ return Number(value) === 1;
34
+ },
35
+ },
36
+ datetime: identity("DATETIME(3)"),
37
+ f32: identity("DOUBLE"),
38
+ f64: identity("DOUBLE"),
39
+ i128: {
40
+ bind(value) {
41
+ return String(value);
42
+ },
43
+ column: "DECIMAL(39, 0)",
44
+ unbind(value) {
45
+ return BigInt(value);
46
+ },
47
+ },
48
+ i16: number("SMALLINT"),
49
+ i32: number("INT"),
50
+ i64: {
51
+ bind(value) {
52
+ return String(value);
53
+ },
54
+ column: "BIGINT",
55
+ unbind(value) {
56
+ return BigInt(value);
57
+ },
58
+ },
59
+ i8: number("TINYINT"),
60
+ primary: {
61
+ bind(value) {
62
+ if (numeric(value)) {
63
+ return Number(value);
64
+ }
65
+ throw new Error(`\`${value}\` is not a valid primary key value`);
66
+ },
67
+ column: "INT NOT NULL AUTO_INCREMENT PRIMARY KEY",
68
+ unbind(value) {
69
+ return String(value);
70
+ },
71
+ },
72
+ string: identity("TEXT"),
73
+ time: identity("TEXT"),
74
+ u128: {
75
+ bind(value) {
76
+ return String(value);
77
+ },
78
+ column: "DECIMAL(39, 0)",
79
+ unbind(value) {
80
+ return BigInt(value);
81
+ },
82
+ },
83
+ u16: number("SMALLINT UNSIGNED"),
84
+ u32: number("INT UNSIGNED"),
85
+ u64: {
86
+ bind(value) {
87
+ return String(value);
88
+ },
89
+ column: "BIGINT UNSIGNED",
90
+ unbind(value) {
91
+ return BigInt(value);
92
+ },
93
+ },
94
+ u8: number("TINYINT UNSIGNED"),
95
+ url: {
96
+ bind(value) {
97
+ return value.toString();
98
+ },
99
+ column: "TEXT",
100
+ unbind(value) {
101
+ return new URL(value);
102
+ },
103
+ },
104
+ };
105
+ export default typemap;
106
+ //# 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,34 +1,45 @@
1
1
  {
2
2
  "name": "@primate/mysql",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "description": "Primate MySQL database",
5
- "homepage": "https://primatejs.com/modules/mysql",
6
- "bugs": "https://github.com/primatejs/primate/issues",
5
+ "homepage": "https://primate.run/docs/database/mysql",
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/mysql"
16
17
  },
17
18
  "dependencies": {
18
- "@rcompat/invariant": "^0.5.0",
19
- "@rcompat/object": "^0.5.0",
20
- "mysql2": "^3.11.0",
21
- "@primate/core": "^0.1.4",
22
- "@primate/store": "^0.25.1"
19
+ "@rcompat/assert": "^0.3.1",
20
+ "@rcompat/is": "^0.1.4",
21
+ "@rcompat/record": "^0.9.1",
22
+ "mysql2": "^3.15.1",
23
+ "pema": "",
24
+ "@primate/core": "^0.2.0"
23
25
  },
24
26
  "type": "module",
25
27
  "imports": {
26
28
  "#*": {
27
- "@primate/lt": "./src/private/*.js",
28
- "default": "./src/private/*.js"
29
+ "apekit": "./src/private/*.ts",
30
+ "default": "./lib/private/*.js"
29
31
  }
30
32
  },
31
33
  "exports": {
32
- ".": "./src/default.js"
34
+ ".": {
35
+ "apekit": "./src/public/index.ts",
36
+ "default": "./lib/public/index.js"
37
+ }
38
+ },
39
+ "scripts": {
40
+ "build": "npm run clean && tsc",
41
+ "clean": "rm -rf ./lib",
42
+ "lint": "eslint .",
43
+ "test": "npm run build && npx proby"
33
44
  }
34
45
  }
package/src/default.js DELETED
@@ -1,12 +0,0 @@
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
- });
@@ -1,105 +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
-
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
- }
@@ -1,16 +0,0 @@
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
- });
@@ -1,4 +0,0 @@
1
- export default {
2
- host: "localhost",
3
- port: 3306,
4
- };
@@ -1,81 +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
- },
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
- };
@@ -1,24 +0,0 @@
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];