@deterministic-code/datasources-mysql 0.1.1 → 0.1.2

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 (73) hide show
  1. package/dist/MysqlAlterTableStatementRenderer.d.ts +6 -0
  2. package/dist/MysqlAlterTableStatementRenderer.js +13 -0
  3. package/dist/MysqlBulkUpdateStatementTextRenderer.d.ts +1 -1
  4. package/dist/MysqlBulkUpdateStatementTextRenderer.js +9 -0
  5. package/dist/MysqlCreateRoutineStatementRenderer.d.ts +4 -0
  6. package/dist/MysqlCreateTableStatementRenderer.d.ts +1 -1
  7. package/dist/MysqlCreateTableStatementRenderer.js +10 -0
  8. package/dist/MysqlCreateTriggerStatementRenderer.d.ts +4 -0
  9. package/dist/MysqlCreateTriggerStatementRenderer.js +7 -0
  10. package/dist/MysqlDriver.d.ts +5 -1
  11. package/dist/MysqlDriver.js +76 -0
  12. package/dist/MysqlDropIndexStatementRenderer.d.ts +4 -0
  13. package/dist/MysqlDropIndexStatementRenderer.js +6 -0
  14. package/dist/MysqlDropRoutineStatementRenderer.d.ts +4 -0
  15. package/dist/MysqlDropRoutineStatementRenderer.js +6 -0
  16. package/dist/MysqlStatementRenderer.d.ts +12 -1
  17. package/dist/MysqlStatementRenderer.js +60 -0
  18. package/dist/MysqlStoredProcedureStatementRenderer.d.ts +10 -0
  19. package/dist/MysqlStoredProcedureStatementRenderer.js +101 -0
  20. package/dist/bind.d.ts +1 -1
  21. package/dist/bind.js +20 -0
  22. package/dist/columnTypes.js +10 -0
  23. package/dist/command.d.ts +1 -1
  24. package/dist/command.js +143 -0
  25. package/dist/connection-options.js +1 -0
  26. package/dist/connection.d.ts +1 -1
  27. package/dist/connection.js +64 -0
  28. package/dist/converters/BinaryConverter.d.ts +1 -1
  29. package/dist/converters/BinaryConverter.js +6 -0
  30. package/dist/converters/BoolConverter.d.ts +1 -1
  31. package/dist/converters/BoolConverter.js +5 -0
  32. package/dist/converters/DateTimeConverter.d.ts +1 -1
  33. package/dist/converters/DateTimeConverter.js +10 -0
  34. package/dist/converters/DecimalConverter.d.ts +1 -1
  35. package/dist/converters/DecimalConverter.js +5 -0
  36. package/dist/converters/MysqlRowTypeConverters.d.ts +1 -1
  37. package/dist/converters/MysqlRowTypeConverters.js +20 -0
  38. package/dist/converters/UuidConverter.d.ts +1 -1
  39. package/dist/converters/UuidConverter.js +5 -0
  40. package/dist/i-mysql-engine.d.ts +1 -1
  41. package/dist/i-mysql-engine.js +14 -0
  42. package/dist/index.js +1 -0
  43. package/dist/scalar.js +1 -0
  44. package/dist/transaction.d.ts +1 -1
  45. package/dist/transaction.js +15 -0
  46. package/package.json +9 -10
  47. package/src/MysqlBulkUpdateStatementTextRenderer.ts +0 -10
  48. package/src/MysqlCreateTableStatementRenderer.ts +0 -12
  49. package/src/MysqlDriver.ts +0 -54
  50. package/src/MysqlStatementRenderer.test.ts +0 -64
  51. package/src/MysqlStatementRenderer.ts +0 -34
  52. package/src/bind.ts +0 -31
  53. package/src/columnTypes.ts +0 -10
  54. package/src/command.ts +0 -197
  55. package/src/connection-options.ts +0 -6
  56. package/src/connection.ts +0 -91
  57. package/src/converters/BinaryConverter.test.ts +0 -12
  58. package/src/converters/BinaryConverter.ts +0 -9
  59. package/src/converters/BoolConverter.test.ts +0 -14
  60. package/src/converters/BoolConverter.ts +0 -6
  61. package/src/converters/DateTimeConverter.test.ts +0 -14
  62. package/src/converters/DateTimeConverter.ts +0 -15
  63. package/src/converters/DecimalConverter.test.ts +0 -11
  64. package/src/converters/DecimalConverter.ts +0 -7
  65. package/src/converters/MysqlRowTypeConverters.test.ts +0 -19
  66. package/src/converters/MysqlRowTypeConverters.ts +0 -25
  67. package/src/converters/UuidConverter.test.ts +0 -11
  68. package/src/converters/UuidConverter.ts +0 -6
  69. package/src/i-mysql-engine.ts +0 -58
  70. package/src/index.ts +0 -1
  71. package/src/mysql.test.ts +0 -342
  72. package/src/scalar.ts +0 -2
  73. package/src/transaction.ts +0 -21
package/src/mysql.test.ts DELETED
@@ -1,342 +0,0 @@
1
- import { afterEach, describe, expect, it, vi } from "vitest";
2
-
3
- vi.mock("mysql2/promise", () => ({
4
- createConnection: async () => ({
5
- query: async () => [{}],
6
- beginTransaction: async () => {},
7
- commit: async () => {},
8
- rollback: async () => {},
9
- end: async () => {},
10
- }),
11
- }));
12
-
13
- import { Datasource, DatasourceFactory, DatasourceError, IsolationLevel, CRUDRepository, ReadonlyRepository, untyped, Native, ParameterDirection, columnType, RowTypeConverter, CreateTableStatement, ExecuteStoredProcedureStatement, ReturnStatement, SelectStatement, type IDriver } from "@datasources/core";
14
- import { bindParameters, toMysql } from "./bind.ts";
15
- import { MysqlCommand } from "./command.ts";
16
- import { MysqlConnection } from "./connection.ts";
17
- import { MysqlRowTypeConverters } from "./converters/MysqlRowTypeConverters.ts";
18
- import { mysql2Connect, type IMysqlClient, type MysqlQueryHeader } from "./i-mysql-engine.ts";
19
- import { MysqlDriver } from "./MysqlDriver.ts";
20
- import { MysqlTransaction } from "./transaction.ts";
21
- import type { Cells, Scalar } from "./scalar.ts";
22
-
23
- class FakeClient implements IMysqlClient {
24
- queries: Array<{ sql: string; params?: Record<string, Scalar> }> = [];
25
- begins = 0;
26
- commits = 0;
27
- rollbacks = 0;
28
- ended = false;
29
- header: MysqlQueryHeader = { affectedRows: 2, insertId: 5 };
30
- rows: Cells[] = [{ id: 1 }];
31
- arrayResult = false;
32
- /** Multi-result-set payload for CALL (array of row arrays). */
33
- callSets?: Cells[][];
34
-
35
- async query(sql: string, params?: Record<string, Scalar>) {
36
- this.queries.push({ sql, params });
37
- if (this.callSets !== undefined)
38
- return [this.callSets] as [MysqlQueryHeader | Cells[]];
39
- return [this.arrayResult ? this.rows : this.header] as [
40
- MysqlQueryHeader | Cells[],
41
- ];
42
- }
43
- async *queryRows(sql: string, params?: Record<string, Scalar>): AsyncGenerator<Cells> {
44
- this.queries.push({ sql, params });
45
- if (!this.arrayResult) return;
46
- for (const row of this.rows) yield row;
47
- }
48
- async beginTransaction(): Promise<void> {
49
- this.begins += 1;
50
- }
51
- async commit(): Promise<void> {
52
- this.commits += 1;
53
- }
54
- async rollback(): Promise<void> {
55
- this.rollbacks += 1;
56
- }
57
- async end(): Promise<void> {
58
- this.ended = true;
59
- }
60
- }
61
-
62
- const opened = async (url = "mysql://localhost/app", client = new FakeClient()) => {
63
- const connection = new MysqlConnection({ url, connect: async () => client });
64
- await connection.open();
65
- return { connection, client, command: new MysqlCommand(connection) };
66
- };
67
-
68
- afterEach(() => {
69
- DatasourceFactory.reset();
70
- DatasourceFactory.register("mysql", new MysqlDriver());
71
- });
72
-
73
- describe("bindParameters", () => {
74
- it("binds and rewrites parameters", () => {
75
- expect(bindParameters()).toEqual({});
76
- expect(bindParameters(null)).toEqual({});
77
- expect(bindParameters([{ name: "id", value: 1 }])).toEqual({ id: 1 });
78
- expect(toMysql("SELECT * FROM t WHERE id = $id")).toBe(
79
- "SELECT * FROM t WHERE id = :id",
80
- );
81
- expect(toMysql("INSERT INTO t (id) VALUES ($id) RETURNING id")).toBe(
82
- "INSERT INTO t (id) VALUES (:id)",
83
- );
84
- expect(toMysql("INSERT INTO contact_settings (contact_id, key, value) VALUES ($contact_id, $key, $value)"))
85
- .toBe("INSERT INTO contact_settings (contact_id, `key`, value) VALUES (:contact_id, :key, :value)");
86
- expect(toMysql("CREATE TABLE t (id INT PRIMARY KEY)")).toBe("CREATE TABLE t (id INT PRIMARY KEY)");
87
- expect(toMysql("CREATE TABLE t (id INT AUTO_INCREMENT, CONSTRAINT `pk` PRIMARY KEY (`id`))"))
88
- .toBe("CREATE TABLE t (id INT AUTO_INCREMENT, CONSTRAINT `pk` PRIMARY KEY (`id`))");
89
- expect(toMysql("INSERT INTO OldContactsTbl (CntID) VALUES ($CntID)"))
90
- .toBe("INSERT INTO `OldContactsTbl` (`CntID`) VALUES (:CntID)");
91
- });
92
- });
93
-
94
- describe("MysqlConnection", () => {
95
- it("opens, runs SQL, transacts, and closes", async () => {
96
- const { connection, client, command } = await opened("mysql://db/app");
97
- expect(await command.execute("INSERT INTO items (id) VALUES ($id)", [{ name: "id", value: 1 }]))
98
- .toMatchObject({ rowsAffected: 2, result: null });
99
- expect(await command.executeStatement(new CreateTableStatement("users", [{ name: "id", type: "INTEGER" }])))
100
- .toMatchObject({ rowsAffected: 2 });
101
- expect(client.queries.at(-1)?.sql).toBe("CREATE TABLE users (id INTEGER)");
102
- client.arrayResult = true;
103
- expect(await (await command.executeReaderNative(new Native("SELECT 1"))).next()).toBe(true);
104
- expect(await command.executeNative(new Native(" "))).toEqual({ result: undefined, rowsAffected: 0, parameters: undefined });
105
- client.arrayResult = true;
106
- const reader = await command.executeReader("SELECT * FROM items");
107
- expect(await reader.next()).toBe(true);
108
- expect(reader.current).toEqual({ id: 1 });
109
- expect(await (await command.executeReaderNative(new Native(""))).next()).toBe(false);
110
- client.arrayResult = false;
111
- await connection.startTransaction();
112
- await connection.startTransaction(IsolationLevel.ReadUncommitted);
113
- await connection.startTransaction(IsolationLevel.ReadCommitted);
114
- await connection.startTransaction(IsolationLevel.RepeatableRead);
115
- await new MysqlTransaction(connection).commit();
116
- await new MysqlTransaction(connection).abort();
117
- expect(client.begins).toBe(4);
118
- expect(client.commits).toBe(1);
119
- expect(client.rollbacks).toBe(1);
120
- expect(client.queries.map((q) => q.sql)).toEqual([
121
- "SET SESSION sql_mode = CONCAT(@@sql_mode, ',ANSI_QUOTES')",
122
- "INSERT INTO items (id) VALUES (:id)",
123
- "CREATE TABLE users (id INTEGER)",
124
- "SELECT 1",
125
- "SELECT * FROM items",
126
- "SET TRANSACTION ISOLATION LEVEL READ COMMITTED",
127
- "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED",
128
- "SET TRANSACTION ISOLATION LEVEL READ COMMITTED",
129
- "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ",
130
- ]);
131
- await connection.close();
132
- expect(client.ended).toBe(true);
133
- expect(() => connection.require()).toThrow("not open");
134
- await expect(command.executeNative(new Native("x"))).rejects.toThrow("not open");
135
- });
136
-
137
- it("connects through mysql2 and treats array results as row counts", async () => {
138
- const connect = mysql2Connect({
139
- createConnection: async () => new FakeClient(),
140
- });
141
- const named = new MysqlConnection({ url: "mysql://db/app", connect });
142
- await named.open();
143
- await named.close();
144
-
145
- const { command, client, connection } = await opened("x");
146
- client.arrayResult = true;
147
- expect(await command.executeNative(new Native("SELECT 1"))).toMatchObject({ rowsAffected: 1, result: undefined });
148
- client.arrayResult = false;
149
- client.header = {};
150
- expect(await command.executeNative(new Native("UPDATE items"))).toMatchObject({ rowsAffected: 0 });
151
- await connection.close();
152
- await connection.close();
153
- });
154
-
155
- it("opens, reopens, transacts, and closes", async () => {
156
- const { connection, client } = await opened("mysql://db/app");
157
- await expect(connection.open()).rejects.toThrow("Connection is already open");
158
- expect(connection.createCommand()).toBeInstanceOf(MysqlCommand);
159
- expect(connection.isOpen).toBe(true);
160
- const txn = await connection.startTransaction();
161
- await txn.commit();
162
- const txn2 = await connection.startTransaction(IsolationLevel.ReadUncommitted);
163
- expect(txn2.isolation).toBe(IsolationLevel.ReadUncommitted);
164
- await txn2.abort();
165
- expect(txn.isolation).toBe("readCommitted");
166
- await connection.close();
167
- expect(client.ended).toBe(true);
168
- expect(() => connection.ensureOpen()).toThrow(DatasourceError);
169
- await expect(connection.startTransaction()).rejects.toThrow(DatasourceError);
170
- });
171
-
172
- it("defaults url and requires a client to open", async () => {
173
- const connection = new MysqlConnection();
174
- expect(connection.url).toBe("");
175
- await expect(connection.open()).rejects.toThrow(DatasourceError);
176
- });
177
- });
178
-
179
- describe("MysqlCommand", () => {
180
- it("executes SQL through the client", async () => {
181
- const { command, client } = await opened();
182
- client.arrayResult = true;
183
- expect(await command.execute("DELETE FROM items", [{ name: "id", value: 1 }]))
184
- .toEqual({ result: undefined, rowsAffected: 1, parameters: [{ name: "id", value: 1 }] });
185
- expect(await command.executeNative(new Native(""))).toEqual({ result: undefined, rowsAffected: 0, parameters: undefined });
186
- const reader = await command.executeReader("SELECT * FROM items");
187
- expect(await reader.next()).toBe(true);
188
- expect(reader.current).toEqual({ id: 1 });
189
- const empty = await command.executeReaderNative(new Native(""));
190
- expect(await empty.next()).toBe(false);
191
- expect(await (await command.executeReaderNative(new Native(";"))).next()).toBe(false);
192
- client.rows = [{ add_one: 5 }];
193
- const n = { name: "n", value: 4 };
194
- expect(await command.executeStatement(new ReturnStatement("add_one", [n]), [n]))
195
- .toEqual({ result: 5, rowsAffected: 1, parameters: [n] });
196
- client.rows = [];
197
- expect(await command.executeNative(new Native("SELECT 1"))).toEqual({
198
- result: undefined,
199
- rowsAffected: 0,
200
- parameters: undefined,
201
- });
202
- client.rows = [{ result: 5 }];
203
- const start = { name: "start_n", value: 4 };
204
- const out = { name: "result", direction: ParameterDirection.Output };
205
- expect(
206
- await command.executeStatement(new ExecuteStoredProcedureStatement("bump", [start, out]), [start, out]),
207
- ).toMatchObject({
208
- parameters: [start, { name: "result", direction: ParameterDirection.Output, value: 5 }],
209
- });
210
- const inout = { name: "n", value: 4, direction: ParameterDirection.InputOutput };
211
- client.rows = [{ n: 5 }];
212
- expect(await command.executeStatement(new ExecuteStoredProcedureStatement("bump", [inout]), [inout])).toMatchObject({
213
- parameters: [{ name: "n", value: 5, direction: ParameterDirection.InputOutput }],
214
- });
215
- expect(
216
- await command.executeStatement(new ExecuteStoredProcedureStatement("bump", [
217
- { name: "start_n" },
218
- { name: "result", direction: ParameterDirection.Output },
219
- ]), [
220
- { name: "start_n" },
221
- { name: "result", direction: ParameterDirection.Output },
222
- ]),
223
- ).toMatchObject({ rowsAffected: 0 });
224
- client.arrayResult = true;
225
- client.rows = [];
226
- expect(await command.executeStatement(new SelectStatement({ table: "dual", fields: ["1"] }))).toMatchObject({
227
- result: null,
228
- rowsAffected: 0,
229
- });
230
- client.rows = [{}];
231
- expect(await command.executeStatement(new SelectStatement({ table: "dual", fields: ["1"] }))).toMatchObject({ result: null });
232
- expect(await command.executeStatement(new ExecuteStoredProcedureStatement("bump", []))).toMatchObject({
233
- result: undefined,
234
- });
235
- client.arrayResult = false;
236
- expect(await (await command.executeReaderNative(new Native("SELECT 1"))).next()).toBe(false);
237
- expect(
238
- await command.executeStatement(new ExecuteStoredProcedureStatement("bump", [
239
- { name: "result", direction: ParameterDirection.Output },
240
- ]), [
241
- { name: "result", direction: ParameterDirection.Output },
242
- ]),
243
- ).toMatchObject({ rowsAffected: 0 });
244
- });
245
-
246
- it("reads CALL result sets through the reader", async () => {
247
- const { command, client } = await opened();
248
- client.callSets = [[{ id: 1 }, { id: 2 }], [{ id: 3 }]];
249
- const reader = await command.executeReaderNative(new Native("CALL two_ids()"));
250
- expect(await reader.next()).toBe(true);
251
- expect(reader.current).toEqual({ id: 1 });
252
- expect(await reader.next()).toBe(true);
253
- expect(reader.current).toEqual({ id: 2 });
254
- expect(await reader.next()).toBe(false);
255
- expect(await reader.nextResult()).toBe(true);
256
- expect(await reader.next()).toBe(true);
257
- expect(reader.current).toEqual({ id: 3 });
258
- expect(await reader.next()).toBe(false);
259
- expect(await reader.nextResult()).toBe(false);
260
-
261
- client.callSets = undefined;
262
- client.arrayResult = false;
263
- const empty = await command.executeReaderNative(new Native("CALL noop()"));
264
- expect(await empty.next()).toBe(false);
265
- expect(await empty.nextResult()).toBe(false);
266
- });
267
- });
268
-
269
- describe("Mysql datasource", () => {
270
- it("registers and constructs children", async () => {
271
- expect(
272
- await new Datasource("mysql", new MysqlDriver()).createConnection(),
273
- ).toBeInstanceOf(MysqlConnection);
274
- const of = (): IDriver => ({
275
- connection: () => new MysqlConnection({ connect: async () => new FakeClient() }),
276
- command: (c) => c.createCommand(),
277
- transaction: (c, isolation = "readCommitted") =>
278
- new MysqlTransaction(c as MysqlConnection, isolation),
279
- rowTypeConverters: MysqlRowTypeConverters,
280
- columnType,
281
- });
282
- const ds = new Datasource("mysql", of());
283
- expect(ds.provider).toBe("mysql");
284
- const connection = await ds.createConnection();
285
- await (connection as MysqlConnection).open();
286
- const command = await ds.createCommand(connection);
287
- expect(command).toBeInstanceOf(MysqlCommand);
288
- expect(command.connection).toBe(connection);
289
- await command.execute("DELETE FROM items");
290
- await command.executeReaderNative(new Native("SELECT 1"));
291
- await expect(ds.createCommand()).rejects.toThrow("Connection is already open");
292
- const repo = ds.createRepository(untyped(), connection);
293
- expect(ds.createReadonlyRepository(untyped(), connection).constructor).toBe(ReadonlyRepository);
294
- expect(repo).toBeInstanceOf(CRUDRepository);
295
- expect(new Datasource("mysql", of()).createRepository(untyped())).toBeInstanceOf(CRUDRepository);
296
- expect(Datasource.create({ PROVIDER: "mysql" }).provider).toBe("mysql");
297
- expect(MysqlConnection.from({ DATASOURCE_URL: "mysql://db/app" }).url).toBe("mysql://db/app");
298
- expect(MysqlConnection.from({ DATASOURCE_URL: "mysql://db/app" }).url).toBe("mysql://db/app");
299
- expect(MysqlConnection.from().url).toBe("");
300
- const provider = new MysqlDriver();
301
- expect(provider.columnType("int")).toBe("INT");
302
- expect(provider.columnType("uuid")).toBe("CHAR(36)");
303
- expect(provider.columnType("string")).toBe("TEXT");
304
- expect(provider.columnType("datetime")).toBe("TEXT");
305
- expect(provider.columnType("bool")).toBe("TINYINT");
306
- expect(provider.columnType("decimal")).toBe("DECIMAL(18,4)");
307
- expect(provider.columnType("float")).toBe("DOUBLE");
308
- expect(provider.columnType("binary")).toBe("BLOB");
309
- expect(() => provider.columnType("xml")).toThrow('Unknown mysql type "xml"');
310
- expect(provider.command(connection)).toBeInstanceOf(MysqlCommand);
311
- expect(provider.transaction(connection as MysqlConnection).isolation).toBe("readCommitted");
312
- });
313
-
314
- it("maps property targets", () => {
315
- const provider = new MysqlDriver();
316
- const created = "2020-01-02T03:04:05.000Z";
317
- const converter = RowTypeConverter.from(provider.rowTypeConverters, {
318
- Key: "uuid",
319
- Active: "bool",
320
- Login: "string",
321
- Created: "datetime",
322
- });
323
- const row = converter.convert({
324
- Key: "11111111-1111-1111-1111-111111111111",
325
- Active: 1,
326
- Login: "ada",
327
- Created: created,
328
- });
329
- expect(row).toEqual({
330
- Key: "11111111-1111-1111-1111-111111111111",
331
- Active: true,
332
- Login: "ada",
333
- Created: new Date(created),
334
- });
335
- expect(converter.reverseConvert(row)).toEqual({
336
- Key: "11111111-1111-1111-1111-111111111111",
337
- Active: 1,
338
- Login: "ada",
339
- Created: "2020-01-02 03:04:05.000",
340
- });
341
- });
342
- });
package/src/scalar.ts DELETED
@@ -1,2 +0,0 @@
1
- export type Scalar = string | number | boolean | bigint | null;
2
- export type Cells = Record<string, Scalar>;
@@ -1,21 +0,0 @@
1
- import {
2
- IsolationLevel,
3
- type ITransaction,
4
- type IsolationLevelName,
5
- } from "@datasources/core";
6
- import type { MysqlConnection } from "./connection.ts";
7
-
8
- export class MysqlTransaction implements ITransaction {
9
- constructor(
10
- readonly connection: MysqlConnection,
11
- readonly isolation: IsolationLevelName = IsolationLevel.ReadCommitted,
12
- ) {}
13
-
14
- async commit(): Promise<void> {
15
- await this.connection.require().commit();
16
- }
17
-
18
- async abort(): Promise<void> {
19
- await this.connection.require().rollback();
20
- }
21
- }