@atscript/db-mysql 0.1.39 → 0.1.40

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/index.d.ts DELETED
@@ -1,271 +0,0 @@
1
- import { BaseDbAdapter, TDbDefaultFn, TExistingTableOption, TTableOptionDiff, TDbFieldMeta, TValueFormatterPair, TDbInsertResult, TDbInsertManyResult, DbQuery, FilterExpr, TDbUpdateResult, TDbDeleteResult, TExistingColumn, TColumnDiff, TSyncColumnResult, TSearchIndexInfo, DbSpace } from '@atscript/db';
2
- import { TAtscriptAnnotatedType, TMetadataMap } from '@atscript/typescript/utils';
3
- import * as mysql2_promise from 'mysql2/promise';
4
- import { TAtscriptPlugin } from '@atscript/core';
5
- import { FilterExpr as FilterExpr$1 } from '@uniqu/core';
6
- import { TSqlFragment } from '@atscript/db-sql-tools';
7
- export { TSqlFragment } from '@atscript/db-sql-tools';
8
-
9
- /**
10
- * Result of a MySQL statement that modifies data (INSERT, UPDATE, DELETE).
11
- */
12
- interface TMysqlRunResult {
13
- /** Number of rows affected by the statement. */
14
- affectedRows: number;
15
- /** Auto-generated ID from last INSERT (0 if not applicable). */
16
- insertId: number | bigint;
17
- /** Number of rows changed by an UPDATE (differs from affectedRows when row matches but value unchanged). */
18
- changedRows: number;
19
- }
20
- /**
21
- * Async driver interface for MySQL engines.
22
- *
23
- * Unlike SQLite's synchronous driver, MySQL is network-based
24
- * and requires async operations throughout.
25
- *
26
- * The driver has two modes of operation:
27
- * 1. **Pool mode** (default) — each call acquires/releases a connection automatically
28
- * 2. **Connection mode** (for transactions) — a dedicated connection is acquired
29
- * and all operations run on it until released
30
- *
31
- * Implementations: {@link Mysql2Driver}
32
- */
33
- interface TMysqlDriver {
34
- /**
35
- * Execute a SQL statement that modifies data (INSERT, UPDATE, DELETE, DDL).
36
- * Uses parameterized queries (`?` placeholders).
37
- */
38
- run(sql: string, params?: unknown[]): Promise<TMysqlRunResult>;
39
- /**
40
- * Execute a query and return all matching rows.
41
- */
42
- all<T = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<T[]>;
43
- /**
44
- * Execute a query and return the first matching row, or null.
45
- */
46
- get<T = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<T | null>;
47
- /**
48
- * Execute raw SQL without returning results.
49
- * Used for DDL, SET statements, multi-statement strings, etc.
50
- */
51
- exec(sql: string): Promise<void>;
52
- /**
53
- * Acquire a dedicated connection for transaction use.
54
- * Returns a {@link TMysqlConnection} that must be released after use.
55
- */
56
- getConnection(): Promise<TMysqlConnection>;
57
- /**
58
- * Close the pool / end all connections.
59
- */
60
- close(): Promise<void>;
61
- }
62
- /**
63
- * A dedicated connection acquired from the pool.
64
- * Used for transactions where all operations must run on the same connection.
65
- */
66
- interface TMysqlConnection {
67
- /** Execute a statement that modifies data. */
68
- run(sql: string, params?: unknown[]): Promise<TMysqlRunResult>;
69
- /** Execute a query and return all matching rows. */
70
- all<T = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<T[]>;
71
- /** Execute a query and return the first matching row, or null. */
72
- get<T = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<T | null>;
73
- /** Execute raw SQL without returning results. */
74
- exec(sql: string): Promise<void>;
75
- /** Release this connection back to the pool. */
76
- release(): void;
77
- }
78
-
79
- /**
80
- * MySQL adapter for {@link AtscriptDbTable}.
81
- *
82
- * Accepts any {@link TMysqlDriver} implementation — the actual MySQL driver
83
- * is fully swappable (mysql2/promise pool, custom implementations, etc.).
84
- *
85
- * Usage:
86
- * ```typescript
87
- * import { Mysql2Driver, MysqlAdapter } from '@atscript/db-mysql'
88
- * import { DbSpace } from '@atscript/db'
89
- *
90
- * const driver = new Mysql2Driver('mysql://root@localhost:3306/mydb')
91
- * const space = new DbSpace(() => new MysqlAdapter(driver))
92
- * const users = space.getTable(UsersType)
93
- * ```
94
- */
95
- declare class MysqlAdapter extends BaseDbAdapter {
96
- protected readonly driver: TMysqlDriver;
97
- supportsColumnModify: boolean;
98
- private static readonly NATIVE_DEFAULT_FNS;
99
- private _engine;
100
- private _charset;
101
- private _collation;
102
- private _autoIncrementStart?;
103
- private _incrementFields;
104
- private _onUpdateFields;
105
- /** Whether the connected MySQL instance supports native VECTOR type (MySQL 9.0+). */
106
- private _supportsVector;
107
- /** Vector fields: physical field name → { dimensions, similarity, indexName }. */
108
- private _vectorFields;
109
- /** Default similarity thresholds per vector field (from @db.search.vector.threshold). */
110
- private _vectorThresholds;
111
- /** Schema name for INFORMATION_SCHEMA queries (null falls through to DATABASE()). */
112
- private get _schema();
113
- constructor(driver: TMysqlDriver);
114
- protected _beginTransaction(): Promise<TMysqlConnection>;
115
- protected _commitTransaction(state: unknown): Promise<void>;
116
- protected _rollbackTransaction(state: unknown): Promise<void>;
117
- /**
118
- * Returns the active executor: dedicated connection if inside a transaction,
119
- * otherwise the pool-based driver.
120
- */
121
- private _exec;
122
- /** MySQL InnoDB enforces FK constraints natively. */
123
- supportsNativeForeignKeys(): boolean;
124
- prepareId(id: unknown, _fieldType: TAtscriptAnnotatedType): unknown;
125
- supportsNativeValueDefaults(): boolean;
126
- nativeDefaultFns(): ReadonlySet<TDbDefaultFn>;
127
- onBeforeFlatten(type: TAtscriptAnnotatedType): void;
128
- onFieldScanned(field: string, _type: TAtscriptAnnotatedType, metadata: TMetadataMap<AtscriptMetadata>): void;
129
- getDesiredTableOptions(): TExistingTableOption[];
130
- getExistingTableOptions(): Promise<TExistingTableOption[]>;
131
- applyTableOptions(changes: TTableOptionDiff['changed']): Promise<void>;
132
- /**
133
- * Returns a value formatter for TIMESTAMP-mapped fields.
134
- * Number fields with @db.default.now map to MySQL TIMESTAMP — the formatter
135
- * converts epoch ms to a UTC datetime string for the wire protocol.
136
- */
137
- formatValue(field: TDbFieldMeta): TValueFormatterPair | ((value: unknown) => unknown) | undefined;
138
- /**
139
- * Wraps an async write operation to catch MySQL constraint errors
140
- * and rethrow as structured `DbError`.
141
- *
142
- * MySQL uses numeric error codes:
143
- * - 1062 = ER_DUP_ENTRY (unique constraint violation)
144
- * - 1451 = ER_ROW_IS_REFERENCED_2 (FK violation on delete)
145
- * - 1452 = ER_NO_REFERENCED_ROW_2 (FK violation on insert/update)
146
- */
147
- private _wrapConstraintError;
148
- private _mapFkError;
149
- insertOne(data: Record<string, unknown>): Promise<TDbInsertResult>;
150
- insertMany(data: Array<Record<string, unknown>>): Promise<TDbInsertManyResult>;
151
- findOne(query: DbQuery): Promise<Record<string, unknown> | null>;
152
- findMany(query: DbQuery): Promise<Array<Record<string, unknown>>>;
153
- count(query: DbQuery): Promise<number>;
154
- aggregate(query: DbQuery): Promise<Array<Record<string, unknown>>>;
155
- updateOne(filter: FilterExpr, data: Record<string, unknown>): Promise<TDbUpdateResult>;
156
- updateMany(filter: FilterExpr, data: Record<string, unknown>): Promise<TDbUpdateResult>;
157
- replaceOne(filter: FilterExpr, data: Record<string, unknown>): Promise<TDbUpdateResult>;
158
- replaceMany(filter: FilterExpr, data: Record<string, unknown>): Promise<TDbUpdateResult>;
159
- deleteOne(filter: FilterExpr): Promise<TDbDeleteResult>;
160
- deleteMany(filter: FilterExpr): Promise<TDbDeleteResult>;
161
- ensureTable(): Promise<void>;
162
- private _ensureView;
163
- getExistingColumns(): Promise<TExistingColumn[]>;
164
- getExistingColumnsForTable(tableName: string): Promise<TExistingColumn[]>;
165
- syncColumns(diff: TColumnDiff): Promise<TSyncColumnResult>;
166
- recreateTable(): Promise<void>;
167
- dropTable(): Promise<void>;
168
- dropColumns(columns: string[]): Promise<void>;
169
- dropTableByName(tableName: string): Promise<void>;
170
- dropViewByName(viewName: string): Promise<void>;
171
- renameTable(oldName: string): Promise<void>;
172
- typeMapper(field: TDbFieldMeta): string;
173
- syncIndexes(): Promise<void>;
174
- syncForeignKeys(): Promise<void>;
175
- dropForeignKeys(fkFieldKeys: string[]): Promise<void>;
176
- /** Queries INFORMATION_SCHEMA for existing FK constraints, grouped by constraint name → column names. */
177
- private _getExistingFkConstraints;
178
- getSearchIndexes(): TSearchIndexInfo[];
179
- search(text: string, query: DbQuery, indexName?: string): Promise<Array<Record<string, unknown>>>;
180
- searchWithCount(text: string, query: DbQuery, indexName?: string): Promise<{
181
- data: Array<Record<string, unknown>>;
182
- count: number;
183
- }>;
184
- private _buildSearchWhere;
185
- private _getFulltextIndex;
186
- /**
187
- * Detects native VECTOR type support by inspecting the server version.
188
- * MySQL 9.0+ supports the VECTOR column type natively.
189
- * Caches the result for the lifetime of this adapter instance.
190
- */
191
- private _detectVectorSupport;
192
- isVectorSearchable(): boolean;
193
- vectorSearch(vector: number[], query: DbQuery, indexName?: string): Promise<Array<Record<string, unknown>>>;
194
- vectorSearchWithCount(vector: number[], query: DbQuery, indexName?: string): Promise<{
195
- data: Array<Record<string, unknown>>;
196
- count: number;
197
- }>;
198
- /** Resolves vector field and computes shared context for vector search SQL builders. */
199
- private _prepareVectorSearch;
200
- private _buildVectorSearchQuery;
201
- private _buildVectorSearchCountQuery;
202
- /** Resolves threshold: query-time $threshold > schema-level @db.search.vector.threshold. */
203
- private _resolveVectorThreshold;
204
- }
205
-
206
- /**
207
- * {@link TMysqlDriver} implementation backed by `mysql2/promise`.
208
- *
209
- * Accepts a connection URI string, a `PoolOptions` object, or a pre-created
210
- * `Pool` instance from `mysql2/promise`.
211
- *
212
- * ```typescript
213
- * import { Mysql2Driver } from '@atscript/db-mysql'
214
- *
215
- * // Connection URI
216
- * const driver = new Mysql2Driver('mysql://root:pass@localhost:3306/mydb')
217
- *
218
- * // Pool options
219
- * const driver = new Mysql2Driver({
220
- * host: 'localhost',
221
- * user: 'root',
222
- * database: 'mydb',
223
- * waitForConnections: true,
224
- * connectionLimit: 10,
225
- * })
226
- *
227
- * // Pre-created pool
228
- * import mysql from 'mysql2/promise'
229
- * const pool = mysql.createPool({ host: 'localhost', database: 'mydb' })
230
- * const driver = new Mysql2Driver(pool)
231
- * ```
232
- *
233
- * Requires `mysql2` to be installed:
234
- * ```bash
235
- * pnpm add mysql2
236
- * ```
237
- */
238
- declare class Mysql2Driver implements TMysqlDriver {
239
- private pool;
240
- private poolInit;
241
- constructor(poolOrConfig: string | mysql2_promise.Pool | mysql2_promise.PoolOptions);
242
- private getPool;
243
- run(sql: string, params?: unknown[]): Promise<TMysqlRunResult>;
244
- all<T = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<T[]>;
245
- get<T = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<T | null>;
246
- exec(sql: string): Promise<void>;
247
- getConnection(): Promise<TMysqlConnection>;
248
- close(): Promise<void>;
249
- }
250
-
251
- declare const MysqlPlugin: () => TAtscriptPlugin;
252
-
253
- /**
254
- * Translates a uniqu filter expression into a parameterized MySQL WHERE clause.
255
- *
256
- * @returns `{ sql, params }` — the WHERE clause (without "WHERE") and bound params.
257
- * Returns `{ sql: '1=1', params: [] }` for empty/null filters.
258
- */
259
- declare function buildWhere(filter: FilterExpr$1): TSqlFragment;
260
-
261
- /**
262
- * Creates a {@link DbSpace} backed by a MySQL connection pool.
263
- *
264
- * @param uri - MySQL connection URI (e.g., `mysql://root@localhost:3306/mydb`)
265
- * @param options - Additional pool options passed to mysql2.
266
- * @returns A `DbSpace` that creates `MysqlAdapter` instances per table.
267
- */
268
- declare function createAdapter(uri: string, options?: Record<string, unknown>): DbSpace;
269
-
270
- export { Mysql2Driver, MysqlAdapter, MysqlPlugin, buildWhere, createAdapter };
271
- export type { TMysqlConnection, TMysqlDriver, TMysqlRunResult };
package/dist/plugin.d.ts DELETED
@@ -1,5 +0,0 @@
1
- import { TAtscriptPlugin } from '@atscript/core';
2
-
3
- declare const MysqlPlugin: () => TAtscriptPlugin;
4
-
5
- export { MysqlPlugin };