@naturalcycles/mysql-lib 4.11.0 → 4.12.1

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.
@@ -45,7 +45,7 @@ export declare class MysqlDB extends BaseCommonDB implements CommonDB {
45
45
  * Be careful to manage this connection yourself (open, release, etc).
46
46
  */
47
47
  createSingleConnection(): Promise<Connection>;
48
- getByIds<ROW extends ObjectWithId>(table: string, ids: string[], opt?: MysqlDBOptions): Promise<ROW[]>;
48
+ getByIds<ROW extends ObjectWithId>(table: string, ids: readonly string[], opt?: MysqlDBOptions): Promise<ROW[]>;
49
49
  runQuery<ROW extends ObjectWithId>(q: DBQuery<ROW>, _opt?: MysqlDBOptions): Promise<RunQueryResult<ROW>>;
50
50
  runSQL<RESULT>(q: QueryOptions): Promise<RESULT>;
51
51
  /**
@@ -55,11 +55,11 @@ export declare class MysqlDB extends BaseCommonDB implements CommonDB {
55
55
  runSQLString(s: string): Promise<void>;
56
56
  runQueryCount<ROW extends ObjectWithId>(q: DBQuery<ROW>, _opt?: CommonDBOptions): Promise<number>;
57
57
  streamQuery<ROW extends ObjectWithId>(q: DBQuery<ROW>, _opt?: MysqlDBOptions): Pipeline<ROW>;
58
- saveBatch<ROW extends ObjectWithId>(table: string, rowsInput: ROW[], opt?: MysqlDBSaveOptions<ROW>): Promise<void>;
58
+ saveBatch<ROW extends ObjectWithId>(table: string, rowsInput: readonly ROW[], opt?: MysqlDBSaveOptions<ROW>): Promise<void>;
59
59
  /**
60
60
  * Limitation: always returns [], regardless of which rows are actually deleted
61
61
  */
62
- deleteByIds(table: string, ids: string[], _opt?: MysqlDBOptions): Promise<number>;
62
+ deleteByIds(table: string, ids: readonly string[], _opt?: MysqlDBOptions): Promise<number>;
63
63
  deleteByQuery<ROW extends ObjectWithId>(q: DBQuery<ROW>, _opt?: CommonDBOptions): Promise<number>;
64
64
  /**
65
65
  * Use with caution!
@@ -11,18 +11,18 @@ export declare class MySQLKeyValueDB implements CommonKeyValueDB {
11
11
  ping(): Promise<void>;
12
12
  close(): Promise<void>;
13
13
  createTable(table: string, opt?: CommonDBCreateOptions): Promise<void>;
14
- getByIds(table: string, ids: string[]): Promise<KeyValueDBTuple[]>;
14
+ getByIds(table: string, ids: readonly string[]): Promise<KeyValueDBTuple[]>;
15
15
  /**
16
16
  * Use with caution!
17
17
  */
18
18
  dropTable(table: string): Promise<void>;
19
- deleteByIds(table: string, ids: string[]): Promise<void>;
20
- saveBatch(table: string, entries: KeyValueDBTuple[]): Promise<void>;
19
+ deleteByIds(table: string, ids: readonly string[]): Promise<void>;
20
+ saveBatch(table: string, entries: readonly KeyValueDBTuple[]): Promise<void>;
21
21
  streamIds(table: string, limit?: number): Pipeline<string>;
22
22
  streamValues(table: string, limit?: number): Pipeline<Buffer>;
23
23
  streamEntries(table: string, limit?: number): Pipeline<KeyValueDBTuple>;
24
24
  beginTransaction(): Promise<void>;
25
25
  endTransaction(): Promise<void>;
26
26
  count(table: string): Promise<number>;
27
- incrementBatch(_table: string, _entries: IncrementTuple[]): Promise<IncrementTuple[]>;
27
+ incrementBatch(_table: string, _entries: readonly IncrementTuple[]): Promise<IncrementTuple[]>;
28
28
  }
@@ -13,7 +13,7 @@ export declare function dbQueryToSQLDelete(q: DBQuery<any>): string | null;
13
13
  /**
14
14
  * Returns array of sql statements to respect the max sql size.
15
15
  */
16
- export declare function insertSQL(table: string, rows: Record<any, any>[], verb?: 'INSERT' | 'REPLACE', logger?: CommonLogger): string[];
16
+ export declare function insertSQL(table: string, rows: readonly Record<any, any>[], verb?: 'INSERT' | 'REPLACE', logger?: CommonLogger): string[];
17
17
  export declare function insertSQLSingle(table: string, record: Record<any, any>): string;
18
18
  export declare function insertSQLSetSingle(table: string, record: Record<any, any>): QueryOptions;
19
19
  export declare function dbQueryToSQLUpdate(q: DBQuery<any>, patch: Record<any, any>): string | null;
@@ -58,7 +58,7 @@ export function insertSQL(table, rows, verb = 'INSERT', logger = consoleLogger)
58
58
  `VALUES\n`,
59
59
  ].join(' ');
60
60
  const valueRows = rows.map(rec => {
61
- return `(` + fields.map(k => mysql.escape(rec[k])).join(',') + `)`;
61
+ return `(` + fields.map(k => mysql.escape(mapValueToMySQL(rec[k]))).join(',') + `)`;
62
62
  });
63
63
  const full = start + valueRows.join(',\n');
64
64
  if (full.length < MAX_PACKET_SIZE)
@@ -126,7 +126,22 @@ export function dbQueryToSQLUpdate(q, patch) {
126
126
  .join(', '),
127
127
  ...whereTokens,
128
128
  ];
129
- return mysql.format(tokens.join(' '), Object.values(patch));
129
+ return mysql.format(tokens.join(' '), Object.values(patch).map(v => mapValueToMySQL(v)));
130
+ }
131
+ /**
132
+ * Objects and arrays are stored as JSON, as mysql.escape would turn an object into `key = value`
133
+ * pairs and an array into a list of values. Buffer, Date and raw SQL (toSqlString) are left to
134
+ * mysql.escape.
135
+ */
136
+ function mapValueToMySQL(v) {
137
+ if (v &&
138
+ typeof v === 'object' &&
139
+ !Buffer.isBuffer(v) &&
140
+ !(v instanceof Date) &&
141
+ typeof v.toSqlString !== 'function') {
142
+ return JSON.stringify(v);
143
+ }
144
+ return v;
130
145
  }
131
146
  function selectTokens(q) {
132
147
  let fields = ['*'];
@@ -16,7 +16,7 @@ export interface MySQLSchemaOptions {
16
16
  * It currently skips nullability and declares everything as "DEFAULT NULL".
17
17
  */
18
18
  export declare function jsonSchemaToMySQLDDL(table: string, schema: JsonSchema<any>, opt?: MySQLSchemaOptions): string;
19
- export declare function mysqlTableStatsToJsonSchemaField<T extends AnyObject = any>(table: string, stats: MySQLTableStats[], logger: CommonLogger): JsonSchema<T>;
19
+ export declare function mysqlTableStatsToJsonSchemaField<T extends AnyObject = any>(table: string, stats: readonly MySQLTableStats[], logger: CommonLogger): JsonSchema<T>;
20
20
  /**
21
21
  * Because MySQL doesn't support `.` in field names and escapes them as tableName + fieldName.
22
22
  *
package/package.json CHANGED
@@ -10,7 +10,7 @@
10
10
  "tslib": "^2"
11
11
  },
12
12
  "devDependencies": {
13
- "@naturalcycles/dev-lib": "20.66.0",
13
+ "@naturalcycles/dev-lib": "0.0.0",
14
14
  "@types/node": "^26",
15
15
  "typescript": "^7"
16
16
  },
@@ -38,7 +38,7 @@
38
38
  "engines": {
39
39
  "node": ">=26.12.1"
40
40
  },
41
- "version": "4.11.0",
41
+ "version": "4.12.1",
42
42
  "description": "MySQL client implementing CommonDB interface",
43
43
  "keywords": [
44
44
  "mysql",
package/src/mysql.db.ts CHANGED
@@ -192,7 +192,7 @@ export class MysqlDB extends BaseCommonDB implements CommonDB {
192
192
  // GET
193
193
  override async getByIds<ROW extends ObjectWithId>(
194
194
  table: string,
195
- ids: string[],
195
+ ids: readonly string[],
196
196
  opt: MysqlDBOptions = {},
197
197
  ): Promise<ROW[]> {
198
198
  if (!ids.length) return []
@@ -291,7 +291,7 @@ export class MysqlDB extends BaseCommonDB implements CommonDB {
291
291
  // SAVE
292
292
  override async saveBatch<ROW extends ObjectWithId>(
293
293
  table: string,
294
- rowsInput: ROW[],
294
+ rowsInput: readonly ROW[],
295
295
  opt: MysqlDBSaveOptions<ROW> = {},
296
296
  ): Promise<void> {
297
297
  if (!rowsInput.length) return
@@ -358,7 +358,11 @@ export class MysqlDB extends BaseCommonDB implements CommonDB {
358
358
  /**
359
359
  * Limitation: always returns [], regardless of which rows are actually deleted
360
360
  */
361
- override async deleteByIds(table: string, ids: string[], _opt?: MysqlDBOptions): Promise<number> {
361
+ override async deleteByIds(
362
+ table: string,
363
+ ids: readonly string[],
364
+ _opt?: MysqlDBOptions,
365
+ ): Promise<number> {
362
366
  if (!ids.length) return 0
363
367
  const sql = dbQueryToSQLDelete(new DBQuery(table).filterEq('id', ids))
364
368
  if (!sql) return 0
@@ -45,7 +45,7 @@ export class MySQLKeyValueDB implements CommonKeyValueDB {
45
45
  await this.db.runSQL({ sql })
46
46
  }
47
47
 
48
- async getByIds(table: string, ids: string[]): Promise<KeyValueDBTuple[]> {
48
+ async getByIds(table: string, ids: readonly string[]): Promise<KeyValueDBTuple[]> {
49
49
  if (!ids.length) return []
50
50
 
51
51
  const sql = `SELECT id,v FROM ${table} where id in (${ids.map(id => `"${id}"`).join(',')})`
@@ -62,13 +62,13 @@ export class MySQLKeyValueDB implements CommonKeyValueDB {
62
62
  await this.db.runSQL({ sql: `DROP TABLE IF EXISTS ${table}` })
63
63
  }
64
64
 
65
- async deleteByIds(table: string, ids: string[]): Promise<void> {
65
+ async deleteByIds(table: string, ids: readonly string[]): Promise<void> {
66
66
  const sql = `DELETE FROM ${table} WHERE id in (${ids.map(id => `"${id}"`).join(',')})`
67
67
  if (this.cfg.logSQL) this.db.cfg.logger.log(sql)
68
68
  await this.db.runSQL({ sql })
69
69
  }
70
70
 
71
- async saveBatch(table: string, entries: KeyValueDBTuple[]): Promise<void> {
71
+ async saveBatch(table: string, entries: readonly KeyValueDBTuple[]): Promise<void> {
72
72
  const statements: QueryOptions[] = entries.map(([id, buf]) => {
73
73
  return {
74
74
  sql: `INSERT INTO ${table} (id, v) VALUES (?, ?)`,
@@ -126,7 +126,10 @@ export class MySQLKeyValueDB implements CommonKeyValueDB {
126
126
  return rows[0]!.cnt
127
127
  }
128
128
 
129
- async incrementBatch(_table: string, _entries: IncrementTuple[]): Promise<IncrementTuple[]> {
129
+ async incrementBatch(
130
+ _table: string,
131
+ _entries: readonly IncrementTuple[],
132
+ ): Promise<IncrementTuple[]> {
130
133
  throw new AppError('MySQLKeyValueDB.incrementBatch() is not implemented')
131
134
  }
132
135
  }
package/src/query.util.ts CHANGED
@@ -54,7 +54,7 @@ export function dbQueryToSQLDelete(q: DBQuery<any>): string | null {
54
54
  */
55
55
  export function insertSQL(
56
56
  table: string,
57
- rows: Record<any, any>[],
57
+ rows: readonly Record<any, any>[],
58
58
  verb: 'INSERT' | 'REPLACE' = 'INSERT',
59
59
  logger: CommonLogger = consoleLogger,
60
60
  ): string[] {
@@ -79,7 +79,7 @@ export function insertSQL(
79
79
  ].join(' ')
80
80
 
81
81
  const valueRows = rows.map(rec => {
82
- return `(` + fields.map(k => mysql.escape(rec[k])).join(',') + `)`
82
+ return `(` + fields.map(k => mysql.escape(mapValueToMySQL(rec[k]))).join(',') + `)`
83
83
  })
84
84
 
85
85
  const full = start + valueRows.join(',\n')
@@ -162,7 +162,28 @@ export function dbQueryToSQLUpdate(q: DBQuery<any>, patch: Record<any, any>): st
162
162
  ...whereTokens,
163
163
  ]
164
164
 
165
- return mysql.format(tokens.join(' '), Object.values(patch))
165
+ return mysql.format(
166
+ tokens.join(' '),
167
+ Object.values(patch).map(v => mapValueToMySQL(v)),
168
+ )
169
+ }
170
+
171
+ /**
172
+ * Objects and arrays are stored as JSON, as mysql.escape would turn an object into `key = value`
173
+ * pairs and an array into a list of values. Buffer, Date and raw SQL (toSqlString) are left to
174
+ * mysql.escape.
175
+ */
176
+ function mapValueToMySQL(v: any): any {
177
+ if (
178
+ v &&
179
+ typeof v === 'object' &&
180
+ !Buffer.isBuffer(v) &&
181
+ !(v instanceof Date) &&
182
+ typeof v.toSqlString !== 'function'
183
+ ) {
184
+ return JSON.stringify(v)
185
+ }
186
+ return v
166
187
  }
167
188
 
168
189
  function selectTokens(q: DBQuery<any>): string[] {
@@ -76,7 +76,7 @@ export function jsonSchemaToMySQLDDL(
76
76
 
77
77
  export function mysqlTableStatsToJsonSchemaField<T extends AnyObject = any>(
78
78
  table: string,
79
- stats: MySQLTableStats[],
79
+ stats: readonly MySQLTableStats[],
80
80
  logger: CommonLogger,
81
81
  ): JsonSchema<T> {
82
82
  const s: JsonSchema<T> = {