@deterministic-code/datasources-mysql 0.1.0 → 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.
- package/dist/MysqlAlterTableStatementRenderer.d.ts +6 -0
- package/dist/MysqlAlterTableStatementRenderer.js +13 -0
- package/dist/MysqlBulkUpdateStatementTextRenderer.d.ts +4 -0
- package/dist/MysqlBulkUpdateStatementTextRenderer.js +9 -0
- package/dist/MysqlCreateRoutineStatementRenderer.d.ts +4 -0
- package/dist/MysqlCreateTableStatementRenderer.d.ts +5 -0
- package/dist/MysqlCreateTableStatementRenderer.js +10 -0
- package/dist/MysqlCreateTriggerStatementRenderer.d.ts +4 -0
- package/dist/MysqlCreateTriggerStatementRenderer.js +7 -0
- package/dist/MysqlDriver.d.ts +16 -0
- package/dist/MysqlDriver.js +76 -0
- package/dist/MysqlDropIndexStatementRenderer.d.ts +4 -0
- package/dist/MysqlDropIndexStatementRenderer.js +6 -0
- package/dist/MysqlDropRoutineStatementRenderer.d.ts +4 -0
- package/dist/MysqlDropRoutineStatementRenderer.js +6 -0
- package/dist/MysqlStatementRenderer.d.ts +18 -0
- package/dist/MysqlStatementRenderer.js +60 -0
- package/dist/MysqlStoredProcedureStatementRenderer.d.ts +10 -0
- package/dist/MysqlStoredProcedureStatementRenderer.js +101 -0
- package/dist/bind.d.ts +5 -0
- package/dist/bind.js +20 -0
- package/dist/columnTypes.d.ts +1 -0
- package/dist/columnTypes.js +10 -0
- package/dist/command.d.ts +16 -0
- package/dist/command.js +143 -0
- package/dist/connection-options.d.ts +5 -0
- package/dist/connection-options.js +1 -0
- package/dist/connection.d.ts +19 -0
- package/dist/connection.js +64 -0
- package/dist/converters/BinaryConverter.d.ts +5 -0
- package/dist/converters/BinaryConverter.js +6 -0
- package/dist/converters/BoolConverter.d.ts +5 -0
- package/dist/converters/BoolConverter.js +5 -0
- package/dist/converters/DateTimeConverter.d.ts +5 -0
- package/dist/converters/DateTimeConverter.js +10 -0
- package/dist/converters/DecimalConverter.d.ts +5 -0
- package/dist/converters/DecimalConverter.js +5 -0
- package/dist/converters/MysqlRowTypeConverters.d.ts +3 -0
- package/dist/converters/MysqlRowTypeConverters.js +20 -0
- package/dist/converters/UuidConverter.d.ts +5 -0
- package/dist/converters/UuidConverter.js +5 -0
- package/dist/i-mysql-engine.d.ts +27 -0
- package/dist/i-mysql-engine.js +14 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/scalar.js +1 -0
- package/dist/transaction.d.ts +9 -0
- package/dist/transaction.js +15 -0
- package/package.json +10 -7
- package/src/MysqlBulkUpdateStatementTextRenderer.ts +0 -10
- package/src/MysqlCreateTableStatementRenderer.ts +0 -12
- package/src/MysqlDriver.ts +0 -54
- package/src/MysqlStatementRenderer.ts +0 -34
- package/src/bind.ts +0 -31
- package/src/columnTypes.ts +0 -10
- package/src/command.ts +0 -197
- package/src/connection-options.ts +0 -6
- package/src/connection.ts +0 -91
- package/src/converters/BinaryConverter.ts +0 -9
- package/src/converters/BoolConverter.ts +0 -6
- package/src/converters/DateTimeConverter.ts +0 -15
- package/src/converters/DecimalConverter.ts +0 -7
- package/src/converters/MysqlRowTypeConverters.ts +0 -25
- package/src/converters/UuidConverter.ts +0 -6
- package/src/i-mysql-engine.ts +0 -58
- package/src/index.ts +0 -1
- package/src/transaction.ts +0 -21
- /package/{src/scalar.ts → dist/scalar.d.ts} +0 -0
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { DatasourceError, IsolationLevel, StatementTextRenderer, } from "@deterministic-code/datasources";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { MysqlCommand } from "./command.js";
|
|
4
|
+
import { mysql2Connect, } from "./i-mysql-engine.js";
|
|
5
|
+
import { MysqlStatementRenderer } from "./MysqlStatementRenderer.js";
|
|
6
|
+
import { MysqlTransaction } from "./transaction.js";
|
|
7
|
+
const require = createRequire(import.meta.url);
|
|
8
|
+
const isoSql = (isolation) => isolation === IsolationLevel.ReadUncommitted
|
|
9
|
+
? "READ UNCOMMITTED"
|
|
10
|
+
: isolation === IsolationLevel.ReadCommitted
|
|
11
|
+
? "READ COMMITTED"
|
|
12
|
+
: "REPEATABLE READ";
|
|
13
|
+
export class MysqlConnection {
|
|
14
|
+
provider = "mysql";
|
|
15
|
+
url;
|
|
16
|
+
isOpen = false;
|
|
17
|
+
client;
|
|
18
|
+
connect;
|
|
19
|
+
static from = (options) => {
|
|
20
|
+
const url = options?.DATASOURCE_URL ?? "";
|
|
21
|
+
return new MysqlConnection({
|
|
22
|
+
url,
|
|
23
|
+
connect: mysql2Connect(require("mysql2/promise")),
|
|
24
|
+
});
|
|
25
|
+
};
|
|
26
|
+
constructor(options = {}) {
|
|
27
|
+
this.url = options.url ?? "";
|
|
28
|
+
this.connect = options.connect;
|
|
29
|
+
}
|
|
30
|
+
createCommand = () => new MysqlCommand(this, new StatementTextRenderer(t => new MysqlStatementRenderer(t)));
|
|
31
|
+
async open() {
|
|
32
|
+
if (this.isOpen)
|
|
33
|
+
throw new DatasourceError("Connection is already open");
|
|
34
|
+
if (!this.client) {
|
|
35
|
+
if (!this.connect)
|
|
36
|
+
throw new DatasourceError("MySQL engine is required");
|
|
37
|
+
this.client = await this.connect(this.url);
|
|
38
|
+
}
|
|
39
|
+
await this.client.query("SET SESSION sql_mode = CONCAT(@@sql_mode, ',ANSI_QUOTES')");
|
|
40
|
+
this.isOpen = true;
|
|
41
|
+
}
|
|
42
|
+
async close() {
|
|
43
|
+
await this.client?.end();
|
|
44
|
+
this.client = undefined;
|
|
45
|
+
this.isOpen = false;
|
|
46
|
+
}
|
|
47
|
+
[Symbol.asyncDispose] = () => this.close();
|
|
48
|
+
async startTransaction(isolation = IsolationLevel.Serializable) {
|
|
49
|
+
this.ensureOpen();
|
|
50
|
+
const client = this.require();
|
|
51
|
+
await client.query(`SET TRANSACTION ISOLATION LEVEL ${isoSql(isolation)}`);
|
|
52
|
+
await client.beginTransaction();
|
|
53
|
+
return new MysqlTransaction(this, isolation);
|
|
54
|
+
}
|
|
55
|
+
ensureOpen() {
|
|
56
|
+
if (!this.isOpen)
|
|
57
|
+
throw new DatasourceError("Connection is not open");
|
|
58
|
+
}
|
|
59
|
+
require() {
|
|
60
|
+
if (!this.client)
|
|
61
|
+
throw new DatasourceError("Connection is not open");
|
|
62
|
+
return this.client;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { TypeConverter } from "@deterministic-code/datasources";
|
|
2
|
+
const bytes = (value) => typeof value === "string" ? Uint8Array.from(Buffer.from(value, "base64")) : value;
|
|
3
|
+
export class BinaryConverter extends TypeConverter {
|
|
4
|
+
convert = (from) => bytes(from);
|
|
5
|
+
reverseConvert = (to) => bytes(to);
|
|
6
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { TypeConverter } from "@deterministic-code/datasources";
|
|
2
|
+
const stamp = (date) => date.toISOString().replace("T", " ").replace("Z", "");
|
|
3
|
+
export class DateTimeConverter extends TypeConverter {
|
|
4
|
+
convert = (from) => typeof from === "string" ? new Date(from) : from;
|
|
5
|
+
reverseConvert = (to) => to instanceof Date
|
|
6
|
+
? stamp(to)
|
|
7
|
+
: typeof to === "string" && /^\d{4}-\d{2}-\d{2}T/.test(to)
|
|
8
|
+
? stamp(new Date(to))
|
|
9
|
+
: to;
|
|
10
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { BinaryConverter } from "./BinaryConverter.js";
|
|
2
|
+
import { BoolConverter } from "./BoolConverter.js";
|
|
3
|
+
import { DateTimeConverter } from "./DateTimeConverter.js";
|
|
4
|
+
import { DecimalConverter } from "./DecimalConverter.js";
|
|
5
|
+
import { UuidConverter } from "./UuidConverter.js";
|
|
6
|
+
export const MysqlRowTypeConverters = {
|
|
7
|
+
bool: new BoolConverter(),
|
|
8
|
+
datetime: new DateTimeConverter(),
|
|
9
|
+
uuid: new UuidConverter(),
|
|
10
|
+
decimal: new DecimalConverter(),
|
|
11
|
+
binary: new BinaryConverter(),
|
|
12
|
+
};
|
|
13
|
+
export const reverse = (value) => typeof value === "boolean"
|
|
14
|
+
? MysqlRowTypeConverters.bool.reverseConvert(value)
|
|
15
|
+
: value instanceof Date
|
|
16
|
+
|| (typeof value === "string" && /^\d{4}-\d{2}-\d{2}T/.test(value))
|
|
17
|
+
? MysqlRowTypeConverters.datetime.reverseConvert(value)
|
|
18
|
+
: value instanceof Uint8Array
|
|
19
|
+
? MysqlRowTypeConverters.binary.reverseConvert(value)
|
|
20
|
+
: value;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { Parameter } from "@deterministic-code/datasources";
|
|
2
|
+
import type { Cells, Scalar } from "./scalar.js";
|
|
3
|
+
export interface MysqlExecuteResult {
|
|
4
|
+
rowsAffected: number;
|
|
5
|
+
result?: Scalar;
|
|
6
|
+
parameters?: Parameter[];
|
|
7
|
+
}
|
|
8
|
+
export interface MysqlQueryHeader {
|
|
9
|
+
affectedRows?: number;
|
|
10
|
+
insertId?: Scalar;
|
|
11
|
+
}
|
|
12
|
+
export interface IMysqlClient {
|
|
13
|
+
query(sql: string, params?: Record<string, Scalar>): Promise<[MysqlQueryHeader | Cells[]]>;
|
|
14
|
+
queryRows(sql: string, params?: Record<string, Scalar>): AsyncIterable<Cells>;
|
|
15
|
+
beginTransaction(): Promise<void>;
|
|
16
|
+
commit(): Promise<void>;
|
|
17
|
+
rollback(): Promise<void>;
|
|
18
|
+
end(): Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
export type MysqlCreateConnection = (url: string) => Promise<IMysqlClient>;
|
|
21
|
+
export type Mysql2Module = {
|
|
22
|
+
createConnection: (options: {
|
|
23
|
+
uri: string;
|
|
24
|
+
namedPlaceholders: boolean;
|
|
25
|
+
}) => Promise<IMysqlClient>;
|
|
26
|
+
};
|
|
27
|
+
export declare const mysql2Connect: (mysql: Mysql2Module) => MysqlCreateConnection;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export const mysql2Connect = (mysql) => async (uri) => {
|
|
2
|
+
const client = (await mysql.createConnection({
|
|
3
|
+
uri,
|
|
4
|
+
namedPlaceholders: true,
|
|
5
|
+
}));
|
|
6
|
+
return {
|
|
7
|
+
query: (sql, params) => client.query(sql, params),
|
|
8
|
+
queryRows: (sql, params) => client.connection.query(sql, params).stream(),
|
|
9
|
+
beginTransaction: () => client.beginTransaction(),
|
|
10
|
+
commit: () => client.commit(),
|
|
11
|
+
rollback: () => client.rollback(),
|
|
12
|
+
end: () => client.end(),
|
|
13
|
+
};
|
|
14
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { MysqlDriver } from "./MysqlDriver.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { MysqlDriver } from "./MysqlDriver.js";
|
package/dist/scalar.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type ITransaction, type IsolationLevelName } from "@deterministic-code/datasources";
|
|
2
|
+
import type { MysqlConnection } from "./connection.js";
|
|
3
|
+
export declare class MysqlTransaction implements ITransaction {
|
|
4
|
+
readonly connection: MysqlConnection;
|
|
5
|
+
readonly isolation: IsolationLevelName;
|
|
6
|
+
constructor(connection: MysqlConnection, isolation?: IsolationLevelName);
|
|
7
|
+
commit(): Promise<void>;
|
|
8
|
+
abort(): Promise<void>;
|
|
9
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { IsolationLevel, } from "@deterministic-code/datasources";
|
|
2
|
+
export class MysqlTransaction {
|
|
3
|
+
connection;
|
|
4
|
+
isolation;
|
|
5
|
+
constructor(connection, isolation = IsolationLevel.ReadCommitted) {
|
|
6
|
+
this.connection = connection;
|
|
7
|
+
this.isolation = isolation;
|
|
8
|
+
}
|
|
9
|
+
async commit() {
|
|
10
|
+
await this.connection.require().commit();
|
|
11
|
+
}
|
|
12
|
+
async abort() {
|
|
13
|
+
await this.connection.require().rollback();
|
|
14
|
+
}
|
|
15
|
+
}
|
package/package.json
CHANGED
|
@@ -1,21 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@deterministic-code/datasources-mysql",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"main": "./
|
|
6
|
-
"types": "./
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"types": "./dist/index.d.js",
|
|
7
7
|
"exports": {
|
|
8
|
-
".":
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.js",
|
|
10
|
+
"import": "./dist/index.js",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
|
+
}
|
|
9
13
|
},
|
|
10
14
|
"files": [
|
|
11
|
-
"
|
|
15
|
+
"dist"
|
|
12
16
|
],
|
|
13
17
|
"publishConfig": {
|
|
14
18
|
"access": "public"
|
|
15
19
|
},
|
|
16
|
-
"license": "MIT",
|
|
17
20
|
"dependencies": {
|
|
18
|
-
"@deterministic-code/datasources": "^0.1.
|
|
21
|
+
"@deterministic-code/datasources": "^0.1.2",
|
|
19
22
|
"mysql2": "^3.14.0"
|
|
20
23
|
}
|
|
21
24
|
}
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import { BulkUpdateStatementTextRenderer, type BulkUpdateStatement } from "@deterministic-code/datasources";
|
|
2
|
-
|
|
3
|
-
export class MysqlBulkUpdateStatementTextRenderer extends BulkUpdateStatementTextRenderer {
|
|
4
|
-
override render = (statement: BulkUpdateStatement): string => {
|
|
5
|
-
const assigns = statement.set
|
|
6
|
-
.map((column) => `${statement.table}.${column} = data.${column}`)
|
|
7
|
-
.join(", ");
|
|
8
|
-
return `UPDATE ${statement.table} JOIN ${this.source(statement)} ON ${this.on(statement)} SET ${assigns}`;
|
|
9
|
-
};
|
|
10
|
-
}
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import { CreateTableStatementTextRenderer, type Column } from "@deterministic-code/datasources";
|
|
2
|
-
import { columnTypes } from "./columnTypes.ts";
|
|
3
|
-
|
|
4
|
-
export class MysqlCreateTableStatementRenderer extends CreateTableStatementTextRenderer {
|
|
5
|
-
protected typeName(column: Column): string {
|
|
6
|
-
return columnTypes[column.type] ?? column.type;
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
protected identity(column: Column): string {
|
|
10
|
-
return column.identity ? " AUTO_INCREMENT" : "";
|
|
11
|
-
}
|
|
12
|
-
}
|
package/src/MysqlDriver.ts
DELETED
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
DatasourceError,
|
|
3
|
-
StatementTextRenderer,
|
|
4
|
-
type Cell,
|
|
5
|
-
type DatasourceOptions,
|
|
6
|
-
type ICommand,
|
|
7
|
-
type IConnection,
|
|
8
|
-
type IDriver,
|
|
9
|
-
type Information,
|
|
10
|
-
type ITransaction,
|
|
11
|
-
type IsolationLevel,
|
|
12
|
-
type TypeConverter,
|
|
13
|
-
} from "@deterministic-code/datasources";
|
|
14
|
-
import { MysqlConnection } from "./connection.ts";
|
|
15
|
-
import { MysqlCommand } from "./command.ts";
|
|
16
|
-
import { MysqlTransaction } from "./transaction.ts";
|
|
17
|
-
import { MysqlRowTypeConverters } from "./converters/MysqlRowTypeConverters.ts";
|
|
18
|
-
import { MysqlStatementRenderer } from "./MysqlStatementRenderer.ts";
|
|
19
|
-
import { columnTypes } from "./columnTypes.ts";
|
|
20
|
-
|
|
21
|
-
export { columnTypes };
|
|
22
|
-
|
|
23
|
-
const statements = new StatementTextRenderer(t => new MysqlStatementRenderer(t));
|
|
24
|
-
|
|
25
|
-
export class MysqlDriver implements IDriver {
|
|
26
|
-
readonly statementRenderer = statements;
|
|
27
|
-
readonly information: Information = {
|
|
28
|
-
descriptions: [
|
|
29
|
-
"MySQL / MariaDB server driver.",
|
|
30
|
-
"Full connection, command, transaction, and repository support.",
|
|
31
|
-
],
|
|
32
|
-
overrides: [
|
|
33
|
-
"Overrides SelectInsertedIdStatement to SELECT LAST_INSERT_ID() AS {column}",
|
|
34
|
-
"Overrides CreateTableStatement identity to AUTO_INCREMENT",
|
|
35
|
-
"Overrides CreateTableStatement type mapping (int→INT, uuid→CHAR(36), string/datetime→TEXT, bool→TINYINT, decimal→DECIMAL(18,4), float→DOUBLE, binary→BLOB)",
|
|
36
|
-
],
|
|
37
|
-
changeLogs: [],
|
|
38
|
-
};
|
|
39
|
-
rowTypeConverters: Record<string, TypeConverter<Cell, Cell>> = MysqlRowTypeConverters;
|
|
40
|
-
columnType = (name: string): string =>
|
|
41
|
-
columnTypes[name] ??
|
|
42
|
-
(() => {
|
|
43
|
-
throw new DatasourceError(`Unknown mysql type "${name}"`);
|
|
44
|
-
})();
|
|
45
|
-
connection = (options?: DatasourceOptions): IConnection =>
|
|
46
|
-
MysqlConnection.from(options);
|
|
47
|
-
command = (connection: IConnection): ICommand =>
|
|
48
|
-
new MysqlCommand(connection as MysqlConnection, statements);
|
|
49
|
-
transaction = (
|
|
50
|
-
connection: IConnection,
|
|
51
|
-
isolation: IsolationLevel = "readCommitted",
|
|
52
|
-
): ITransaction =>
|
|
53
|
-
new MysqlTransaction(connection as MysqlConnection, isolation);
|
|
54
|
-
}
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
BulkUpdateStatement,
|
|
3
|
-
CreateTableStatement,
|
|
4
|
-
SelectInsertedIdStatement,
|
|
5
|
-
SelectInsertedIdStatementTextRenderer,
|
|
6
|
-
StatementRenderer,
|
|
7
|
-
type StatementTextRenderer,
|
|
8
|
-
} from "@deterministic-code/datasources";
|
|
9
|
-
import { MysqlBulkUpdateStatementTextRenderer } from "./MysqlBulkUpdateStatementTextRenderer.ts";
|
|
10
|
-
import { MysqlCreateTableStatementRenderer } from "./MysqlCreateTableStatementRenderer.ts";
|
|
11
|
-
|
|
12
|
-
class MysqlSelectInsertedIdStatementTextRenderer extends SelectInsertedIdStatementTextRenderer {
|
|
13
|
-
override render(statement: SelectInsertedIdStatement): string {
|
|
14
|
-
return `SELECT LAST_INSERT_ID() AS ${statement.column}`;
|
|
15
|
-
}
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export class MysqlStatementRenderer extends StatementRenderer {
|
|
19
|
-
constructor(text: StatementTextRenderer) {
|
|
20
|
-
super(text);
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
protected override visitSelectInsertedId(inserted: SelectInsertedIdStatement): string {
|
|
24
|
-
return new MysqlSelectInsertedIdStatementTextRenderer().render(inserted);
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
protected override visitCreateTable(create: CreateTableStatement): string {
|
|
28
|
-
return new MysqlCreateTableStatementRenderer().render(create);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
protected override visitBulkUpdate(update: BulkUpdateStatement): string {
|
|
32
|
-
return new MysqlBulkUpdateStatementTextRenderer().render(update);
|
|
33
|
-
}
|
|
34
|
-
}
|
package/src/bind.ts
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import { parametersToRecord, type Cell, type Parameter } from "@deterministic-code/datasources";
|
|
2
|
-
import { reverse } from "./converters/MysqlRowTypeConverters.ts";
|
|
3
|
-
import type { Scalar } from "./scalar.ts";
|
|
4
|
-
|
|
5
|
-
const NAME = /\$([A-Za-z_][A-Za-z0-9_]*)/g;
|
|
6
|
-
const TOKEN = /\$[A-Za-z_][A-Za-z0-9_]*|'[^']*'|"[^"]*"|`[^`]*`|\b[A-Za-z_][A-Za-z0-9_]*\b/g;
|
|
7
|
-
|
|
8
|
-
export const withoutReturning = (sql: string): string =>
|
|
9
|
-
sql.replace(/\s+RETURNING\b[^;]*$/i, "");
|
|
10
|
-
|
|
11
|
-
const quoteReserved = (sql: string): string =>
|
|
12
|
-
sql.replace(TOKEN, (token, offset: number) => {
|
|
13
|
-
const skip = token.startsWith("$") || token.startsWith("'") || token.startsWith("\"") || token.startsWith("`");
|
|
14
|
-
const reserved = !skip && token.toLowerCase() === "key"
|
|
15
|
-
&& !/\b(?:PRIMARY|FOREIGN|UNIQUE)\s+$/i.test(sql.slice(0, offset));
|
|
16
|
-
const mixed = !skip && /[A-Z]/.test(token) && /[a-z]/.test(token);
|
|
17
|
-
return reserved || mixed ? `\`${token}\`` : token;
|
|
18
|
-
});
|
|
19
|
-
|
|
20
|
-
export const toMysql = (sql: string): string =>
|
|
21
|
-
quoteReserved(withoutReturning(sql)).replace(NAME, (_match, name: string) => `:${name}`);
|
|
22
|
-
|
|
23
|
-
export const bindParameters = (
|
|
24
|
-
parameters?: Parameter[] | null,
|
|
25
|
-
): Record<string, Scalar> => {
|
|
26
|
-
const record = parametersToRecord(parameters);
|
|
27
|
-
const bound: Record<string, Scalar> = {};
|
|
28
|
-
for (const [name, value] of Object.entries(record))
|
|
29
|
-
bound[name] = reverse(value as Cell) as Scalar;
|
|
30
|
-
return bound;
|
|
31
|
-
};
|
package/src/columnTypes.ts
DELETED
package/src/command.ts
DELETED
|
@@ -1,197 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
ArrayReader,
|
|
3
|
-
CommandMiddlewareHost,
|
|
4
|
-
FirstResultReader,
|
|
5
|
-
DatasourceError,
|
|
6
|
-
ExecuteStoredProcedureStatement,
|
|
7
|
-
Native,
|
|
8
|
-
ParameterDirection,
|
|
9
|
-
ReturnStatement,
|
|
10
|
-
SelectStatement,
|
|
11
|
-
StatementTextRenderer,
|
|
12
|
-
Response,
|
|
13
|
-
splitStatements,
|
|
14
|
-
statementParameters,
|
|
15
|
-
statementReader,
|
|
16
|
-
StreamingReader,
|
|
17
|
-
type Cells,
|
|
18
|
-
type ICommand,
|
|
19
|
-
type IReader,
|
|
20
|
-
type IStatement,
|
|
21
|
-
type Parameter,
|
|
22
|
-
} from "@deterministic-code/datasources";
|
|
23
|
-
import { bindParameters, toMysql } from "./bind.ts";
|
|
24
|
-
import type { MysqlConnection } from "./connection.ts";
|
|
25
|
-
import type { MysqlExecuteResult } from "./i-mysql-engine.ts";
|
|
26
|
-
import type { Scalar } from "./scalar.ts";
|
|
27
|
-
import { MysqlStatementRenderer } from "./MysqlStatementRenderer.ts";
|
|
28
|
-
|
|
29
|
-
const outputs = (parameters?: Parameter[]) =>
|
|
30
|
-
parameters?.filter(
|
|
31
|
-
(parameter) =>
|
|
32
|
-
parameter.direction && parameter.direction !== ParameterDirection.Input,
|
|
33
|
-
) ?? [];
|
|
34
|
-
|
|
35
|
-
export class MysqlCommand extends CommandMiddlewareHost implements ICommand {
|
|
36
|
-
private readonly statements: StatementTextRenderer;
|
|
37
|
-
|
|
38
|
-
constructor(readonly connection: MysqlConnection, statements?: StatementTextRenderer) {
|
|
39
|
-
super();
|
|
40
|
-
this.statements = statements ?? new StatementTextRenderer(t => new MysqlStatementRenderer(t));
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
async executeReaderNative(
|
|
44
|
-
text: Native,
|
|
45
|
-
parameters?: Parameter[],
|
|
46
|
-
): Promise<IReader<Cells>> {
|
|
47
|
-
return this.run(text.text, parameters, async (query, params) => {
|
|
48
|
-
if (!query.trim()) return { value: new ArrayReader([]), rows: [] };
|
|
49
|
-
this.connection.ensureOpen();
|
|
50
|
-
const statements = splitStatements(query);
|
|
51
|
-
if (statements.length === 0) return { value: new ArrayReader([]), rows: [] };
|
|
52
|
-
const bound = bindParameters(params);
|
|
53
|
-
if (statements.some((sql) => /^\s*call\b/i.test(sql))) {
|
|
54
|
-
const sets: Cells[][] = [];
|
|
55
|
-
for (const sql of statements) sets.push(...(await this.callResults(sql, bound)));
|
|
56
|
-
return FirstResultReader.capture(resultSetsReader(sets));
|
|
57
|
-
}
|
|
58
|
-
return FirstResultReader.capture(statementReader(statements, (sql) => this.query(sql, bound)));
|
|
59
|
-
});
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
async executeReaderStatement(
|
|
63
|
-
statement: IStatement,
|
|
64
|
-
parameters?: Parameter[],
|
|
65
|
-
): Promise<IReader<Cells>> {
|
|
66
|
-
return this.executeReaderNative(new Native(this.statements.render(statement)), parameters);
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
async executeStatement(statement: IStatement, parameters?: Parameter[]): Promise<Response> {
|
|
70
|
-
if (statement instanceof SelectStatement || statement instanceof ReturnStatement)
|
|
71
|
-
return this.firstCell(statement, parameters);
|
|
72
|
-
if (statement instanceof ExecuteStoredProcedureStatement && statement.name && outputs(parameters).length)
|
|
73
|
-
return this.executeProcedure(this.statements.render(statement), parameters);
|
|
74
|
-
return this.executeNative(new Native(this.statements.render(statement)), parameters);
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
private async firstCell(statement: IStatement, parameters?: Parameter[]): Promise<Response> {
|
|
78
|
-
const reader = await this.executeReaderStatement(statement, parameters);
|
|
79
|
-
try {
|
|
80
|
-
if (!(await reader.next())) return new Response(null, 0, parameters);
|
|
81
|
-
const row = reader.current;
|
|
82
|
-
/* v8 ignore next */
|
|
83
|
-
if (!row) throw new DatasourceError("Reader current must be a row");
|
|
84
|
-
const values = Object.values(row);
|
|
85
|
-
return new Response(values.length === 0 ? null : values[0], 1, parameters);
|
|
86
|
-
} finally {
|
|
87
|
-
await reader.dispose();
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
async executeNative(text: Native, parameters?: Parameter[]): Promise<Response> {
|
|
92
|
-
return this.run(text.text, parameters, async (query, params) => {
|
|
93
|
-
if (!query.trim()) return { value: new Response(undefined, 0, params), rows: [] };
|
|
94
|
-
this.connection.ensureOpen();
|
|
95
|
-
const named = bindParameters(params);
|
|
96
|
-
let rowsAffected = 0;
|
|
97
|
-
let parameters = params;
|
|
98
|
-
let result: MysqlExecuteResult["result"];
|
|
99
|
-
for (const part of splitStatements(query)) {
|
|
100
|
-
const names = new Set(statementParameters(part));
|
|
101
|
-
const used = Object.fromEntries(
|
|
102
|
-
Object.entries(named).filter(([name]) => names.has(name.replace(/^[$:@]/, ""))),
|
|
103
|
-
);
|
|
104
|
-
const executed = await this.runSql(part, used, params);
|
|
105
|
-
rowsAffected += executed.rowsAffected;
|
|
106
|
-
parameters = executed.parameters ?? params;
|
|
107
|
-
result = executed.result;
|
|
108
|
-
}
|
|
109
|
-
return {
|
|
110
|
-
value: new Response(result, rowsAffected, parameters),
|
|
111
|
-
rows: [],
|
|
112
|
-
};
|
|
113
|
-
});
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
private async executeProcedure(sql: string, parameters?: Parameter[]): Promise<Response> {
|
|
117
|
-
return this.run(sql, parameters, async (query, params) => {
|
|
118
|
-
this.connection.ensureOpen();
|
|
119
|
-
const outs = outputs(params);
|
|
120
|
-
const client = this.connection.require();
|
|
121
|
-
for (const parameter of params!) {
|
|
122
|
-
if (
|
|
123
|
-
!parameter.direction ||
|
|
124
|
-
parameter.direction === ParameterDirection.Input ||
|
|
125
|
-
parameter.direction === ParameterDirection.InputOutput
|
|
126
|
-
)
|
|
127
|
-
await client.query(`SET @${parameter.name} = :${parameter.name}`, {
|
|
128
|
-
[parameter.name]: parameter.value ?? null,
|
|
129
|
-
});
|
|
130
|
-
}
|
|
131
|
-
await client.query(toMysql(query).replace(/:([A-Za-z_][A-Za-z0-9_]*)/g, "@$1"));
|
|
132
|
-
const [rows] = await client.query(
|
|
133
|
-
`SELECT ${outs.map((parameter) => `@${parameter.name} AS \`${parameter.name}\``).join(", ")}`,
|
|
134
|
-
);
|
|
135
|
-
const row = Array.isArray(rows) ? (rows[0] as Cells | undefined) : undefined;
|
|
136
|
-
return {
|
|
137
|
-
value: new Response(
|
|
138
|
-
undefined,
|
|
139
|
-
0,
|
|
140
|
-
params?.map((parameter) =>
|
|
141
|
-
row && parameter.direction && parameter.direction !== ParameterDirection.Input
|
|
142
|
-
? { ...parameter, value: cellValue(row[parameter.name]) }
|
|
143
|
-
: parameter,
|
|
144
|
-
),
|
|
145
|
-
),
|
|
146
|
-
rows: [],
|
|
147
|
-
};
|
|
148
|
-
});
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
private async runSql(
|
|
152
|
-
sql: string,
|
|
153
|
-
params?: Record<string, Scalar>,
|
|
154
|
-
parameters?: Parameter[],
|
|
155
|
-
): Promise<MysqlExecuteResult> {
|
|
156
|
-
const [result] = await this.connection.require().query(toMysql(sql), params);
|
|
157
|
-
return Array.isArray(result)
|
|
158
|
-
? { rowsAffected: result.length, parameters }
|
|
159
|
-
: { rowsAffected: result.affectedRows ?? 0, result: null, parameters };
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
private query(sql: string, params?: Record<string, Scalar>): AsyncIterable<Cells> {
|
|
163
|
-
return this.connection.require().queryRows(toMysql(sql), params);
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
private async callResults(sql: string, params?: Record<string, Scalar>): Promise<Cells[][]> {
|
|
167
|
-
const [result] = await this.connection.require().query(toMysql(sql), params);
|
|
168
|
-
if (!Array.isArray(result)) return [[]];
|
|
169
|
-
return result.filter((item): item is Cells[] => Array.isArray(item));
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
const cellValue = (cell: Scalar | object | undefined): Scalar => {
|
|
174
|
-
if (cell === null || cell === undefined) return null;
|
|
175
|
-
if (typeof cell === "string" || typeof cell === "number" || typeof cell === "boolean" || typeof cell === "bigint")
|
|
176
|
-
return cell;
|
|
177
|
-
if (cell instanceof Uint8Array) return new TextDecoder().decode(cell);
|
|
178
|
-
return JSON.stringify(cell);
|
|
179
|
-
};
|
|
180
|
-
|
|
181
|
-
const resultSetsReader = (sets: Cells[][]): StreamingReader => {
|
|
182
|
-
let set = 0;
|
|
183
|
-
let row = 0;
|
|
184
|
-
return new StreamingReader(
|
|
185
|
-
async () => {
|
|
186
|
-
const current = sets[set]?.[row];
|
|
187
|
-
if (current === undefined) return undefined;
|
|
188
|
-
row += 1;
|
|
189
|
-
return current;
|
|
190
|
-
},
|
|
191
|
-
async () => {
|
|
192
|
-
set += 1;
|
|
193
|
-
row = 0;
|
|
194
|
-
return set < sets.length;
|
|
195
|
-
},
|
|
196
|
-
);
|
|
197
|
-
};
|