@nymphjs/driver-mysql 1.0.0-beta.14 → 1.0.0-beta.141

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.
@@ -1,21 +1,30 @@
1
- import cp from 'child_process';
2
- // @ts-ignore: types are wonky with @vlasky/mysql.
3
- import { default as MySQLType } from '@types/mysql';
4
- // @ts-ignore: replace with mysql once https://github.com/mysqljs/mysql/pull/2233 is merged.
5
- import vlaskyMysql from '@vlasky/mysql';
1
+ import { Pool, PoolOptions, PoolConnection } from 'mysql2';
2
+ import mysql from 'mysql2';
3
+ import SqlString from 'sqlstring';
4
+ import type {
5
+ SearchTerm,
6
+ SearchOrTerm,
7
+ SearchNotTerm,
8
+ SearchSeriesTerm,
9
+ } from '@sciactive/tokenizer';
6
10
  import {
7
11
  NymphDriver,
8
- EntityConstructor,
9
- EntityData,
10
- EntityInterface,
11
- SerializedEntityData,
12
+ type EntityConstructor,
13
+ type EntityData,
14
+ type EntityObjectType,
15
+ type EntityInterface,
16
+ type EntityInstanceType,
17
+ type SerializedEntityData,
18
+ type FormattedSelector,
19
+ type Options,
20
+ type Selector,
21
+ EntityConflictError,
22
+ EntityInvalidDataError,
23
+ EntityUniqueConstraintError,
12
24
  InvalidParametersError,
13
25
  NotConfiguredError,
14
26
  QueryFailedError,
15
27
  UnableToConnectError,
16
- FormattedSelector,
17
- Options,
18
- Selector,
19
28
  xor,
20
29
  } from '@nymphjs/nymph';
21
30
  import { makeTableSuffix } from '@nymphjs/guid';
@@ -23,39 +32,59 @@ import { makeTableSuffix } from '@nymphjs/guid';
23
32
  import {
24
33
  MySQLDriverConfig,
25
34
  MySQLDriverConfigDefaults as defaults,
26
- } from './conf';
35
+ } from './conf/index.js';
27
36
 
28
37
  type MySQLDriverTransaction = {
29
- connection: MySQLType.PoolConnection | null;
38
+ connection: PoolConnection | null;
30
39
  count: number;
40
+ latestPromise: Promise<any>;
31
41
  };
32
42
 
33
- const mysql = vlaskyMysql as typeof MySQLType;
34
-
35
43
  /**
36
44
  * The MySQL Nymph database driver.
37
45
  */
38
46
  export default class MySQLDriver extends NymphDriver {
39
47
  public config: MySQLDriverConfig;
40
- private mysqlConfig: MySQLType.PoolConfig;
48
+ private mysqlConfig: PoolOptions;
41
49
  protected prefix: string;
42
50
  protected connected: boolean = false;
43
51
  // @ts-ignore: this is assigned in connect(), which is called by the constructor.
44
- protected link: MySQLType.Pool;
52
+ protected link: Pool;
45
53
  protected transaction: MySQLDriverTransaction | null = null;
46
54
 
47
55
  static escape(input: string) {
48
- return mysql.escapeId(input);
56
+ return SqlString.escapeId(input, true);
49
57
  }
50
58
 
51
59
  static escapeValue(input: string) {
52
60
  return mysql.escape(input);
53
61
  }
54
62
 
63
+ static escapeTags(tags: string[]) {
64
+ return tags.map(MySQLDriver.escapeTag);
65
+ }
66
+
67
+ static escapeTag(tag: string) {
68
+ return tag
69
+ .replace(/\\/g, () => '\\\\')
70
+ .replace(/_/g, () => '\\_')
71
+ .replace(/ /g, () => '_');
72
+ }
73
+
74
+ static unescapeTags(tags: string[]) {
75
+ return tags.map(MySQLDriver.unescapeTag);
76
+ }
77
+
78
+ static unescapeTag(tag: string) {
79
+ return tag.replace(/\\([\\_])|_/g, (_, char) =>
80
+ char != null ? char : ' ',
81
+ );
82
+ }
83
+
55
84
  constructor(
56
85
  config: Partial<MySQLDriverConfig>,
57
- link?: MySQLType.Pool,
58
- transaction?: MySQLDriverTransaction
86
+ link?: Pool,
87
+ transaction?: MySQLDriverTransaction,
59
88
  ) {
60
89
  super();
61
90
  this.config = { ...defaults, ...config };
@@ -90,16 +119,16 @@ export default class MySQLDriver extends NymphDriver {
90
119
  return new MySQLDriver(
91
120
  this.config,
92
121
  this.link,
93
- this.transaction ?? undefined
122
+ this.transaction ?? undefined,
94
123
  );
95
124
  }
96
125
 
97
- private getConnection(): Promise<MySQLType.PoolConnection> {
126
+ private getConnection(): Promise<PoolConnection> {
98
127
  if (this.transaction != null && this.transaction.connection != null) {
99
128
  return Promise.resolve(this.transaction.connection);
100
129
  }
101
130
  return new Promise((resolve, reject) =>
102
- this.link.getConnection((err, con) => (err ? reject(err) : resolve(con)))
131
+ this.link.getConnection((err, con) => (err ? reject(err) : resolve(con))),
103
132
  );
104
133
  }
105
134
 
@@ -112,16 +141,11 @@ export default class MySQLDriver extends NymphDriver {
112
141
  // If we think we're connected, try pinging the server.
113
142
  try {
114
143
  if (this.connected) {
115
- const connection: MySQLType.PoolConnection = await new Promise(
144
+ const connection: PoolConnection = await new Promise(
116
145
  (resolve, reject) =>
117
146
  this.link.getConnection((err, con) =>
118
- err ? reject(err) : resolve(con)
119
- )
120
- );
121
- await new Promise((resolve) =>
122
- connection.ping(() => {
123
- resolve(0);
124
- })
147
+ err ? reject(err) : resolve(con),
148
+ ),
125
149
  );
126
150
  connection.release();
127
151
  }
@@ -132,7 +156,10 @@ export default class MySQLDriver extends NymphDriver {
132
156
  // Connecting, selecting database
133
157
  if (!this.connected) {
134
158
  try {
135
- this.link = mysql.createPool(this.mysqlConfig);
159
+ this.link = mysql.createPool({
160
+ ...this.mysqlConfig,
161
+ charset: 'utf8mb4_bin',
162
+ });
136
163
  this.connected = true;
137
164
  } catch (e: any) {
138
165
  if (
@@ -142,7 +169,7 @@ export default class MySQLDriver extends NymphDriver {
142
169
  this.mysqlConfig.database === 'nymph'
143
170
  ) {
144
171
  throw new NotConfiguredError(
145
- "It seems the config hasn't been set up correctly."
172
+ "It seems the config hasn't been set up correctly.",
146
173
  );
147
174
  } else {
148
175
  throw new UnableToConnectError('Could not connect: ' + e?.message);
@@ -166,6 +193,9 @@ export default class MySQLDriver extends NymphDriver {
166
193
  }
167
194
 
168
195
  public async inTransaction() {
196
+ if (this.transaction && this.transaction.count === 0) {
197
+ this.transaction = null;
198
+ }
169
199
  return !!this.transaction;
170
200
  }
171
201
 
@@ -178,106 +208,271 @@ export default class MySQLDriver extends NymphDriver {
178
208
  return this.connected;
179
209
  }
180
210
 
181
- /**
182
- * Create entity tables in the database.
183
- *
184
- * @param etype The entity type to create a table for. If this is blank, the default tables are created.
185
- * @returns True on success, false on failure.
186
- */
187
- private createTables(etype: string | null = null) {
188
- this.queryRunSync('SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";');
189
- let foreignKeyDataTableGuid = '';
190
- let foreignKeyDataComparisonsTableGuid = '';
191
- let foreignKeyReferencesTableGuid = '';
192
- if (this.config.foreignKeys) {
193
- foreignKeyDataTableGuid = ` REFERENCES ${MySQLDriver.escape(
194
- `${this.prefix}entities_${etype}`
195
- )}(\`guid\`) ON DELETE CASCADE`;
196
- foreignKeyDataComparisonsTableGuid = ` REFERENCES ${MySQLDriver.escape(
197
- `${this.prefix}entities_${etype}`
198
- )}(\`guid\`) ON DELETE CASCADE`;
199
- foreignKeyReferencesTableGuid = ` REFERENCES ${MySQLDriver.escape(
200
- `${this.prefix}entities_${etype}`
201
- )}(\`guid\`) ON DELETE CASCADE`;
202
- }
203
- if (etype != null) {
204
- // Create the entity table.
205
- this.queryRunSync(
206
- `CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(
207
- `${this.prefix}entities_${etype}`
208
- )} (
211
+ private async createEntitiesTable(etype: string) {
212
+ // Create the entity table.
213
+ await this.queryRun(
214
+ `CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(
215
+ `${this.prefix}entities_${etype}`,
216
+ )} (
209
217
  \`guid\` BINARY(12) NOT NULL,
210
218
  \`tags\` LONGTEXT,
211
219
  \`cdate\` DOUBLE PRECISION NOT NULL,
212
220
  \`mdate\` DOUBLE PRECISION NOT NULL,
221
+ \`user\` BINARY(12),
222
+ \`group\` BINARY(12),
223
+ \`acUser\` TINYINT UNSIGNED,
224
+ \`acGroup\` TINYINT UNSIGNED,
225
+ \`acOther\` TINYINT UNSIGNED,
226
+ \`acRead\` LONGTEXT,
227
+ \`acWrite\` LONGTEXT,
228
+ \`acFull\` LONGTEXT,
213
229
  PRIMARY KEY (\`guid\`),
230
+ INDEX \`id_guid\` USING HASH (\`guid\`),
214
231
  INDEX \`id_cdate\` USING BTREE (\`cdate\`),
215
232
  INDEX \`id_mdate\` USING BTREE (\`mdate\`),
216
- FULLTEXT \`id_tags\` (\`tags\`)
217
- ) ENGINE ${this.config.engine}
218
- CHARACTER SET utf8 COLLATE utf8_bin;`
219
- );
220
- // Create the data table.
221
- this.queryRunSync(
222
- `CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(
223
- `${this.prefix}data_${etype}`
224
- )} (
225
- \`guid\` BINARY(12) NOT NULL${foreignKeyDataTableGuid},
226
- \`name\` TEXT NOT NULL,
227
- \`value\` LONGTEXT NOT NULL,
228
- PRIMARY KEY (\`guid\`,\`name\`(255)),
229
- INDEX \`id_name\` USING HASH (\`name\`(255)),
230
- INDEX \`id_name_value\` USING BTREE (\`name\`(255), \`value\`(512))
233
+ FULLTEXT \`id_tags\` (\`tags\`),
234
+ INDEX \`id_user_acUser\` USING BTREE (\`user\`, \`acUser\`),
235
+ INDEX \`id_group_acGroup\` USING BTREE (\`group\`, \`acGroup\`),
236
+ INDEX \`id_acUser\` USING BTREE (\`acUser\`),
237
+ INDEX \`id_acGroup\` USING BTREE (\`acGroup\`),
238
+ INDEX \`id_acOther\` USING BTREE (\`acOther\`),
239
+ FULLTEXT \`id_acRead\` (\`acRead\`),
240
+ FULLTEXT \`id_acWrite\` (\`acWrite\`),
241
+ FULLTEXT \`id_acFull\` (\`acFull\`)
231
242
  ) ENGINE ${this.config.engine}
232
- CHARACTER SET utf8 COLLATE utf8_bin;`
233
- );
234
- // Create the data comparisons table.
235
- this.queryRunSync(
236
- `CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(
237
- `${this.prefix}comparisons_${etype}`
238
- )} (
239
- \`guid\` BINARY(12) NOT NULL${foreignKeyDataComparisonsTableGuid},
243
+ CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;`,
244
+ );
245
+ }
246
+
247
+ private async addTilmeldColumnsAndIndexes(etype: string) {
248
+ await this.queryRun(
249
+ `ALTER TABLE ${MySQLDriver.escape(
250
+ `${this.prefix}entities_${etype}`,
251
+ )} ADD COLUMN \`user\` BINARY(12);`,
252
+ );
253
+ await this.queryRun(
254
+ `ALTER TABLE ${MySQLDriver.escape(
255
+ `${this.prefix}entities_${etype}`,
256
+ )} ADD COLUMN \`group\` BINARY(12);`,
257
+ );
258
+ await this.queryRun(
259
+ `ALTER TABLE ${MySQLDriver.escape(
260
+ `${this.prefix}entities_${etype}`,
261
+ )} ADD COLUMN \`acUser\` TINYINT UNSIGNED;`,
262
+ );
263
+ await this.queryRun(
264
+ `ALTER TABLE ${MySQLDriver.escape(
265
+ `${this.prefix}entities_${etype}`,
266
+ )} ADD COLUMN \`acGroup\` TINYINT UNSIGNED;`,
267
+ );
268
+ await this.queryRun(
269
+ `ALTER TABLE ${MySQLDriver.escape(
270
+ `${this.prefix}entities_${etype}`,
271
+ )} ADD COLUMN \`acOther\` TINYINT UNSIGNED;`,
272
+ );
273
+ await this.queryRun(
274
+ `ALTER TABLE ${MySQLDriver.escape(
275
+ `${this.prefix}entities_${etype}`,
276
+ )} ADD COLUMN \`acRead\` LONGTEXT;`,
277
+ );
278
+ await this.queryRun(
279
+ `ALTER TABLE ${MySQLDriver.escape(
280
+ `${this.prefix}entities_${etype}`,
281
+ )} ADD COLUMN \`acWrite\` LONGTEXT;`,
282
+ );
283
+ await this.queryRun(
284
+ `ALTER TABLE ${MySQLDriver.escape(
285
+ `${this.prefix}entities_${etype}`,
286
+ )} ADD COLUMN \`acFull\` LONGTEXT;`,
287
+ );
288
+ await this.createEntitiesTilmeldIndexes(etype);
289
+ }
290
+
291
+ private async createEntitiesTilmeldIndexes(etype: string) {
292
+ await this.queryRun(
293
+ `CREATE INDEX \`id_user_acUser\` ON ${MySQLDriver.escape(
294
+ `${this.prefix}entities_${etype}`,
295
+ )} (\`user\`, \`acUser\`) USING BTREE;`,
296
+ );
297
+ await this.queryRun(
298
+ `CREATE INDEX \`id_group_acGroup\` ON ${MySQLDriver.escape(
299
+ `${this.prefix}entities_${etype}`,
300
+ )} (\`group\`, \`acGroup\`) USING BTREE;`,
301
+ );
302
+ await this.queryRun(
303
+ `CREATE INDEX \`id_acUser\` ON ${MySQLDriver.escape(
304
+ `${this.prefix}entities_${etype}`,
305
+ )} (\`acUser\`) USING BTREE;`,
306
+ );
307
+ await this.queryRun(
308
+ `CREATE INDEX \`id_acGroup\` ON ${MySQLDriver.escape(
309
+ `${this.prefix}entities_${etype}`,
310
+ )} (\`acGroup\`) USING BTREE;`,
311
+ );
312
+ await this.queryRun(
313
+ `CREATE INDEX \`id_acOther\` ON ${MySQLDriver.escape(
314
+ `${this.prefix}entities_${etype}`,
315
+ )} (\`acOther\`) USING BTREE;`,
316
+ );
317
+ await this.queryRun(
318
+ `CREATE FULLTEXT INDEX \`id_acRead\` ON ${MySQLDriver.escape(
319
+ `${this.prefix}entities_${etype}`,
320
+ )} (\`acRead\`);`,
321
+ );
322
+ await this.queryRun(
323
+ `CREATE FULLTEXT INDEX \`id_acWrite\` ON ${MySQLDriver.escape(
324
+ `${this.prefix}entities_${etype}`,
325
+ )} (\`acWrite\`);`,
326
+ );
327
+ await this.queryRun(
328
+ `CREATE FULLTEXT INDEX \`id_acFull\` ON ${MySQLDriver.escape(
329
+ `${this.prefix}entities_${etype}`,
330
+ )} (\`acFull\`);`,
331
+ );
332
+ }
333
+
334
+ private async createDataTable(etype: string) {
335
+ let foreignKey = '';
336
+ if (this.config.foreignKeys) {
337
+ foreignKey = ` REFERENCES ${MySQLDriver.escape(
338
+ `${this.prefix}entities_${etype}`,
339
+ )}(\`guid\`) ON DELETE CASCADE`;
340
+ }
341
+ // Create the data table.
342
+ await this.queryRun(
343
+ `CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(
344
+ `${this.prefix}data_${etype}`,
345
+ )} (
346
+ \`guid\` BINARY(12) NOT NULL${foreignKey},
240
347
  \`name\` TEXT NOT NULL,
241
- \`truthy\` BOOLEAN,
348
+ \`value\` CHAR(1) NOT NULL,
349
+ \`json\` JSON,
242
350
  \`string\` LONGTEXT,
243
351
  \`number\` DOUBLE,
352
+ \`truthy\` BOOLEAN,
244
353
  PRIMARY KEY (\`guid\`, \`name\`(255)),
245
- INDEX \`id_name\` USING HASH (\`name\`(255))
354
+ INDEX \`id_name_guid\` USING BTREE (\`name\`(255), \`guid\`),
355
+ INDEX \`id_name_string_guid\` USING BTREE (\`name\`(255), \`string\`(500), \`guid\`),
356
+ INDEX \`id_name_number_guid\` USING BTREE (\`name\`(255), \`number\`, \`guid\`),
357
+ INDEX \`id_name_truthy_guid\` USING BTREE (\`name\`(255), \`truthy\`, \`guid\`),
358
+ INDEX \`id_name_json_guid\` USING BTREE (\`name\`(255), (CAST(\`json\` AS CHAR(500)) COLLATE utf8mb4_bin), \`guid\`)
246
359
  ) ENGINE ${this.config.engine}
247
- CHARACTER SET utf8 COLLATE utf8_bin;`
248
- );
249
- // Create the references table.
250
- this.queryRunSync(
251
- `CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(
252
- `${this.prefix}references_${etype}`
253
- )} (
254
- \`guid\` BINARY(12) NOT NULL${foreignKeyReferencesTableGuid},
360
+ CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;`,
361
+ );
362
+ }
363
+
364
+ private async createReferencesTable(etype: string) {
365
+ let foreignKey = '';
366
+ if (this.config.foreignKeys) {
367
+ foreignKey = ` REFERENCES ${MySQLDriver.escape(
368
+ `${this.prefix}entities_${etype}`,
369
+ )}(\`guid\`) ON DELETE CASCADE`;
370
+ }
371
+ // Create the references table.
372
+ await this.queryRun(
373
+ `CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(
374
+ `${this.prefix}references_${etype}`,
375
+ )} (
376
+ \`guid\` BINARY(12) NOT NULL${foreignKey},
255
377
  \`name\` TEXT NOT NULL,
256
378
  \`reference\` BINARY(12) NOT NULL,
257
379
  PRIMARY KEY (\`guid\`, \`name\`(255), \`reference\`),
258
- INDEX \`id_name_reference\` USING BTREE (\`name\`(255), \`reference\`)
380
+ INDEX \`id_name_reference_guid\` USING HASH (\`name\`(255), \`reference\`, \`guid\`)
259
381
  ) ENGINE ${this.config.engine}
260
- CHARACTER SET utf8 COLLATE utf8_bin;`
261
- );
382
+ CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;`,
383
+ );
384
+ }
385
+
386
+ private async createTokensTable(etype: string) {
387
+ let foreignKey = '';
388
+ if (this.config.foreignKeys) {
389
+ foreignKey = ` REFERENCES ${MySQLDriver.escape(
390
+ `${this.prefix}entities_${etype}`,
391
+ )}(\`guid\`) ON DELETE CASCADE`;
392
+ }
393
+ // Create the tokens table.
394
+ await this.queryRun(
395
+ `CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(
396
+ `${this.prefix}tokens_${etype}`,
397
+ )} (
398
+ \`guid\` BINARY(12) NOT NULL${foreignKey},
399
+ \`name\` TEXT NOT NULL,
400
+ \`token\` INT NOT NULL,
401
+ \`position\` INT UNSIGNED NOT NULL,
402
+ \`stem\` BOOLEAN NOT NULL,
403
+ PRIMARY KEY (\`guid\`, \`name\`(255), \`token\`, \`position\`),
404
+ INDEX \`id_name_token_guid\` USING btree (\`name\`(255), \`token\`, \`guid\`)
405
+ ) ENGINE ${this.config.engine}
406
+ CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;`,
407
+ );
408
+ }
409
+
410
+ private async createUniquesTable(etype: string) {
411
+ let foreignKey = '';
412
+ if (this.config.foreignKeys) {
413
+ foreignKey = ` REFERENCES ${MySQLDriver.escape(
414
+ `${this.prefix}entities_${etype}`,
415
+ )}(\`guid\`) ON DELETE CASCADE`;
416
+ }
417
+ // Create the unique strings table.
418
+ // 255 key is max length for charset UTF8.
419
+ await this.queryRun(
420
+ `CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(
421
+ `${this.prefix}uniques_${etype}`,
422
+ )} (
423
+ \`guid\` BINARY(12) NOT NULL${foreignKey},
424
+ \`unique\` TEXT NOT NULL,
425
+ PRIMARY KEY (\`guid\`, \`unique\`(255)),
426
+ INDEX \`id_guid\` USING HASH (\`guid\`),
427
+ CONSTRAINT \`uc_unique\` UNIQUE (\`unique\`(255))
428
+ ) ENGINE ${this.config.engine}
429
+ CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;`,
430
+ );
431
+ }
432
+
433
+ /**
434
+ * Create entity tables in the database.
435
+ *
436
+ * @param etype The entity type to create a table for. If this is blank, the default tables are created.
437
+ * @returns True on success, false on failure.
438
+ */
439
+ private async createTables(etype: string | null = null) {
440
+ await this.queryRun('SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";');
441
+ if (etype != null) {
442
+ await this.createEntitiesTable(etype);
443
+ await this.createDataTable(etype);
444
+ await this.createReferencesTable(etype);
445
+ await this.createTokensTable(etype);
446
+ await this.createUniquesTable(etype);
262
447
  } else {
263
448
  // Create the UID table.
264
- this.queryRunSync(
449
+ await this.queryRun(
265
450
  `CREATE TABLE IF NOT EXISTS ${MySQLDriver.escape(
266
- `${this.prefix}uids`
451
+ `${this.prefix}uids`,
267
452
  )} (
268
453
  \`name\` TEXT NOT NULL,
269
454
  \`cur_uid\` BIGINT(20) UNSIGNED NOT NULL,
270
- PRIMARY KEY (\`name\`(100))
455
+ PRIMARY KEY (\`name\`(128))
271
456
  ) ENGINE ${this.config.engine}
272
- CHARACTER SET utf8 COLLATE utf8_bin;`
457
+ CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;`,
273
458
  );
274
459
  }
460
+ if (
461
+ this.transaction &&
462
+ this.transaction.count > 0 &&
463
+ this.config.transactions
464
+ ) {
465
+ this.transaction.count = 0;
466
+ this.transaction.connection?.release();
467
+ this.transaction.connection = null;
468
+ this.transaction = null;
469
+ }
275
470
  return true;
276
471
  }
277
472
 
278
473
  private translateQuery(
279
474
  origQuery: string,
280
- origParams: { [k: string]: any }
475
+ origParams: { [k: string]: any },
281
476
  ): { query: string; params: any[] } {
282
477
  const params: any[] = [];
283
478
  let query = origQuery;
@@ -296,32 +491,37 @@ export default class MySQLDriver extends NymphDriver {
296
491
  private async query<T extends () => any>(
297
492
  runQuery: T,
298
493
  query: string,
299
- etypes: string[] = []
494
+ etypes: string[] = [],
300
495
  // @ts-ignore: The return type of T is a promise.
301
496
  ): ReturnType<T> {
302
497
  try {
498
+ this.nymph.config.debugInfo('mysql:query', query);
303
499
  return await runQuery();
304
500
  } catch (e: any) {
305
501
  const errorCode = e?.errno;
306
- if (errorCode === 1146 && this.createTables()) {
502
+ if (errorCode === 1146 && (await this.createTables())) {
307
503
  // If the tables don't exist yet, create them.
308
504
  for (let etype of etypes) {
309
- this.createTables(etype);
505
+ await this.createTables(etype);
310
506
  }
311
507
  try {
312
508
  return await runQuery();
313
509
  } catch (e2: any) {
314
510
  throw new QueryFailedError(
315
511
  'Query failed: ' + e2?.errno + ' - ' + e2?.message,
316
- query
512
+ query,
513
+ e2?.errno,
317
514
  );
318
515
  }
516
+ } else if (errorCode === 1062) {
517
+ throw new EntityUniqueConstraintError(`Unique constraint violation.`);
319
518
  } else if (errorCode === 2006) {
320
519
  // If the MySQL server disconnected, reconnect to it.
321
- if (!this.connect()) {
520
+ if (!(await this.connect())) {
322
521
  throw new QueryFailedError(
323
522
  'Query failed: ' + e?.errno + ' - ' + e?.message,
324
- query
523
+ query,
524
+ e?.errno,
325
525
  );
326
526
  }
327
527
  try {
@@ -329,60 +529,21 @@ export default class MySQLDriver extends NymphDriver {
329
529
  } catch (e2: any) {
330
530
  throw new QueryFailedError(
331
531
  'Query failed: ' + e2?.errno + ' - ' + e2?.message,
332
- query
333
- );
334
- }
335
- } else {
336
- throw e;
337
- }
338
- }
339
- }
340
-
341
- private querySync<T extends () => any>(
342
- runQuery: T,
343
- query: string,
344
- etypes: string[] = []
345
- ): ReturnType<T> {
346
- try {
347
- return runQuery();
348
- } catch (e: any) {
349
- const errorCode = e?.errno;
350
- if (errorCode === 1146 && this.createTables()) {
351
- // If the tables don't exist yet, create them.
352
- for (let etype of etypes) {
353
- this.createTables(etype);
354
- }
355
- try {
356
- return runQuery();
357
- } catch (e2: any) {
358
- throw new QueryFailedError(
359
- 'Query failed: ' + e2?.errno + ' - ' + e2?.message,
360
- query
361
- );
362
- }
363
- } else if (errorCode === 2006) {
364
- // If the MySQL server disconnected, reconnect to it.
365
- if (!this.connect()) {
366
- throw new QueryFailedError(
367
- 'Query failed: ' + e?.errno + ' - ' + e?.message,
368
- query
369
- );
370
- }
371
- try {
372
- return runQuery();
373
- } catch (e2: any) {
374
- throw new QueryFailedError(
375
- 'Query failed: ' + e2?.errno + ' - ' + e2?.message,
376
- query
532
+ query,
533
+ e2?.errno,
377
534
  );
378
535
  }
379
536
  } else {
380
- throw e;
537
+ throw new QueryFailedError(
538
+ 'Query failed: ' + e?.errno + ' - ' + e?.message,
539
+ query,
540
+ e?.errno,
541
+ );
381
542
  }
382
543
  }
383
544
  }
384
545
 
385
- private queryIter(
546
+ private queryArray(
386
547
  query: string,
387
548
  {
388
549
  etypes = [],
@@ -390,82 +551,42 @@ export default class MySQLDriver extends NymphDriver {
390
551
  }: {
391
552
  etypes?: string[];
392
553
  params?: { [k: string]: any };
393
- } = {}
554
+ } = {},
394
555
  ) {
395
556
  const { query: newQuery, params: newParams } = this.translateQuery(
396
557
  query,
397
- params
558
+ params,
398
559
  );
399
560
  return this.query(
400
561
  async () => {
401
- const results: any = await new Promise((resolve, reject) => {
402
- try {
403
- (this.transaction?.connection ?? this.link).query(
404
- newQuery,
405
- newParams,
406
- (error, results) => {
407
- if (error) {
408
- reject(error);
409
- }
562
+ const results: any = await new Promise(async (resolve, reject) => {
563
+ // Only do one query at a time in transations.
564
+ let myResolve: (value: void | PromiseLike<void>) => void = () => {};
565
+ const myPromise = new Promise<void>((resolve) => {
566
+ myResolve = resolve;
567
+ });
568
+ if (this.transaction) {
569
+ const latestPromise = this.transaction.latestPromise;
570
+ this.transaction.latestPromise = myPromise;
571
+ await latestPromise;
572
+ }
573
+ (this.transaction?.connection ?? this.link).query(
574
+ newQuery,
575
+ newParams,
576
+ (error, results) => {
577
+ if (error) {
578
+ reject(error);
579
+ } else {
410
580
  resolve(results);
411
581
  }
412
- );
413
- } catch (e) {
414
- reject(e);
415
- }
582
+ myResolve();
583
+ },
584
+ );
416
585
  });
417
586
  return results;
418
587
  },
419
588
  `${query} -- ${JSON.stringify(params)}`,
420
- etypes
421
- );
422
- }
423
-
424
- private queryIterSync(
425
- query: string,
426
- {
427
- etypes = [],
428
- params = {},
429
- }: { etypes?: string[]; params?: { [k: string]: any } } = {}
430
- ) {
431
- const { query: newQuery, params: newParams } = this.translateQuery(
432
- query,
433
- params
434
- );
435
- return this.querySync(
436
- () => {
437
- const output = cp.spawnSync(
438
- process.argv0,
439
- [__dirname + '/runMysqlSync.js'],
440
- {
441
- input: JSON.stringify({
442
- mysqlConfig: this.mysqlConfig,
443
- query: newQuery,
444
- params: newParams,
445
- }),
446
- timeout: 30000,
447
- maxBuffer: 100 * 1024 * 1024,
448
- encoding: 'utf8',
449
- windowsHide: true,
450
- }
451
- );
452
- try {
453
- const { results } = JSON.parse(output.stdout);
454
- return results;
455
- } catch (e) {
456
- // Do nothing.
457
- }
458
- if (output.status === 0) {
459
- throw new Error('Unknown parse error.');
460
- }
461
- const err = JSON.parse(output.stderr);
462
- const e = new Error(err.name);
463
- for (const name in err) {
464
- (e as any)[name] = err[name];
465
- }
466
- },
467
- `${query} -- ${JSON.stringify(params)}`,
468
- etypes
589
+ etypes,
469
590
  );
470
591
  }
471
592
 
@@ -477,34 +598,42 @@ export default class MySQLDriver extends NymphDriver {
477
598
  }: {
478
599
  etypes?: string[];
479
600
  params?: { [k: string]: any };
480
- } = {}
601
+ } = {},
481
602
  ) {
482
603
  const { query: newQuery, params: newParams } = this.translateQuery(
483
604
  query,
484
- params
605
+ params,
485
606
  );
486
607
  return this.query(
487
608
  async () => {
488
- const results: any = await new Promise((resolve, reject) => {
489
- try {
490
- (this.transaction?.connection ?? this.link).query(
491
- newQuery,
492
- newParams,
493
- (error, results) => {
494
- if (error) {
495
- reject(error);
496
- }
609
+ const results: any = await new Promise(async (resolve, reject) => {
610
+ // Only do one query at a time in transations.
611
+ let myResolve: (value: void | PromiseLike<void>) => void = () => {};
612
+ const myPromise = new Promise<void>((resolve) => {
613
+ myResolve = resolve;
614
+ });
615
+ if (this.transaction) {
616
+ const latestPromise = this.transaction.latestPromise;
617
+ this.transaction.latestPromise = myPromise;
618
+ await latestPromise;
619
+ }
620
+ (this.transaction?.connection ?? this.link).query(
621
+ newQuery,
622
+ newParams,
623
+ (error, results) => {
624
+ if (error) {
625
+ reject(error);
626
+ } else {
497
627
  resolve(results);
498
628
  }
499
- );
500
- } catch (e) {
501
- reject(e);
502
- }
629
+ myResolve();
630
+ },
631
+ );
503
632
  });
504
633
  return results[0];
505
634
  },
506
635
  `${query} -- ${JSON.stringify(params)}`,
507
- etypes
636
+ etypes,
508
637
  );
509
638
  }
510
639
 
@@ -513,92 +642,55 @@ export default class MySQLDriver extends NymphDriver {
513
642
  {
514
643
  etypes = [],
515
644
  params = {},
645
+ transaction,
516
646
  }: {
517
647
  etypes?: string[];
518
648
  params?: { [k: string]: any };
519
- } = {}
649
+ transaction?: MySQLDriverTransaction;
650
+ } = {},
520
651
  ) {
521
652
  const { query: newQuery, params: newParams } = this.translateQuery(
522
653
  query,
523
- params
654
+ params,
524
655
  );
525
656
  return this.query(
526
657
  async () => {
527
- const results: any = await new Promise((resolve, reject) => {
528
- try {
529
- (this.transaction?.connection ?? this.link).query(
530
- newQuery,
531
- newParams,
532
- (error, results) => {
533
- if (error) {
534
- reject(error);
535
- }
658
+ const results: any = await new Promise(async (resolve, reject) => {
659
+ // Only do one query at a time in transations.
660
+ let myResolve: (value: void | PromiseLike<void>) => void = () => {};
661
+ const myPromise = new Promise<void>((resolve) => {
662
+ myResolve = resolve;
663
+ });
664
+ const trans = transaction ?? this.transaction;
665
+ if (trans) {
666
+ const latestPromise = trans.latestPromise;
667
+ trans.latestPromise = myPromise;
668
+ await latestPromise;
669
+ }
670
+ (trans?.connection ?? this.link).query(
671
+ newQuery,
672
+ newParams,
673
+ (error, results) => {
674
+ if (error) {
675
+ reject(error);
676
+ } else {
536
677
  resolve(results);
537
678
  }
538
- );
539
- } catch (e) {
540
- reject(e);
541
- }
679
+ myResolve();
680
+ },
681
+ );
542
682
  });
543
683
  return { changes: results.changedRows ?? 0 };
544
684
  },
545
685
  `${query} -- ${JSON.stringify(params)}`,
546
- etypes
547
- );
548
- }
549
-
550
- private queryRunSync(
551
- query: string,
552
- {
553
- etypes = [],
554
- params = {},
555
- }: { etypes?: string[]; params?: { [k: string]: any } } = {}
556
- ) {
557
- const { query: newQuery, params: newParams } = this.translateQuery(
558
- query,
559
- params
560
- );
561
- return this.querySync(
562
- () => {
563
- const output = cp.spawnSync(
564
- process.argv0,
565
- [__dirname + '/runMysqlSync.js'],
566
- {
567
- input: JSON.stringify({
568
- mysqlConfig: this.mysqlConfig,
569
- query: newQuery,
570
- params: newParams,
571
- }),
572
- timeout: 30000,
573
- maxBuffer: 100 * 1024 * 1024,
574
- encoding: 'utf8',
575
- windowsHide: true,
576
- }
577
- );
578
- try {
579
- const { results } = JSON.parse(output.stdout);
580
- return { changes: results.changedRows ?? 0 };
581
- } catch (e) {
582
- // Do nothing.
583
- }
584
- if (output.status === 0) {
585
- throw new Error('Unknown parse error.');
586
- }
587
- const err = JSON.parse(output.stderr);
588
- const e = new Error(err.name);
589
- for (const name in err) {
590
- (e as any)[name] = err[name];
591
- }
592
- },
593
- `${query} -- ${JSON.stringify(params)}`,
594
- etypes
686
+ etypes,
595
687
  );
596
688
  }
597
689
 
598
690
  public async commit(name: string) {
599
691
  if (name == null || typeof name !== 'string' || name.length === 0) {
600
692
  throw new InvalidParametersError(
601
- 'Transaction commit attempted without a name.'
693
+ 'Transaction commit attempted without a name.',
602
694
  );
603
695
  }
604
696
  if (!this.transaction || this.transaction.count === 0) {
@@ -620,7 +712,7 @@ export default class MySQLDriver extends NymphDriver {
620
712
 
621
713
  public async deleteEntityByID(
622
714
  guid: string,
623
- className?: EntityConstructor | string | null
715
+ className?: EntityConstructor | string | null,
624
716
  ) {
625
717
  let EntityClass: EntityConstructor;
626
718
  if (typeof className === 'string' || className == null) {
@@ -634,161 +726,440 @@ export default class MySQLDriver extends NymphDriver {
634
726
  try {
635
727
  await this.queryRun(
636
728
  `DELETE FROM ${MySQLDriver.escape(
637
- `${this.prefix}entities_${etype}`
729
+ `${this.prefix}entities_${etype}`,
638
730
  )} WHERE \`guid\`=UNHEX(@guid);`,
639
731
  {
640
732
  etypes: [etype],
641
733
  params: {
642
734
  guid,
643
735
  },
644
- }
736
+ },
645
737
  );
646
738
  await this.queryRun(
647
739
  `DELETE FROM ${MySQLDriver.escape(
648
- `${this.prefix}data_${etype}`
740
+ `${this.prefix}data_${etype}`,
649
741
  )} WHERE \`guid\`=UNHEX(@guid);`,
650
742
  {
651
743
  etypes: [etype],
652
744
  params: {
653
745
  guid,
654
746
  },
655
- }
747
+ },
656
748
  );
657
749
  await this.queryRun(
658
750
  `DELETE FROM ${MySQLDriver.escape(
659
- `${this.prefix}comparisons_${etype}`
751
+ `${this.prefix}references_${etype}`,
660
752
  )} WHERE \`guid\`=UNHEX(@guid);`,
661
753
  {
662
754
  etypes: [etype],
663
755
  params: {
664
756
  guid,
665
757
  },
666
- }
758
+ },
667
759
  );
668
760
  await this.queryRun(
669
761
  `DELETE FROM ${MySQLDriver.escape(
670
- `${this.prefix}references_${etype}`
762
+ `${this.prefix}tokens_${etype}`,
671
763
  )} WHERE \`guid\`=UNHEX(@guid);`,
672
764
  {
673
765
  etypes: [etype],
674
766
  params: {
675
767
  guid,
676
768
  },
677
- }
769
+ },
770
+ );
771
+ await this.queryRun(
772
+ `DELETE FROM ${MySQLDriver.escape(
773
+ `${this.prefix}uniques_${etype}`,
774
+ )} WHERE \`guid\`=UNHEX(@guid);`,
775
+ {
776
+ etypes: [etype],
777
+ params: {
778
+ guid,
779
+ },
780
+ },
678
781
  );
679
- await this.commit('nymph-delete');
680
- // Remove any cached versions of this entity.
681
- if (this.nymph.config.cache) {
682
- this.cleanCache(guid);
683
- }
684
- return true;
685
782
  } catch (e: any) {
783
+ this.nymph.config.debugError('mysql', `Delete entity error: "${e}"`);
686
784
  await this.rollback('nymph-delete');
687
785
  throw e;
688
786
  }
787
+
788
+ await this.commit('nymph-delete');
789
+ return true;
689
790
  }
690
791
 
691
792
  public async deleteUID(name: string) {
692
793
  if (!name) {
693
794
  throw new InvalidParametersError('Name not given for UID');
694
795
  }
796
+ if (name.length > 128) {
797
+ throw new InvalidParametersError('UID name too long. 128 chars max.');
798
+ }
695
799
  await this.queryRun(
696
800
  `DELETE FROM ${MySQLDriver.escape(
697
- `${this.prefix}uids`
801
+ `${this.prefix}uids`,
698
802
  )} WHERE \`name\`=@name;`,
699
803
  {
700
804
  params: {
701
805
  name,
702
806
  },
703
- }
807
+ },
704
808
  );
705
809
  return true;
706
810
  }
707
811
 
708
- protected async exportEntities(writeLine: (line: string) => void) {
709
- writeLine('#nex2');
710
- writeLine('# Nymph Entity Exchange v2');
711
- writeLine('# http://nymph.io');
712
- writeLine('#');
713
- writeLine('# Generation Time: ' + new Date().toLocaleString());
714
- writeLine('');
812
+ public async getIndexes(etype: string) {
813
+ const indexes: {
814
+ scope: 'data' | 'references' | 'tokens';
815
+ name: string;
816
+ property: string;
817
+ }[] = [];
715
818
 
716
- writeLine('#');
717
- writeLine('# UIDs');
718
- writeLine('#');
719
- writeLine('');
819
+ for (let [scope, suffix] of [
820
+ ['data', '_string_guid'],
821
+ ['references', '_reference_guid'],
822
+ ['tokens', '_token_guid'],
823
+ ] as (
824
+ | ['data', '_string_guid']
825
+ | ['references', '_reference_guid']
826
+ | ['tokens', '_token_guid']
827
+ )[]) {
828
+ const indexDefinitions = await this.queryArray(
829
+ `SHOW INDEXES FROM ${MySQLDriver.escape(
830
+ `${this.prefix}${scope}_${etype}`,
831
+ )} WHERE \`Key_name\` LIKE @pattern AND \`Seq_in_index\`=1;`,
832
+ {
833
+ params: {
834
+ pattern: `${this.prefix}${scope}_${etype}_id_custom_%${suffix}`,
835
+ },
836
+ },
837
+ );
838
+ for (const indexDefinition of indexDefinitions) {
839
+ indexes.push({
840
+ scope,
841
+ name: (indexDefinition.Key_name as string).substring(
842
+ `${this.prefix}${scope}_${etype}_id_custom_`.length,
843
+ indexDefinition.Key_name.length - suffix.length,
844
+ ),
845
+ property:
846
+ ((indexDefinition.Expression as string).match(
847
+ /\s*\(?\s*`?name`?\s*=\s*(?:\w*)\\*'(.*?)\\*'/,
848
+ ) ?? [])[1] ?? '',
849
+ });
850
+ }
851
+ }
852
+
853
+ return indexes;
854
+ }
855
+
856
+ public async addIndex(
857
+ etype: string,
858
+ definition: {
859
+ scope: 'data' | 'references' | 'tokens';
860
+ name: string;
861
+ property: string;
862
+ },
863
+ ) {
864
+ this.checkIndexName(definition.name);
865
+ await this.deleteIndex(etype, definition.scope, definition.name);
866
+ if (definition.scope === 'data') {
867
+ await this.queryRun(
868
+ `CREATE INDEX ${MySQLDriver.escape(
869
+ `${this.prefix}data_${etype}_id_custom_${definition.name}_string_guid`,
870
+ )} USING btree ON ${MySQLDriver.escape(
871
+ `${this.prefix}data_${etype}`,
872
+ )} (((\`name\` = ${MySQLDriver.escapeValue(definition.property)})), \`string\`(500), \`guid\`);`,
873
+ );
874
+ await this.queryRun(
875
+ `CREATE INDEX ${MySQLDriver.escape(
876
+ `${this.prefix}data_${etype}_id_custom_${definition.name}_number_guid`,
877
+ )} USING btree ON ${MySQLDriver.escape(
878
+ `${this.prefix}data_${etype}`,
879
+ )} (((\`name\` = ${MySQLDriver.escapeValue(definition.property)})), \`number\`, \`guid\`);`,
880
+ );
881
+ await this.queryRun(
882
+ `CREATE INDEX ${MySQLDriver.escape(
883
+ `${this.prefix}data_${etype}_id_custom_${definition.name}_truthy_guid`,
884
+ )} USING btree ON ${MySQLDriver.escape(
885
+ `${this.prefix}data_${etype}`,
886
+ )} (((\`name\` = ${MySQLDriver.escapeValue(definition.property)})), \`truthy\`, \`guid\`);`,
887
+ );
888
+ await this.queryRun(
889
+ `CREATE INDEX ${MySQLDriver.escape(
890
+ `${this.prefix}data_${etype}_id_custom_${definition.name}_json_guid`,
891
+ )} USING btree ON ${MySQLDriver.escape(
892
+ `${this.prefix}data_${etype}`,
893
+ )} (((\`name\` = ${MySQLDriver.escapeValue(definition.property)})), (CAST(\`json\` AS CHAR(500)) COLLATE utf8mb4_bin), \`guid\`);`,
894
+ );
895
+ } else if (definition.scope === 'references') {
896
+ await this.queryRun(
897
+ `CREATE INDEX ${MySQLDriver.escape(
898
+ `${this.prefix}references_${etype}_id_custom_${definition.name}_reference_guid`,
899
+ )} USING btree ON ${MySQLDriver.escape(
900
+ `${this.prefix}references_${etype}`,
901
+ )} (((\`name\` = ${MySQLDriver.escapeValue(definition.property)})), \`reference\`, \`guid\`);`,
902
+ );
903
+ } else if (definition.scope === 'tokens') {
904
+ await this.queryRun(
905
+ `CREATE INDEX ${MySQLDriver.escape(
906
+ `${this.prefix}tokens_${etype}_id_custom_${definition.name}_token_guid`,
907
+ )} USING btree ON ${MySQLDriver.escape(
908
+ `${this.prefix}tokens_${etype}`,
909
+ )} (((\`name\` = ${MySQLDriver.escapeValue(definition.property)})), \`token\`, \`guid\`);`,
910
+ );
911
+ }
912
+ return true;
913
+ }
914
+
915
+ public async deleteIndex(
916
+ etype: string,
917
+ scope: 'data' | 'references' | 'tokens',
918
+ name: string,
919
+ ) {
920
+ this.checkIndexName(name);
921
+ try {
922
+ if (scope === 'data') {
923
+ await this.queryRun(
924
+ `DROP INDEX ${MySQLDriver.escape(
925
+ `${this.prefix}data_${etype}_id_custom_${name}_string_guid`,
926
+ )} ON ${MySQLDriver.escape(`${this.prefix}data_${etype}`)};`,
927
+ );
928
+ await this.queryRun(
929
+ `DROP INDEX ${MySQLDriver.escape(
930
+ `${this.prefix}data_${etype}_id_custom_${name}_number_guid`,
931
+ )} ON ${MySQLDriver.escape(`${this.prefix}data_${etype}`)};`,
932
+ );
933
+ await this.queryRun(
934
+ `DROP INDEX ${MySQLDriver.escape(
935
+ `${this.prefix}data_${etype}_id_custom_${name}_truthy_guid`,
936
+ )} ON ${MySQLDriver.escape(`${this.prefix}data_${etype}`)};`,
937
+ );
938
+ await this.queryRun(
939
+ `DROP INDEX ${MySQLDriver.escape(
940
+ `${this.prefix}data_${etype}_id_custom_${name}_json_guid`,
941
+ )} ON ${MySQLDriver.escape(`${this.prefix}data_${etype}`)};`,
942
+ );
943
+ } else if (scope === 'references') {
944
+ await this.queryRun(
945
+ `DROP INDEX ${MySQLDriver.escape(
946
+ `${this.prefix}references_${etype}_id_custom_${name}_reference_guid`,
947
+ )} ON ${MySQLDriver.escape(`${this.prefix}references_${etype}`)};`,
948
+ );
949
+ } else if (scope === 'tokens') {
950
+ await this.queryRun(
951
+ `DROP INDEX ${MySQLDriver.escape(
952
+ `${this.prefix}tokens_${etype}_id_custom_${name}_token_guid`,
953
+ )} ON ${MySQLDriver.escape(`${this.prefix}tokens_${etype}`)};`,
954
+ );
955
+ }
956
+ } catch (e: any) {
957
+ if (e?.errorCode !== 1091) {
958
+ throw e;
959
+ }
960
+ }
961
+ return true;
962
+ }
963
+
964
+ public async getEtypes() {
965
+ const tables = await this.queryArray(
966
+ 'SELECT `table_name` AS `table_name` FROM `information_schema`.`tables` WHERE `table_schema`=@db AND `table_name` LIKE @prefix;',
967
+ {
968
+ params: {
969
+ db: this.config.database,
970
+ prefix: this.prefix + 'entities_' + '%',
971
+ },
972
+ },
973
+ );
974
+ const etypes: string[] = [];
975
+ for (const table of tables) {
976
+ etypes.push(table.table_name.substr((this.prefix + 'entities_').length));
977
+ }
978
+
979
+ return etypes;
980
+ }
981
+
982
+ public async *exportDataIterator(): AsyncGenerator<
983
+ { type: 'comment' | 'uid' | 'entity'; content: string },
984
+ void,
985
+ false | undefined
986
+ > {
987
+ if (
988
+ yield {
989
+ type: 'comment',
990
+ content: `#nex2
991
+ # Nymph Entity Exchange v2
992
+ # http://nymph.io
993
+ #
994
+ # Generation Time: ${new Date().toLocaleString()}
995
+ `,
996
+ }
997
+ ) {
998
+ return;
999
+ }
1000
+
1001
+ if (
1002
+ yield {
1003
+ type: 'comment',
1004
+ content: `
1005
+
1006
+ #
1007
+ # UIDs
1008
+ #
1009
+
1010
+ `,
1011
+ }
1012
+ ) {
1013
+ return;
1014
+ }
720
1015
 
721
1016
  // Export UIDs.
722
- let uids = await this.queryIter(
1017
+ let uids = await this.queryArray(
723
1018
  `SELECT * FROM ${MySQLDriver.escape(
724
- `${this.prefix}uids`
725
- )} ORDER BY \`name\`;`
1019
+ `${this.prefix}uids`,
1020
+ )} ORDER BY \`name\`;`,
726
1021
  );
727
1022
  for (const uid of uids) {
728
- writeLine(`<${uid.name}>[${uid.cur_uid}]`);
1023
+ if (yield { type: 'uid', content: `<${uid.name}>[${uid.cur_uid}]\n` }) {
1024
+ return;
1025
+ }
729
1026
  }
730
1027
 
731
- writeLine('');
732
- writeLine('#');
733
- writeLine('# Entities');
734
- writeLine('#');
735
- writeLine('');
1028
+ if (
1029
+ yield {
1030
+ type: 'comment',
1031
+ content: `
736
1032
 
737
- // Get the etypes.
738
- const tables = await this.queryIter('SHOW TABLES;');
739
- const etypes = [];
740
- for (const tableRow of tables) {
741
- const table = tableRow[Object.keys(tableRow)[0]];
742
- if (table.startsWith(this.prefix + 'entities_')) {
743
- etypes.push(table.substr((this.prefix + 'entities_').length));
1033
+ #
1034
+ # Entities
1035
+ #
1036
+
1037
+ `,
744
1038
  }
1039
+ ) {
1040
+ return;
745
1041
  }
746
1042
 
1043
+ // Get the etypes.
1044
+ const etypes = await this.getEtypes();
1045
+
747
1046
  for (const etype of etypes) {
748
1047
  // Export entities.
749
- const dataIterator = (
750
- await this.queryIter(
751
- `SELECT LOWER(HEX(e.\`guid\`)) AS \`guid\`, e.\`tags\`, e.\`cdate\`, e.\`mdate\`, d.\`name\` AS \`dname\`, d.\`value\` AS \`dvalue\`, c.\`string\`, c.\`number\`
1048
+ const entityIterator = this.exportEntityInternal(etype);
1049
+ for await (let content of entityIterator) {
1050
+ yield { type: 'entity', content };
1051
+ }
1052
+ }
1053
+ }
1054
+
1055
+ public async exportEntity(etype: string, guid: string): Promise<string> {
1056
+ const entityIterator = this.exportEntityInternal(etype, guid);
1057
+ let exportContent = '';
1058
+ for await (let content of entityIterator) {
1059
+ exportContent += content;
1060
+ }
1061
+
1062
+ return exportContent;
1063
+ }
1064
+
1065
+ private async *exportEntityInternal(
1066
+ etype: string,
1067
+ guid?: string,
1068
+ ): AsyncGenerator<string, void, false | undefined> {
1069
+ // Export entities.
1070
+ const dataIterator = (
1071
+ await this.queryArray(
1072
+ `SELECT LOWER(HEX(e.\`guid\`)) AS \`guid\`, e.\`tags\`, e.\`cdate\`, e.\`mdate\`, LOWER(HEX(e.\`user\`)) AS \`user\`, LOWER(HEX(e.\`group\`)) AS \`group\`, e.\`acUser\`, e.\`acGroup\`, e.\`acOther\`, e.\`acRead\`, e.\`acWrite\`, e.\`acFull\`, d.\`name\`, d.\`value\`, d.\`json\`, d.\`string\`, d.\`number\`
752
1073
  FROM ${MySQLDriver.escape(`${this.prefix}entities_${etype}`)} e
753
1074
  LEFT JOIN ${MySQLDriver.escape(
754
- `${this.prefix}data_${etype}`
755
- )} d ON e.\`guid\`=d.\`guid\`
756
- INNER JOIN ${MySQLDriver.escape(
757
- `${this.prefix}comparisons_${etype}`
758
- )} c ON d.\`guid\`=c.\`guid\` AND d.\`name\`=c.\`name\`
759
- ORDER BY e.\`guid\`;`
760
- )
761
- )[Symbol.iterator]();
762
- let datum = dataIterator.next();
763
- while (!datum.done) {
764
- const guid = datum.value.guid;
765
- const tags = datum.value.tags.slice(1, -1).split(' ').join(',');
766
- const cdate = datum.value.cdate;
767
- const mdate = datum.value.mdate;
768
- writeLine(`{${guid}}<${etype}>[${tags}]`);
769
- writeLine(`\tcdate=${JSON.stringify(cdate)}`);
770
- writeLine(`\tmdate=${JSON.stringify(mdate)}`);
771
- if (datum.value.dname != null) {
772
- // This do will keep going and adding the data until the
773
- // next entity is reached. $row will end on the next entity.
774
- do {
775
- const value =
776
- datum.value.dvalue === 'N'
777
- ? JSON.stringify(datum.value.number)
778
- : datum.value.dvalue === 'S'
1075
+ `${this.prefix}data_${etype}`,
1076
+ )} d ON e.\`guid\`=d.\`guid\`${guid == null ? '' : ` WHERE e.\`guid\`=UNHEX(@guid)`}
1077
+ ORDER BY e.\`guid\`, d.\`name\`;`,
1078
+ guid == null ? undefined : { params: { guid } },
1079
+ )
1080
+ )[Symbol.iterator]();
1081
+ let datum = dataIterator.next();
1082
+ while (!datum.done) {
1083
+ const guid = datum.value.guid;
1084
+ const tags = MySQLDriver.unescapeTags(
1085
+ datum.value.tags
1086
+ .slice(1, -1)
1087
+ .split(' ')
1088
+ .filter((tag: string) => tag),
1089
+ ).join(',');
1090
+ const cdate = datum.value.cdate;
1091
+ const mdate = datum.value.mdate;
1092
+ const user = datum.value.user;
1093
+ const group = datum.value.group;
1094
+ const acUser = datum.value.acUser;
1095
+ const acGroup = datum.value.acGroup;
1096
+ const acOther = datum.value.acOther;
1097
+ const acRead = datum.value.acRead?.slice(1, -1).split(' ');
1098
+ const acWrite = datum.value.acWrite?.slice(1, -1).split(' ');
1099
+ const acFull = datum.value.acFull?.slice(1, -1).split(' ');
1100
+ let currentEntityExport: string[] = [];
1101
+ currentEntityExport.push(
1102
+ `{${guid}}<${etype}>[${tags.replace(/\n/g, () => '\\n')}]`,
1103
+ );
1104
+ currentEntityExport.push(`\tcdate=${JSON.stringify(cdate)}`);
1105
+ currentEntityExport.push(`\tmdate=${JSON.stringify(mdate)}`);
1106
+ if (this.nymph.tilmeld != null) {
1107
+ if (user != null) {
1108
+ currentEntityExport.push(
1109
+ `\tuser=${JSON.stringify(['nymph_entity_reference', user, 'User'])}`,
1110
+ );
1111
+ }
1112
+ if (group != null) {
1113
+ currentEntityExport.push(
1114
+ `\tgroup=${JSON.stringify(['nymph_entity_reference', group, 'Group'])}`,
1115
+ );
1116
+ }
1117
+ if (acUser != null) {
1118
+ currentEntityExport.push(`\tacUser=${JSON.stringify(acUser)}`);
1119
+ }
1120
+ if (acGroup != null) {
1121
+ currentEntityExport.push(`\tacGroup=${JSON.stringify(acGroup)}`);
1122
+ }
1123
+ if (acOther != null) {
1124
+ currentEntityExport.push(`\tacOther=${JSON.stringify(acOther)}`);
1125
+ }
1126
+ if (acRead != null) {
1127
+ currentEntityExport.push(`\tacRead=${JSON.stringify(acRead)}`);
1128
+ }
1129
+ if (acWrite != null) {
1130
+ currentEntityExport.push(`\tacWrite=${JSON.stringify(acWrite)}`);
1131
+ }
1132
+ if (acFull != null) {
1133
+ currentEntityExport.push(`\tacFull=${JSON.stringify(acFull)}`);
1134
+ }
1135
+ }
1136
+ if (datum.value.name != null) {
1137
+ // This do will keep going and adding the data until the
1138
+ // next entity is reached. $row will end on the next entity.
1139
+ do {
1140
+ const value =
1141
+ datum.value.value === 'N'
1142
+ ? JSON.stringify(datum.value.number)
1143
+ : datum.value.value === 'S'
779
1144
  ? JSON.stringify(datum.value.string)
780
- : datum.value.dvalue;
781
- writeLine(`\t${datum.value.dname}=${value}`);
782
- datum = dataIterator.next();
783
- } while (!datum.done && datum.value.guid === guid);
784
- } else {
785
- // Make sure that datum is incremented :)
1145
+ : datum.value.value === 'J'
1146
+ ? JSON.stringify(datum.value.json)
1147
+ : datum.value.value;
1148
+ currentEntityExport.push(
1149
+ `\t${datum.value.name.replace(/\n/g, () => '\\n')}=${value}`,
1150
+ );
786
1151
  datum = dataIterator.next();
787
- }
1152
+ } while (!datum.done && datum.value.guid === guid);
1153
+ } else {
1154
+ // Make sure that datum is incremented :)
1155
+ datum = dataIterator.next();
788
1156
  }
789
- }
1157
+ currentEntityExport.push('');
790
1158
 
791
- return;
1159
+ if (yield currentEntityExport.join('\n')) {
1160
+ return;
1161
+ }
1162
+ }
792
1163
  }
793
1164
 
794
1165
  /**
@@ -809,21 +1180,23 @@ export default class MySQLDriver extends NymphDriver {
809
1180
  params: { [k: string]: any } = {},
810
1181
  subquery = false,
811
1182
  tableSuffix = '',
812
- etypes: string[] = []
1183
+ etypes: string[] = [],
1184
+ guidSelector: string | undefined = undefined,
1185
+ guidExplicitSelector: ((guid: string) => string) | undefined = undefined,
813
1186
  ) {
814
1187
  if (typeof options.class?.alterOptions === 'function') {
815
1188
  options = options.class.alterOptions(options);
816
1189
  }
817
1190
  const eTable = `e${tableSuffix}`;
818
1191
  const dTable = `d${tableSuffix}`;
819
- const cTable = `c${tableSuffix}`;
820
1192
  const fTable = `f${tableSuffix}`;
821
1193
  const ieTable = `ie${tableSuffix}`;
822
1194
  const countTable = `count${tableSuffix}`;
823
- const sort = options.sort ?? 'cdate';
1195
+ const sTable = `s${tableSuffix}`;
1196
+ const sort = options.sort === undefined ? 'cdate' : options.sort;
824
1197
  const queryParts = this.iterateSelectorsForQuery(
825
1198
  formattedSelectors,
826
- (key, value, typeIsOr, typeIsNot) => {
1199
+ ({ key, value, typeIsOr, typeIsNot }) => {
827
1200
  const clauseNot = key.startsWith('!');
828
1201
  let curQuery = '';
829
1202
  for (const curValue of value) {
@@ -854,12 +1227,13 @@ export default class MySQLDriver extends NymphDriver {
854
1227
  }
855
1228
  const tag = `param${++count.i}`;
856
1229
  curQuery += ieTable + '.`tags` NOT REGEXP @' + tag;
857
- params[tag] = ' ' + curTag + ' ';
1230
+ params[tag] = ' ' + MySQLDriver.escapeTag(curTag) + ' ';
858
1231
  }
859
1232
  } else {
860
1233
  const tag = `param${++count.i}`;
861
1234
  curQuery += ieTable + '.`tags` NOT REGEXP @' + tag;
862
- params[tag] = ' (' + curValue.join('|') + ') ';
1235
+ params[tag] =
1236
+ ' (' + MySQLDriver.escapeTags(curValue).join('|') + ') ';
863
1237
  }
864
1238
  } else {
865
1239
  if (curQuery) {
@@ -868,7 +1242,8 @@ export default class MySQLDriver extends NymphDriver {
868
1242
  const groupQueryParam = `param${++count.i}`;
869
1243
  let groupQuery = '';
870
1244
  for (const curTag of curValue) {
871
- groupQuery += (typeIsOr ? ' ' : ' +') + curTag;
1245
+ groupQuery +=
1246
+ (typeIsOr ? ' ' : ' +') + MySQLDriver.escapeTag(curTag);
872
1247
  }
873
1248
  curQuery +=
874
1249
  'MATCH (' +
@@ -885,17 +1260,39 @@ export default class MySQLDriver extends NymphDriver {
885
1260
  if (curQuery) {
886
1261
  curQuery += typeIsOr ? ' OR ' : ' AND ';
887
1262
  }
888
- const name = `param${++count.i}`;
889
- curQuery +=
890
- ieTable +
891
- '.`guid` ' +
892
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
893
- 'IN (SELECT `guid` FROM ' +
894
- MySQLDriver.escape(this.prefix + 'data_' + etype) +
895
- ' WHERE `name`=@' +
896
- name +
897
- ')';
898
- params[name] = curVar;
1263
+ if (
1264
+ curVar === 'cdate' ||
1265
+ curVar === 'mdate' ||
1266
+ (this.nymph.tilmeld != null &&
1267
+ (curVar === 'user' ||
1268
+ curVar === 'group' ||
1269
+ curVar === 'acUser' ||
1270
+ curVar === 'acGroup' ||
1271
+ curVar === 'acOther' ||
1272
+ curVar === 'acRead' ||
1273
+ curVar === 'acWrite' ||
1274
+ curVar === 'acFull'))
1275
+ ) {
1276
+ curQuery +=
1277
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1278
+ '(' +
1279
+ ieTable +
1280
+ '.' +
1281
+ MySQLDriver.escape(curVar) +
1282
+ ' IS NOT NULL)';
1283
+ } else {
1284
+ const name = `param${++count.i}`;
1285
+ curQuery +=
1286
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1287
+ 'EXISTS (SELECT `guid` FROM ' +
1288
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1289
+ ' WHERE `guid`=' +
1290
+ ieTable +
1291
+ '.`guid` AND `name`=@' +
1292
+ name +
1293
+ ')';
1294
+ params[name] = curVar;
1295
+ }
899
1296
  }
900
1297
  break;
901
1298
  case 'truthy':
@@ -904,28 +1301,35 @@ export default class MySQLDriver extends NymphDriver {
904
1301
  if (curQuery) {
905
1302
  curQuery += typeIsOr ? ' OR ' : ' AND ';
906
1303
  }
907
- if (curVar === 'cdate') {
908
- curQuery +=
909
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
910
- '(' +
911
- ieTable +
912
- '.`cdate` NOT NULL)';
913
- break;
914
- } else if (curVar === 'mdate') {
1304
+ if (
1305
+ curVar === 'cdate' ||
1306
+ curVar === 'mdate' ||
1307
+ (this.nymph.tilmeld != null &&
1308
+ (curVar === 'user' ||
1309
+ curVar === 'group' ||
1310
+ curVar === 'acUser' ||
1311
+ curVar === 'acGroup' ||
1312
+ curVar === 'acOther' ||
1313
+ curVar === 'acRead' ||
1314
+ curVar === 'acWrite' ||
1315
+ curVar === 'acFull'))
1316
+ ) {
915
1317
  curQuery +=
916
1318
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
917
1319
  '(' +
918
1320
  ieTable +
919
- '.`mdate` NOT NULL)';
920
- break;
1321
+ '.' +
1322
+ MySQLDriver.escape(curVar) +
1323
+ ' IS NOT NULL)';
921
1324
  } else {
922
1325
  const name = `param${++count.i}`;
923
1326
  curQuery +=
924
1327
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1328
+ 'EXISTS (SELECT `guid` FROM ' +
1329
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1330
+ ' WHERE `guid`=' +
925
1331
  ieTable +
926
- '.`guid` IN (SELECT `guid` FROM ' +
927
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
928
- ' WHERE `name`=@' +
1332
+ '.`guid` AND `name`=@' +
929
1333
  name +
930
1334
  ' AND `truthy`=TRUE)';
931
1335
  params[name] = curVar;
@@ -934,34 +1338,65 @@ export default class MySQLDriver extends NymphDriver {
934
1338
  break;
935
1339
  case 'equal':
936
1340
  case '!equal':
937
- if (curValue[0] === 'cdate') {
1341
+ if (
1342
+ curValue[0] === 'cdate' ||
1343
+ curValue[0] === 'mdate' ||
1344
+ (this.nymph.tilmeld != null &&
1345
+ (curValue[0] === 'acUser' ||
1346
+ curValue[0] === 'acGroup' ||
1347
+ curValue[0] === 'acOther'))
1348
+ ) {
938
1349
  if (curQuery) {
939
1350
  curQuery += typeIsOr ? ' OR ' : ' AND ';
940
1351
  }
941
- const cdate = `param${++count.i}`;
1352
+ const value = `param${++count.i}`;
942
1353
  curQuery +=
943
1354
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
944
1355
  ieTable +
945
- '.`cdate`=@' +
946
- cdate;
947
- params[cdate] = isNaN(Number(curValue[1]))
1356
+ '.' +
1357
+ MySQLDriver.escape(curValue[0]) +
1358
+ '=@' +
1359
+ value;
1360
+ params[value] = isNaN(Number(curValue[1]))
948
1361
  ? null
949
1362
  : Number(curValue[1]);
950
- break;
951
- } else if (curValue[0] === 'mdate') {
1363
+ } else if (
1364
+ this.nymph.tilmeld != null &&
1365
+ (curValue[0] === 'user' || curValue[0] === 'group')
1366
+ ) {
952
1367
  if (curQuery) {
953
1368
  curQuery += typeIsOr ? ' OR ' : ' AND ';
954
1369
  }
955
- const mdate = `param${++count.i}`;
1370
+ const value = `param${++count.i}`;
956
1371
  curQuery +=
957
1372
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
958
1373
  ieTable +
959
- '.`mdate`=@' +
960
- mdate;
961
- params[mdate] = isNaN(Number(curValue[1]))
962
- ? null
963
- : Number(curValue[1]);
964
- break;
1374
+ '.' +
1375
+ MySQLDriver.escape(curValue[0]) +
1376
+ '=UNHEX(@' +
1377
+ value +
1378
+ ')';
1379
+ params[value] = `${curValue[1]}`;
1380
+ } else if (
1381
+ this.nymph.tilmeld != null &&
1382
+ (curValue[0] === 'acRead' ||
1383
+ curValue[0] === 'acWrite' ||
1384
+ curValue[0] === 'acFull')
1385
+ ) {
1386
+ if (curQuery) {
1387
+ curQuery += typeIsOr ? ' OR ' : ' AND ';
1388
+ }
1389
+ const value = `param${++count.i}`;
1390
+ curQuery +=
1391
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1392
+ ieTable +
1393
+ '.' +
1394
+ MySQLDriver.escape(curValue[0]) +
1395
+ '=@' +
1396
+ value;
1397
+ params[value] = Array.isArray(curValue[1])
1398
+ ? ' ' + MySQLDriver.escapeTags(curValue[1]).join(' ') + ' '
1399
+ : '';
965
1400
  } else if (typeof curValue[1] === 'number') {
966
1401
  if (curQuery) {
967
1402
  curQuery += typeIsOr ? ' OR ' : ' AND ';
@@ -970,10 +1405,11 @@ export default class MySQLDriver extends NymphDriver {
970
1405
  const value = `param${++count.i}`;
971
1406
  curQuery +=
972
1407
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1408
+ 'EXISTS (SELECT `guid` FROM ' +
1409
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1410
+ ' WHERE `guid`=' +
973
1411
  ieTable +
974
- '.`guid` IN (SELECT `guid` FROM ' +
975
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
976
- ' WHERE `name`=@' +
1412
+ '.`guid` AND `name`=@' +
977
1413
  name +
978
1414
  ' AND `number`=@' +
979
1415
  value +
@@ -988,10 +1424,11 @@ export default class MySQLDriver extends NymphDriver {
988
1424
  const value = `param${++count.i}`;
989
1425
  curQuery +=
990
1426
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1427
+ 'EXISTS (SELECT `guid` FROM ' +
1428
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1429
+ ' WHERE `guid`=' +
991
1430
  ieTable +
992
- '.`guid` IN (SELECT `guid` FROM ' +
993
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
994
- ' WHERE `name`=@' +
1431
+ '.`guid` AND `name`=@' +
995
1432
  name +
996
1433
  ' AND `string`=@' +
997
1434
  value +
@@ -1013,136 +1450,313 @@ export default class MySQLDriver extends NymphDriver {
1013
1450
  }
1014
1451
  const name = `param${++count.i}`;
1015
1452
  const value = `param${++count.i}`;
1016
- curQuery +=
1017
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1018
- ieTable +
1019
- '.`guid` IN (SELECT `guid` FROM ' +
1020
- MySQLDriver.escape(this.prefix + 'data_' + etype) +
1021
- ' WHERE `name`=@' +
1022
- name +
1023
- ' AND `value`=@' +
1024
- value +
1025
- ')';
1453
+ if (svalue.length < 500) {
1454
+ curQuery +=
1455
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1456
+ 'EXISTS (SELECT `guid` FROM ' +
1457
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1458
+ ' WHERE `guid`=' +
1459
+ ieTable +
1460
+ '.`guid` AND `name`=@' +
1461
+ name +
1462
+ ' AND (CAST(`json` AS CHAR(500)) COLLATE utf8mb4_bin)=CAST(CAST(@' +
1463
+ value +
1464
+ ' AS JSON) AS CHAR(500)))';
1465
+ } else {
1466
+ curQuery +=
1467
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1468
+ 'EXISTS (SELECT `guid` FROM ' +
1469
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1470
+ ' WHERE `guid`=' +
1471
+ ieTable +
1472
+ '.`guid` AND `name`=@' +
1473
+ name +
1474
+ ' AND `json`=CAST(@' +
1475
+ value +
1476
+ ' AS JSON))';
1477
+ }
1026
1478
  params[name] = curValue[0];
1027
1479
  params[value] = svalue;
1028
1480
  }
1029
1481
  break;
1030
1482
  case 'contain':
1031
1483
  case '!contain':
1032
- if (curValue[0] === 'cdate') {
1484
+ if (
1485
+ curValue[0] === 'cdate' ||
1486
+ curValue[0] === 'mdate' ||
1487
+ (this.nymph.tilmeld != null &&
1488
+ (curValue[0] === 'acUser' ||
1489
+ curValue[0] === 'acGroup' ||
1490
+ curValue[0] === 'acOther'))
1491
+ ) {
1033
1492
  if (curQuery) {
1034
1493
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1035
1494
  }
1036
- const cdate = `param${++count.i}`;
1495
+ const value = `param${++count.i}`;
1037
1496
  curQuery +=
1038
1497
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1039
1498
  ieTable +
1040
- '.`cdate`=' +
1041
- cdate;
1042
- params[cdate] = isNaN(Number(curValue[1]))
1499
+ '.' +
1500
+ MySQLDriver.escape(curValue[0]) +
1501
+ '=@' +
1502
+ value;
1503
+ params[value] = isNaN(Number(curValue[1]))
1043
1504
  ? null
1044
1505
  : Number(curValue[1]);
1045
- break;
1046
- } else if (curValue[0] === 'mdate') {
1506
+ } else if (
1507
+ this.nymph.tilmeld != null &&
1508
+ (curValue[0] === 'user' || curValue[0] === 'group')
1509
+ ) {
1047
1510
  if (curQuery) {
1048
1511
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1049
1512
  }
1050
- const mdate = `param${++count.i}`;
1513
+ const value = `param${++count.i}`;
1051
1514
  curQuery +=
1052
1515
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1053
1516
  ieTable +
1054
- '.`mdate`=' +
1055
- mdate;
1056
- params[mdate] = isNaN(Number(curValue[1]))
1057
- ? null
1058
- : Number(curValue[1]);
1059
- break;
1517
+ '.' +
1518
+ MySQLDriver.escape(curValue[0]) +
1519
+ '=UNHEX(@' +
1520
+ value +
1521
+ ')';
1522
+ params[value] = `${curValue[1]}`;
1523
+ } else if (
1524
+ this.nymph.tilmeld != null &&
1525
+ (curValue[0] === 'acRead' ||
1526
+ curValue[0] === 'acWrite' ||
1527
+ curValue[0] === 'acFull')
1528
+ ) {
1529
+ if (curQuery) {
1530
+ curQuery += typeIsOr ? ' OR ' : ' AND ';
1531
+ }
1532
+ const queryParam = `param${++count.i}`;
1533
+ curQuery +=
1534
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1535
+ 'MATCH (' +
1536
+ ieTable +
1537
+ '.' +
1538
+ MySQLDriver.escape(curValue[0]) +
1539
+ ') AGAINST (@' +
1540
+ queryParam +
1541
+ ' IN BOOLEAN MODE)';
1542
+ params[queryParam] = '+' + curValue[1];
1060
1543
  } else {
1061
1544
  if (curQuery) {
1062
1545
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1063
1546
  }
1064
1547
  let svalue: string;
1065
- let stringValue: string;
1066
1548
  if (
1067
1549
  curValue[1] instanceof Object &&
1068
1550
  typeof curValue[1].toReference === 'function'
1069
1551
  ) {
1070
1552
  svalue = JSON.stringify(curValue[1].toReference());
1071
- stringValue = `${curValue[1].toReference()}`;
1072
1553
  } else {
1073
1554
  svalue = JSON.stringify(curValue[1]);
1074
- stringValue = `${curValue[1]}`;
1075
1555
  }
1076
1556
  const name = `param${++count.i}`;
1077
1557
  const value = `param${++count.i}`;
1078
- if (typeof curValue[1] === 'string') {
1079
- const stringParam = `param${++count.i}`;
1558
+ curQuery +=
1559
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1560
+ 'EXISTS (SELECT `guid` FROM ' +
1561
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1562
+ ' WHERE `guid`=' +
1563
+ ieTable +
1564
+ '.`guid` AND `name`=@' +
1565
+ name +
1566
+ ' AND JSON_CONTAINS(`json`, @' +
1567
+ value +
1568
+ '))';
1569
+ params[name] = curValue[0];
1570
+ params[value] = svalue;
1571
+ }
1572
+ break;
1573
+ case 'search':
1574
+ case '!search':
1575
+ if (
1576
+ curValue[0] === 'cdate' ||
1577
+ curValue[0] === 'mdate' ||
1578
+ (this.nymph.tilmeld != null &&
1579
+ (curValue[0] === 'user' ||
1580
+ curValue[0] === 'group' ||
1581
+ curValue[0] === 'acUser' ||
1582
+ curValue[0] === 'acGroup' ||
1583
+ curValue[0] === 'acOther' ||
1584
+ curValue[0] === 'acRead' ||
1585
+ curValue[0] === 'acWrite' ||
1586
+ curValue[0] === 'acFull'))
1587
+ ) {
1588
+ if (curQuery) {
1589
+ curQuery += typeIsOr ? ' OR ' : ' AND ';
1590
+ }
1591
+ curQuery +=
1592
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') + '(FALSE)';
1593
+ } else {
1594
+ if (curQuery) {
1595
+ curQuery += typeIsOr ? ' OR ' : ' AND ';
1596
+ }
1597
+
1598
+ const parsedFTSQuery = this.tokenizer.parseSearchQuery(
1599
+ curValue[1],
1600
+ );
1601
+
1602
+ if (!parsedFTSQuery.length) {
1080
1603
  curQuery +=
1081
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1082
- '(' +
1083
- ieTable +
1084
- '.`guid` IN (SELECT `guid` FROM ' +
1085
- MySQLDriver.escape(this.prefix + 'data_' + etype) +
1086
- ' WHERE `name`=@' +
1087
- name +
1088
- ' AND INSTR(`value`, @' +
1089
- value +
1090
- ')) OR ' +
1091
- ieTable +
1092
- '.`guid` IN (SELECT `guid` FROM ' +
1093
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1094
- ' WHERE `name`=@' +
1095
- name +
1096
- ' AND `string`=@' +
1097
- stringParam +
1098
- '))';
1099
- params[stringParam] = stringValue;
1604
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') + '(FALSE)';
1100
1605
  } else {
1606
+ const name = `param${++count.i}`;
1607
+
1608
+ const queryPartToken = (term: SearchTerm) => {
1609
+ const value = `param${++count.i}`;
1610
+ params[value] = term.token;
1611
+ return (
1612
+ 'EXISTS (SELECT `guid` FROM ' +
1613
+ MySQLDriver.escape(this.prefix + 'tokens_' + etype) +
1614
+ ' WHERE `guid`=' +
1615
+ ieTable +
1616
+ '.`guid` AND `name`=@' +
1617
+ name +
1618
+ ' AND `token`=@' +
1619
+ value +
1620
+ (term.nostemmed ? ' AND `stem`=FALSE' : '') +
1621
+ ')'
1622
+ );
1623
+ };
1624
+
1625
+ const queryPartSeries = (series: SearchSeriesTerm) => {
1626
+ const tokenTableSuffix = makeTableSuffix();
1627
+ const tokenParts = series.tokens.map((token, i) => {
1628
+ const value = `param${++count.i}`;
1629
+ params[value] = token.token;
1630
+ return {
1631
+ fromClause:
1632
+ i === 0
1633
+ ? 'FROM ' +
1634
+ MySQLDriver.escape(
1635
+ this.prefix + 'tokens_' + etype,
1636
+ ) +
1637
+ ' t' +
1638
+ tokenTableSuffix +
1639
+ '0'
1640
+ : 'JOIN ' +
1641
+ MySQLDriver.escape(
1642
+ this.prefix + 'tokens_' + etype,
1643
+ ) +
1644
+ ' t' +
1645
+ tokenTableSuffix +
1646
+ i +
1647
+ ' ON t' +
1648
+ tokenTableSuffix +
1649
+ i +
1650
+ '.`guid` = t' +
1651
+ tokenTableSuffix +
1652
+ '0.`guid` AND t' +
1653
+ tokenTableSuffix +
1654
+ i +
1655
+ '.`name` = t' +
1656
+ tokenTableSuffix +
1657
+ '0.`name` AND t' +
1658
+ tokenTableSuffix +
1659
+ i +
1660
+ '.`position` = t' +
1661
+ tokenTableSuffix +
1662
+ '0.`position` + ' +
1663
+ i,
1664
+ whereClause:
1665
+ 't' +
1666
+ tokenTableSuffix +
1667
+ i +
1668
+ '.`token`=@' +
1669
+ value +
1670
+ (token.nostemmed
1671
+ ? ' AND t' + tokenTableSuffix + i + '.`stem`=FALSE'
1672
+ : ''),
1673
+ };
1674
+ });
1675
+ return (
1676
+ 'EXISTS (SELECT t' +
1677
+ tokenTableSuffix +
1678
+ '0.`guid` ' +
1679
+ tokenParts.map((part) => part.fromClause).join(' ') +
1680
+ ' WHERE t' +
1681
+ tokenTableSuffix +
1682
+ '0.`guid`=' +
1683
+ ieTable +
1684
+ '.`guid` AND t' +
1685
+ tokenTableSuffix +
1686
+ '0.`name`=@' +
1687
+ name +
1688
+ ' AND ' +
1689
+ tokenParts.map((part) => part.whereClause).join(' AND ') +
1690
+ ')'
1691
+ );
1692
+ };
1693
+
1694
+ const queryPartTerm = (
1695
+ term:
1696
+ | SearchTerm
1697
+ | SearchOrTerm
1698
+ | SearchNotTerm
1699
+ | SearchSeriesTerm,
1700
+ ): string => {
1701
+ if (term.type === 'series') {
1702
+ return queryPartSeries(term);
1703
+ } else if (term.type === 'not') {
1704
+ return 'NOT ' + queryPartTerm(term.operand);
1705
+ } else if (term.type === 'or') {
1706
+ let queryParts: string[] = [];
1707
+ for (let operand of term.operands) {
1708
+ queryParts.push(queryPartTerm(operand));
1709
+ }
1710
+ return '(' + queryParts.join(' OR ') + ')';
1711
+ }
1712
+ return queryPartToken(term);
1713
+ };
1714
+
1715
+ // Run through the query and add terms.
1716
+ let termStrings: string[] = [];
1717
+ for (let term of parsedFTSQuery) {
1718
+ termStrings.push(queryPartTerm(term));
1719
+ }
1720
+
1101
1721
  curQuery +=
1102
1722
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1103
- ieTable +
1104
- '.`guid` IN (SELECT `guid` FROM ' +
1105
- MySQLDriver.escape(this.prefix + 'data_' + etype) +
1106
- ' WHERE `name`=@' +
1107
- name +
1108
- ' AND INSTR(`value`, @' +
1109
- value +
1110
- '))';
1723
+ '(' +
1724
+ termStrings.join(' AND ') +
1725
+ ')';
1726
+
1727
+ params[name] = curValue[0];
1111
1728
  }
1112
- params[name] = curValue[0];
1113
- params[value] = svalue;
1114
1729
  }
1115
1730
  break;
1116
1731
  case 'match':
1117
1732
  case '!match':
1118
- if (curValue[0] === 'cdate') {
1733
+ if (
1734
+ curValue[0] === 'cdate' ||
1735
+ curValue[0] === 'mdate' ||
1736
+ (this.nymph.tilmeld != null &&
1737
+ (curValue[0] === 'user' ||
1738
+ curValue[0] === 'group' ||
1739
+ curValue[0] === 'acUser' ||
1740
+ curValue[0] === 'acGroup' ||
1741
+ curValue[0] === 'acOther' ||
1742
+ curValue[0] === 'acRead' ||
1743
+ curValue[0] === 'acWrite' ||
1744
+ curValue[0] === 'acFull'))
1745
+ ) {
1119
1746
  if (curQuery) {
1120
1747
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1121
1748
  }
1122
- const cdate = `param${++count.i}`;
1123
- curQuery +=
1124
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1125
- '(' +
1126
- ieTable +
1127
- '.`cdate` REGEXP @' +
1128
- cdate +
1129
- ')';
1130
- params[cdate] = curValue[1];
1131
- break;
1132
- } else if (curValue[0] === 'mdate') {
1133
- if (curQuery) {
1134
- curQuery += typeIsOr ? ' OR ' : ' AND ';
1135
- }
1136
- const mdate = `param${++count.i}`;
1749
+ const value = `param${++count.i}`;
1137
1750
  curQuery +=
1138
1751
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1139
1752
  '(' +
1140
1753
  ieTable +
1141
- '.`mdate` REGEXP @' +
1142
- mdate +
1754
+ '.' +
1755
+ MySQLDriver.escape(curValue[0]) +
1756
+ ' REGEXP @' +
1757
+ value +
1143
1758
  ')';
1144
- params[mdate] = curValue[1];
1145
- break;
1759
+ params[value] = curValue[1];
1146
1760
  } else {
1147
1761
  if (curQuery) {
1148
1762
  curQuery += typeIsOr ? ' OR ' : ' AND ';
@@ -1151,10 +1765,11 @@ export default class MySQLDriver extends NymphDriver {
1151
1765
  const value = `param${++count.i}`;
1152
1766
  curQuery +=
1153
1767
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1768
+ 'EXISTS (SELECT `guid` FROM ' +
1769
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1770
+ ' WHERE `guid`=' +
1154
1771
  ieTable +
1155
- '.`guid` IN (SELECT `guid` FROM ' +
1156
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1157
- ' WHERE `name`=@' +
1772
+ '.`guid` AND `name`=@' +
1158
1773
  name +
1159
1774
  ' AND `string` REGEXP @' +
1160
1775
  value +
@@ -1165,34 +1780,33 @@ export default class MySQLDriver extends NymphDriver {
1165
1780
  break;
1166
1781
  case 'imatch':
1167
1782
  case '!imatch':
1168
- if (curValue[0] === 'cdate') {
1783
+ if (
1784
+ curValue[0] === 'cdate' ||
1785
+ curValue[0] === 'mdate' ||
1786
+ (this.nymph.tilmeld != null &&
1787
+ (curValue[0] === 'user' ||
1788
+ curValue[0] === 'group' ||
1789
+ curValue[0] === 'acUser' ||
1790
+ curValue[0] === 'acGroup' ||
1791
+ curValue[0] === 'acOther' ||
1792
+ curValue[0] === 'acRead' ||
1793
+ curValue[0] === 'acWrite' ||
1794
+ curValue[0] === 'acFull'))
1795
+ ) {
1169
1796
  if (curQuery) {
1170
1797
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1171
1798
  }
1172
- const cdate = `param${++count.i}`;
1173
- curQuery +=
1174
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1175
- '(' +
1176
- ieTable +
1177
- '.`cdate` REGEXP @' +
1178
- cdate +
1179
- ')';
1180
- params[cdate] = curValue[1];
1181
- break;
1182
- } else if (curValue[0] === 'mdate') {
1183
- if (curQuery) {
1184
- curQuery += typeIsOr ? ' OR ' : ' AND ';
1185
- }
1186
- const mdate = `param${++count.i}`;
1799
+ const value = `param${++count.i}`;
1187
1800
  curQuery +=
1188
1801
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1189
1802
  '(' +
1190
1803
  ieTable +
1191
- '.`mdate` REGEXP @' +
1192
- mdate +
1804
+ '.' +
1805
+ MySQLDriver.escape(curValue[0]) +
1806
+ ' REGEXP @' +
1807
+ value +
1193
1808
  ')';
1194
- params[mdate] = curValue[1];
1195
- break;
1809
+ params[value] = curValue[1];
1196
1810
  } else {
1197
1811
  if (curQuery) {
1198
1812
  curQuery += typeIsOr ? ' OR ' : ' AND ';
@@ -1201,10 +1815,11 @@ export default class MySQLDriver extends NymphDriver {
1201
1815
  const value = `param${++count.i}`;
1202
1816
  curQuery +=
1203
1817
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1818
+ 'EXISTS (SELECT `guid` FROM ' +
1819
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1820
+ ' WHERE `guid`=' +
1204
1821
  ieTable +
1205
- '.`guid` IN (SELECT `guid` FROM ' +
1206
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1207
- ' WHERE `name`=@' +
1822
+ '.`guid` AND `name`=@' +
1208
1823
  name +
1209
1824
  ' AND LOWER(`string`) REGEXP LOWER(@' +
1210
1825
  value +
@@ -1215,34 +1830,33 @@ export default class MySQLDriver extends NymphDriver {
1215
1830
  break;
1216
1831
  case 'like':
1217
1832
  case '!like':
1218
- if (curValue[0] === 'cdate') {
1219
- if (curQuery) {
1220
- curQuery += typeIsOr ? ' OR ' : ' AND ';
1221
- }
1222
- const cdate = `param${++count.i}`;
1223
- curQuery +=
1224
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1225
- '(' +
1226
- ieTable +
1227
- '.`cdate` LIKE @' +
1228
- cdate +
1229
- ')';
1230
- params[cdate] = curValue[1];
1231
- break;
1232
- } else if (curValue[0] === 'mdate') {
1833
+ if (
1834
+ curValue[0] === 'cdate' ||
1835
+ curValue[0] === 'mdate' ||
1836
+ (this.nymph.tilmeld != null &&
1837
+ (curValue[0] === 'user' ||
1838
+ curValue[0] === 'group' ||
1839
+ curValue[0] === 'acUser' ||
1840
+ curValue[0] === 'acGroup' ||
1841
+ curValue[0] === 'acOther' ||
1842
+ curValue[0] === 'acRead' ||
1843
+ curValue[0] === 'acWrite' ||
1844
+ curValue[0] === 'acFull'))
1845
+ ) {
1233
1846
  if (curQuery) {
1234
1847
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1235
1848
  }
1236
- const mdate = `param${++count.i}`;
1849
+ const value = `param${++count.i}`;
1237
1850
  curQuery +=
1238
1851
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1239
1852
  '(' +
1240
1853
  ieTable +
1241
- '.`mdate` LIKE @' +
1242
- mdate +
1854
+ '.' +
1855
+ MySQLDriver.escape(curValue[0]) +
1856
+ ' LIKE @' +
1857
+ value +
1243
1858
  ')';
1244
- params[mdate] = curValue[1];
1245
- break;
1859
+ params[value] = curValue[1];
1246
1860
  } else {
1247
1861
  if (curQuery) {
1248
1862
  curQuery += typeIsOr ? ' OR ' : ' AND ';
@@ -1251,10 +1865,11 @@ export default class MySQLDriver extends NymphDriver {
1251
1865
  const value = `param${++count.i}`;
1252
1866
  curQuery +=
1253
1867
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1868
+ 'EXISTS (SELECT `guid` FROM ' +
1869
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1870
+ ' WHERE `guid`=' +
1254
1871
  ieTable +
1255
- '.`guid` IN (SELECT `guid` FROM ' +
1256
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1257
- ' WHERE `name`=@' +
1872
+ '.`guid` AND `name`=@' +
1258
1873
  name +
1259
1874
  ' AND `string` LIKE @' +
1260
1875
  value +
@@ -1265,34 +1880,33 @@ export default class MySQLDriver extends NymphDriver {
1265
1880
  break;
1266
1881
  case 'ilike':
1267
1882
  case '!ilike':
1268
- if (curValue[0] === 'cdate') {
1269
- if (curQuery) {
1270
- curQuery += typeIsOr ? ' OR ' : ' AND ';
1271
- }
1272
- const cdate = `param${++count.i}`;
1273
- curQuery +=
1274
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1275
- '(' +
1276
- ieTable +
1277
- '.`cdate` LIKE @' +
1278
- cdate +
1279
- ')';
1280
- params[cdate] = curValue[1];
1281
- break;
1282
- } else if (curValue[0] === 'mdate') {
1883
+ if (
1884
+ curValue[0] === 'cdate' ||
1885
+ curValue[0] === 'mdate' ||
1886
+ (this.nymph.tilmeld != null &&
1887
+ (curValue[0] === 'user' ||
1888
+ curValue[0] === 'group' ||
1889
+ curValue[0] === 'acUser' ||
1890
+ curValue[0] === 'acGroup' ||
1891
+ curValue[0] === 'acOther' ||
1892
+ curValue[0] === 'acRead' ||
1893
+ curValue[0] === 'acWrite' ||
1894
+ curValue[0] === 'acFull'))
1895
+ ) {
1283
1896
  if (curQuery) {
1284
1897
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1285
1898
  }
1286
- const mdate = `param${++count.i}`;
1899
+ const value = `param${++count.i}`;
1287
1900
  curQuery +=
1288
1901
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1289
1902
  '(' +
1290
1903
  ieTable +
1291
- '.`mdate` LIKE @' +
1292
- mdate +
1904
+ '.' +
1905
+ MySQLDriver.escape(curValue[0]) +
1906
+ ' LIKE @' +
1907
+ value +
1293
1908
  ')';
1294
- params[mdate] = curValue[1];
1295
- break;
1909
+ params[value] = curValue[1];
1296
1910
  } else {
1297
1911
  if (curQuery) {
1298
1912
  curQuery += typeIsOr ? ' OR ' : ' AND ';
@@ -1301,10 +1915,11 @@ export default class MySQLDriver extends NymphDriver {
1301
1915
  const value = `param${++count.i}`;
1302
1916
  curQuery +=
1303
1917
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1918
+ 'EXISTS (SELECT `guid` FROM ' +
1919
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1920
+ ' WHERE `guid`=' +
1304
1921
  ieTable +
1305
- '.`guid` IN (SELECT `guid` FROM ' +
1306
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1307
- ' WHERE `name`=@' +
1922
+ '.`guid` AND `name`=@' +
1308
1923
  name +
1309
1924
  ' AND LOWER(`string`) LIKE LOWER(@' +
1310
1925
  value +
@@ -1315,34 +1930,33 @@ export default class MySQLDriver extends NymphDriver {
1315
1930
  break;
1316
1931
  case 'gt':
1317
1932
  case '!gt':
1318
- if (curValue[0] === 'cdate') {
1933
+ if (
1934
+ curValue[0] === 'cdate' ||
1935
+ curValue[0] === 'mdate' ||
1936
+ (this.nymph.tilmeld != null &&
1937
+ (curValue[0] === 'user' ||
1938
+ curValue[0] === 'group' ||
1939
+ curValue[0] === 'acUser' ||
1940
+ curValue[0] === 'acGroup' ||
1941
+ curValue[0] === 'acOther' ||
1942
+ curValue[0] === 'acRead' ||
1943
+ curValue[0] === 'acWrite' ||
1944
+ curValue[0] === 'acFull'))
1945
+ ) {
1319
1946
  if (curQuery) {
1320
1947
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1321
1948
  }
1322
- const cdate = `param${++count.i}`;
1323
- curQuery +=
1324
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1325
- ieTable +
1326
- '.`cdate`>@' +
1327
- cdate;
1328
- params[cdate] = isNaN(Number(curValue[1]))
1329
- ? null
1330
- : Number(curValue[1]);
1331
- break;
1332
- } else if (curValue[0] === 'mdate') {
1333
- if (curQuery) {
1334
- curQuery += typeIsOr ? ' OR ' : ' AND ';
1335
- }
1336
- const mdate = `param${++count.i}`;
1949
+ const value = `param${++count.i}`;
1337
1950
  curQuery +=
1338
1951
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1339
1952
  ieTable +
1340
- '.`mdate`>@' +
1341
- mdate;
1342
- params[mdate] = isNaN(Number(curValue[1]))
1953
+ '.' +
1954
+ MySQLDriver.escape(curValue[0]) +
1955
+ '>@' +
1956
+ value;
1957
+ params[value] = isNaN(Number(curValue[1]))
1343
1958
  ? null
1344
1959
  : Number(curValue[1]);
1345
- break;
1346
1960
  } else {
1347
1961
  if (curQuery) {
1348
1962
  curQuery += typeIsOr ? ' OR ' : ' AND ';
@@ -1351,10 +1965,11 @@ export default class MySQLDriver extends NymphDriver {
1351
1965
  const value = `param${++count.i}`;
1352
1966
  curQuery +=
1353
1967
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1968
+ 'EXISTS (SELECT `guid` FROM ' +
1969
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
1970
+ ' WHERE `guid`=' +
1354
1971
  ieTable +
1355
- '.`guid` IN (SELECT `guid` FROM ' +
1356
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1357
- ' WHERE `name`=@' +
1972
+ '.`guid` AND `name`=@' +
1358
1973
  name +
1359
1974
  ' AND `number`>@' +
1360
1975
  value +
@@ -1367,34 +1982,33 @@ export default class MySQLDriver extends NymphDriver {
1367
1982
  break;
1368
1983
  case 'gte':
1369
1984
  case '!gte':
1370
- if (curValue[0] === 'cdate') {
1371
- if (curQuery) {
1372
- curQuery += typeIsOr ? ' OR ' : ' AND ';
1373
- }
1374
- const cdate = `param${++count.i}`;
1375
- curQuery +=
1376
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1377
- ieTable +
1378
- '.`cdate`>=@' +
1379
- cdate;
1380
- params[cdate] = isNaN(Number(curValue[1]))
1381
- ? null
1382
- : Number(curValue[1]);
1383
- break;
1384
- } else if (curValue[0] === 'mdate') {
1985
+ if (
1986
+ curValue[0] === 'cdate' ||
1987
+ curValue[0] === 'mdate' ||
1988
+ (this.nymph.tilmeld != null &&
1989
+ (curValue[0] === 'user' ||
1990
+ curValue[0] === 'group' ||
1991
+ curValue[0] === 'acUser' ||
1992
+ curValue[0] === 'acGroup' ||
1993
+ curValue[0] === 'acOther' ||
1994
+ curValue[0] === 'acRead' ||
1995
+ curValue[0] === 'acWrite' ||
1996
+ curValue[0] === 'acFull'))
1997
+ ) {
1385
1998
  if (curQuery) {
1386
1999
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1387
2000
  }
1388
- const mdate = `param${++count.i}`;
2001
+ const value = `param${++count.i}`;
1389
2002
  curQuery +=
1390
2003
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1391
2004
  ieTable +
1392
- '.`mdate`>=@' +
1393
- mdate;
1394
- params[mdate] = isNaN(Number(curValue[1]))
2005
+ '.' +
2006
+ MySQLDriver.escape(curValue[0]) +
2007
+ '>=@' +
2008
+ value;
2009
+ params[value] = isNaN(Number(curValue[1]))
1395
2010
  ? null
1396
2011
  : Number(curValue[1]);
1397
- break;
1398
2012
  } else {
1399
2013
  if (curQuery) {
1400
2014
  curQuery += typeIsOr ? ' OR ' : ' AND ';
@@ -1403,10 +2017,11 @@ export default class MySQLDriver extends NymphDriver {
1403
2017
  const value = `param${++count.i}`;
1404
2018
  curQuery +=
1405
2019
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
2020
+ 'EXISTS (SELECT `guid` FROM ' +
2021
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
2022
+ ' WHERE `guid`=' +
1406
2023
  ieTable +
1407
- '.`guid` IN (SELECT `guid` FROM ' +
1408
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1409
- ' WHERE `name`=@' +
2024
+ '.`guid` AND `name`=@' +
1410
2025
  name +
1411
2026
  ' AND `number`>=@' +
1412
2027
  value +
@@ -1417,36 +2032,35 @@ export default class MySQLDriver extends NymphDriver {
1417
2032
  : Number(curValue[1]);
1418
2033
  }
1419
2034
  break;
1420
- case 'lt':
1421
- case '!lt':
1422
- if (curValue[0] === 'cdate') {
1423
- if (curQuery) {
1424
- curQuery += typeIsOr ? ' OR ' : ' AND ';
1425
- }
1426
- const cdate = `param${++count.i}`;
1427
- curQuery +=
1428
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1429
- ieTable +
1430
- '.`cdate`<@' +
1431
- cdate;
1432
- params[cdate] = isNaN(Number(curValue[1]))
1433
- ? null
1434
- : Number(curValue[1]);
1435
- break;
1436
- } else if (curValue[0] === 'mdate') {
2035
+ case 'lt':
2036
+ case '!lt':
2037
+ if (
2038
+ curValue[0] === 'cdate' ||
2039
+ curValue[0] === 'mdate' ||
2040
+ (this.nymph.tilmeld != null &&
2041
+ (curValue[0] === 'user' ||
2042
+ curValue[0] === 'group' ||
2043
+ curValue[0] === 'acUser' ||
2044
+ curValue[0] === 'acGroup' ||
2045
+ curValue[0] === 'acOther' ||
2046
+ curValue[0] === 'acRead' ||
2047
+ curValue[0] === 'acWrite' ||
2048
+ curValue[0] === 'acFull'))
2049
+ ) {
1437
2050
  if (curQuery) {
1438
2051
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1439
2052
  }
1440
- const mdate = `param${++count.i}`;
2053
+ const value = `param${++count.i}`;
1441
2054
  curQuery +=
1442
2055
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1443
2056
  ieTable +
1444
- '.`mdate`<@' +
1445
- mdate;
1446
- params[mdate] = isNaN(Number(curValue[1]))
2057
+ '.' +
2058
+ MySQLDriver.escape(curValue[0]) +
2059
+ '<@' +
2060
+ value;
2061
+ params[value] = isNaN(Number(curValue[1]))
1447
2062
  ? null
1448
2063
  : Number(curValue[1]);
1449
- break;
1450
2064
  } else {
1451
2065
  if (curQuery) {
1452
2066
  curQuery += typeIsOr ? ' OR ' : ' AND ';
@@ -1455,10 +2069,11 @@ export default class MySQLDriver extends NymphDriver {
1455
2069
  const value = `param${++count.i}`;
1456
2070
  curQuery +=
1457
2071
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
2072
+ 'EXISTS (SELECT `guid` FROM ' +
2073
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
2074
+ ' WHERE `guid`=' +
1458
2075
  ieTable +
1459
- '.`guid` IN (SELECT `guid` FROM ' +
1460
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1461
- ' WHERE `name`=@' +
2076
+ '.`guid` AND `name`=@' +
1462
2077
  name +
1463
2078
  ' AND `number`<@' +
1464
2079
  value +
@@ -1471,34 +2086,33 @@ export default class MySQLDriver extends NymphDriver {
1471
2086
  break;
1472
2087
  case 'lte':
1473
2088
  case '!lte':
1474
- if (curValue[0] === 'cdate') {
1475
- if (curQuery) {
1476
- curQuery += typeIsOr ? ' OR ' : ' AND ';
1477
- }
1478
- const cdate = `param${++count.i}`;
1479
- curQuery +=
1480
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1481
- ieTable +
1482
- '.`cdate`<=@' +
1483
- cdate;
1484
- params[cdate] = isNaN(Number(curValue[1]))
1485
- ? null
1486
- : Number(curValue[1]);
1487
- break;
1488
- } else if (curValue[0] === 'mdate') {
2089
+ if (
2090
+ curValue[0] === 'cdate' ||
2091
+ curValue[0] === 'mdate' ||
2092
+ (this.nymph.tilmeld != null &&
2093
+ (curValue[0] === 'user' ||
2094
+ curValue[0] === 'group' ||
2095
+ curValue[0] === 'acUser' ||
2096
+ curValue[0] === 'acGroup' ||
2097
+ curValue[0] === 'acOther' ||
2098
+ curValue[0] === 'acRead' ||
2099
+ curValue[0] === 'acWrite' ||
2100
+ curValue[0] === 'acFull'))
2101
+ ) {
1489
2102
  if (curQuery) {
1490
2103
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1491
2104
  }
1492
- const mdate = `param${++count.i}`;
2105
+ const value = `param${++count.i}`;
1493
2106
  curQuery +=
1494
2107
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1495
2108
  ieTable +
1496
- '.`mdate`<=@' +
1497
- mdate;
1498
- params[mdate] = isNaN(Number(curValue[1]))
2109
+ '.' +
2110
+ MySQLDriver.escape(curValue[0]) +
2111
+ '<=@' +
2112
+ value;
2113
+ params[value] = isNaN(Number(curValue[1]))
1499
2114
  ? null
1500
2115
  : Number(curValue[1]);
1501
- break;
1502
2116
  } else {
1503
2117
  if (curQuery) {
1504
2118
  curQuery += typeIsOr ? ' OR ' : ' AND ';
@@ -1507,10 +2121,11 @@ export default class MySQLDriver extends NymphDriver {
1507
2121
  const value = `param${++count.i}`;
1508
2122
  curQuery +=
1509
2123
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
2124
+ 'EXISTS (SELECT `guid` FROM ' +
2125
+ MySQLDriver.escape(this.prefix + 'data_' + etype) +
2126
+ ' WHERE `guid`=' +
1510
2127
  ieTable +
1511
- '.`guid` IN (SELECT `guid` FROM ' +
1512
- MySQLDriver.escape(this.prefix + 'comparisons_' + etype) +
1513
- ' WHERE `name`=@' +
2128
+ '.`guid` AND `name`=@' +
1514
2129
  name +
1515
2130
  ' AND `number`<=@' +
1516
2131
  value +
@@ -1534,32 +2149,66 @@ export default class MySQLDriver extends NymphDriver {
1534
2149
  if (curQuery) {
1535
2150
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1536
2151
  }
1537
- const name = `param${++count.i}`;
1538
- const guid = `param${++count.i}`;
1539
- curQuery +=
1540
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1541
- ieTable +
1542
- '.`guid` IN (SELECT `guid` FROM ' +
1543
- MySQLDriver.escape(this.prefix + 'references_' + etype) +
1544
- ' WHERE `name`=@' +
1545
- name +
1546
- ' AND `reference`=UNHEX(@' +
1547
- guid +
1548
- '))';
1549
- params[name] = curValue[0];
1550
- params[guid] = curQguid;
2152
+ if (
2153
+ this.nymph.tilmeld != null &&
2154
+ (curValue[0] === 'user' || curValue[0] === 'group')
2155
+ ) {
2156
+ const guid = `param${++count.i}`;
2157
+ curQuery +=
2158
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
2159
+ ieTable +
2160
+ '.' +
2161
+ MySQLDriver.escape(curValue[0]) +
2162
+ '=UNHEX(@' +
2163
+ guid +
2164
+ ')';
2165
+ params[guid] = curQguid;
2166
+ } else if (
2167
+ this.nymph.tilmeld != null &&
2168
+ (curValue[0] === 'acRead' ||
2169
+ curValue[0] === 'acWrite' ||
2170
+ curValue[0] === 'acFull')
2171
+ ) {
2172
+ const queryParam = `param${++count.i}`;
2173
+ curQuery +=
2174
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
2175
+ 'MATCH (' +
2176
+ ieTable +
2177
+ '.' +
2178
+ MySQLDriver.escape(curValue[0]) +
2179
+ ') AGAINST (@' +
2180
+ queryParam +
2181
+ ' IN BOOLEAN MODE)';
2182
+ params[queryParam] = '+' + curQguid;
2183
+ } else {
2184
+ const name = `param${++count.i}`;
2185
+ const guid = `param${++count.i}`;
2186
+ curQuery +=
2187
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
2188
+ 'EXISTS (SELECT `guid` FROM ' +
2189
+ MySQLDriver.escape(this.prefix + 'references_' + etype) +
2190
+ ' WHERE `guid`=' +
2191
+ ieTable +
2192
+ '.`guid` AND `name`=@' +
2193
+ name +
2194
+ ' AND `reference`=UNHEX(@' +
2195
+ guid +
2196
+ '))';
2197
+ params[name] = curValue[0];
2198
+ params[guid] = curQguid;
2199
+ }
1551
2200
  break;
1552
2201
  case 'selector':
1553
2202
  case '!selector':
1554
- const subquery = this.makeEntityQuery(
1555
- options,
2203
+ const innerquery = this.makeEntityQuery(
2204
+ { ...options, sort: null, limit: undefined },
1556
2205
  [curValue],
1557
2206
  etype,
1558
2207
  count,
1559
2208
  params,
1560
2209
  true,
1561
2210
  tableSuffix,
1562
- etypes
2211
+ etypes,
1563
2212
  );
1564
2213
  if (curQuery) {
1565
2214
  curQuery += typeIsOr ? ' OR ' : ' AND ';
@@ -1567,61 +2216,174 @@ export default class MySQLDriver extends NymphDriver {
1567
2216
  curQuery +=
1568
2217
  (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1569
2218
  '(' +
1570
- subquery.query +
2219
+ innerquery.query +
1571
2220
  ')';
1572
2221
  break;
1573
2222
  case 'qref':
1574
2223
  case '!qref':
2224
+ const referenceTableSuffix = makeTableSuffix();
1575
2225
  const [qrefOptions, ...qrefSelectors] = curValue[1] as [
1576
2226
  Options,
1577
- ...FormattedSelector[]
2227
+ ...FormattedSelector[],
1578
2228
  ];
1579
2229
  const QrefEntityClass = qrefOptions.class as EntityConstructor;
1580
2230
  etypes.push(QrefEntityClass.ETYPE);
1581
- const qrefQuery = this.makeEntityQuery(
1582
- { ...qrefOptions, return: 'guid', class: QrefEntityClass },
1583
- qrefSelectors,
1584
- QrefEntityClass.ETYPE,
1585
- count,
1586
- params,
1587
- false,
1588
- makeTableSuffix(),
1589
- etypes
1590
- );
1591
2231
  if (curQuery) {
1592
2232
  curQuery += typeIsOr ? ' OR ' : ' AND ';
1593
2233
  }
1594
- const qrefName = `param${++count.i}`;
1595
- curQuery +=
1596
- (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
1597
- ieTable +
1598
- '.`guid` IN (SELECT `guid` FROM ' +
1599
- MySQLDriver.escape(this.prefix + 'references_' + etype) +
1600
- ' WHERE `name`=@' +
1601
- qrefName +
1602
- ' AND `reference` IN (' +
1603
- qrefQuery.query +
1604
- '))';
1605
- params[qrefName] = curValue[0];
2234
+ if (
2235
+ this.nymph.tilmeld != null &&
2236
+ (curValue[0] === 'user' || curValue[0] === 'group')
2237
+ ) {
2238
+ const qrefQuery = this.makeEntityQuery(
2239
+ {
2240
+ ...qrefOptions,
2241
+ sort: qrefOptions.sort ?? null,
2242
+ return: 'guid',
2243
+ class: QrefEntityClass,
2244
+ },
2245
+ qrefSelectors,
2246
+ QrefEntityClass.ETYPE,
2247
+ count,
2248
+ params,
2249
+ false,
2250
+ makeTableSuffix(),
2251
+ etypes,
2252
+ 'r' +
2253
+ referenceTableSuffix +
2254
+ '.' +
2255
+ MySQLDriver.escape(curValue[0]),
2256
+ );
2257
+
2258
+ curQuery +=
2259
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
2260
+ 'EXISTS (SELECT `guid` FROM ' +
2261
+ MySQLDriver.escape(this.prefix + 'entities_' + etype) +
2262
+ ' r' +
2263
+ referenceTableSuffix +
2264
+ ' WHERE r' +
2265
+ referenceTableSuffix +
2266
+ '.`guid`=' +
2267
+ ieTable +
2268
+ '.`guid` AND EXISTS (' +
2269
+ qrefQuery.query +
2270
+ '))';
2271
+ } else if (
2272
+ this.nymph.tilmeld != null &&
2273
+ (curValue[0] === 'acRead' ||
2274
+ curValue[0] === 'acWrite' ||
2275
+ curValue[0] === 'acFull')
2276
+ ) {
2277
+ const qrefQuery = this.makeEntityQuery(
2278
+ {
2279
+ ...qrefOptions,
2280
+ sort: qrefOptions.sort ?? null,
2281
+ return: 'guid',
2282
+ class: QrefEntityClass,
2283
+ },
2284
+ qrefSelectors,
2285
+ QrefEntityClass.ETYPE,
2286
+ count,
2287
+ params,
2288
+ false,
2289
+ makeTableSuffix(),
2290
+ etypes,
2291
+ undefined,
2292
+ (guid) =>
2293
+ ieTable +
2294
+ '.' +
2295
+ MySQLDriver.escape(curValue[0]) +
2296
+ " LIKE CONCAT('% ', LOWER(HEX(" +
2297
+ guid +
2298
+ ")), ' %')",
2299
+ );
2300
+
2301
+ curQuery +=
2302
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
2303
+ 'EXISTS (' +
2304
+ qrefQuery.query +
2305
+ ')';
2306
+ } else {
2307
+ const qrefQuery = this.makeEntityQuery(
2308
+ {
2309
+ ...qrefOptions,
2310
+ sort: qrefOptions.sort ?? null,
2311
+ return: 'guid',
2312
+ class: QrefEntityClass,
2313
+ },
2314
+ qrefSelectors,
2315
+ QrefEntityClass.ETYPE,
2316
+ count,
2317
+ params,
2318
+ false,
2319
+ makeTableSuffix(),
2320
+ etypes,
2321
+ 'r' + referenceTableSuffix + '.`reference`',
2322
+ );
2323
+ const qrefName = `param${++count.i}`;
2324
+ curQuery +=
2325
+ (xor(typeIsNot, clauseNot) ? 'NOT ' : '') +
2326
+ 'EXISTS (SELECT `guid` FROM ' +
2327
+ MySQLDriver.escape(this.prefix + 'references_' + etype) +
2328
+ ' r' +
2329
+ referenceTableSuffix +
2330
+ ' WHERE r' +
2331
+ referenceTableSuffix +
2332
+ '.`guid`=' +
2333
+ ieTable +
2334
+ '.`guid` AND r' +
2335
+ referenceTableSuffix +
2336
+ '.`name`=@' +
2337
+ qrefName +
2338
+ ' AND EXISTS (' +
2339
+ qrefQuery.query +
2340
+ '))';
2341
+ params[qrefName] = curValue[0];
2342
+ }
1606
2343
  break;
1607
2344
  }
1608
2345
  }
1609
2346
  return curQuery;
1610
- }
2347
+ },
1611
2348
  );
1612
2349
 
1613
2350
  let sortBy: string;
1614
- switch (sort) {
1615
- case 'mdate':
1616
- sortBy = '`mdate`';
1617
- break;
1618
- case 'cdate':
1619
- default:
1620
- sortBy = '`cdate`';
1621
- break;
1622
- }
1623
- if (options.reverse) {
1624
- sortBy += ' DESC';
2351
+ let sortByInner: string;
2352
+ let sortJoin = '';
2353
+ let sortJoinInner = '';
2354
+ const order = options.reverse ? ' DESC' : '';
2355
+ if (sort == null) {
2356
+ sortBy = '';
2357
+ sortByInner = '';
2358
+ } else {
2359
+ switch (sort) {
2360
+ case 'mdate':
2361
+ sortBy = `ORDER BY ${eTable}.\`mdate\`${order}`;
2362
+ sortByInner = `ORDER BY ${ieTable}.\`mdate\`${order}`;
2363
+ break;
2364
+ case 'cdate':
2365
+ sortBy = `ORDER BY ${eTable}.\`cdate\`${order}`;
2366
+ sortByInner = `ORDER BY ${ieTable}.\`cdate\`${order}`;
2367
+ break;
2368
+ default:
2369
+ const name = `param${++count.i}`;
2370
+ sortJoin = `LEFT JOIN (
2371
+ SELECT \`guid\`, \`string\`, \`number\`
2372
+ FROM ${MySQLDriver.escape(this.prefix + 'data_' + etype)}
2373
+ WHERE \`name\`=@${name}
2374
+ ORDER BY \`number\`${order}, \`string\`${order}
2375
+ ) ${sTable} ON ${eTable}.\`guid\`=${sTable}.\`guid\``;
2376
+ sortJoinInner = `LEFT JOIN (
2377
+ SELECT \`guid\`, \`string\`, \`number\`
2378
+ FROM ${MySQLDriver.escape(this.prefix + 'data_' + etype)}
2379
+ WHERE \`name\`=@${name}
2380
+ ORDER BY \`number\`${order}, \`string\`${order}
2381
+ ) ${sTable} ON ${ieTable}.\`guid\`=${sTable}.\`guid\``;
2382
+ sortBy = `ORDER BY ${sTable}.\`number\`${order}, ${sTable}.\`string\`${order}`;
2383
+ sortByInner = sortBy;
2384
+ params[name] = sort;
2385
+ break;
2386
+ }
1625
2387
  }
1626
2388
 
1627
2389
  let query: string;
@@ -1632,31 +2394,36 @@ export default class MySQLDriver extends NymphDriver {
1632
2394
  let limit = '';
1633
2395
  if ('limit' in options) {
1634
2396
  limit = ` LIMIT ${Math.floor(
1635
- isNaN(Number(options.limit)) ? 0 : Number(options.limit)
2397
+ isNaN(Number(options.limit)) ? 0 : Number(options.limit),
1636
2398
  )}`;
1637
2399
  }
1638
2400
  let offset = '';
1639
2401
  if ('offset' in options) {
1640
2402
  offset = ` OFFSET ${Math.floor(
1641
- isNaN(Number(options.offset)) ? 0 : Number(options.offset)
2403
+ isNaN(Number(options.offset)) ? 0 : Number(options.offset),
1642
2404
  )}`;
1643
2405
  }
1644
2406
  const whereClause = queryParts.join(') AND (');
2407
+ const guidClause = guidExplicitSelector
2408
+ ? `${guidExplicitSelector(`${ieTable}.\`guid\``)} AND `
2409
+ : guidSelector
2410
+ ? `${ieTable}.\`guid\`=${guidSelector} AND `
2411
+ : '';
1645
2412
  if (options.return === 'count') {
1646
2413
  if (limit || offset) {
1647
2414
  query = `SELECT COUNT(${countTable}.\`guid\`) AS \`count\` FROM (
1648
2415
  SELECT ${ieTable}.\`guid\` AS \`guid\`
1649
2416
  FROM ${MySQLDriver.escape(
1650
- `${this.prefix}entities_${etype}`
2417
+ `${this.prefix}entities_${etype}`,
1651
2418
  )} ${ieTable}
1652
- WHERE (${whereClause})${limit}${offset}
2419
+ WHERE ${guidClause}(${whereClause})${limit}${offset}
1653
2420
  ) ${countTable}`;
1654
2421
  } else {
1655
2422
  query = `SELECT COUNT(${ieTable}.\`guid\`) AS \`count\`
1656
2423
  FROM ${MySQLDriver.escape(
1657
- `${this.prefix}entities_${etype}`
2424
+ `${this.prefix}entities_${etype}`,
1658
2425
  )} ${ieTable}
1659
- WHERE (${whereClause})`;
2426
+ WHERE ${guidClause}(${whereClause})`;
1660
2427
  }
1661
2428
  } else if (options.return === 'guid') {
1662
2429
  const guidColumn =
@@ -1665,38 +2432,47 @@ export default class MySQLDriver extends NymphDriver {
1665
2432
  : `${ieTable}.\`guid\``;
1666
2433
  query = `SELECT ${guidColumn} AS \`guid\`
1667
2434
  FROM ${MySQLDriver.escape(
1668
- `${this.prefix}entities_${etype}`
2435
+ `${this.prefix}entities_${etype}`,
1669
2436
  )} ${ieTable}
1670
- WHERE (${whereClause})
1671
- ORDER BY ${ieTable}.${sortBy}${limit}${offset}`;
2437
+ ${sortJoinInner}
2438
+ WHERE ${guidClause}(${whereClause})
2439
+ ${sortByInner ? sortByInner + ', ' : 'ORDER BY '}${ieTable}.\`guid\`${limit}${offset}`;
1672
2440
  } else {
1673
2441
  query = `SELECT
1674
2442
  LOWER(HEX(${eTable}.\`guid\`)) AS \`guid\`,
1675
2443
  ${eTable}.\`tags\`,
1676
2444
  ${eTable}.\`cdate\`,
1677
2445
  ${eTable}.\`mdate\`,
2446
+ LOWER(HEX(${eTable}.\`user\`)) AS \`user\`,
2447
+ LOWER(HEX(${eTable}.\`group\`)) AS \`group\`,
2448
+ ${eTable}.\`acUser\`,
2449
+ ${eTable}.\`acGroup\`,
2450
+ ${eTable}.\`acOther\`,
2451
+ ${eTable}.\`acRead\`,
2452
+ ${eTable}.\`acWrite\`,
2453
+ ${eTable}.\`acFull\`,
1678
2454
  ${dTable}.\`name\`,
1679
2455
  ${dTable}.\`value\`,
1680
- ${cTable}.\`string\`,
1681
- ${cTable}.\`number\`
2456
+ ${dTable}.\`json\`,
2457
+ ${dTable}.\`string\`,
2458
+ ${dTable}.\`number\`
1682
2459
  FROM ${MySQLDriver.escape(
1683
- `${this.prefix}entities_${etype}`
2460
+ `${this.prefix}entities_${etype}`,
1684
2461
  )} ${eTable}
1685
2462
  LEFT JOIN ${MySQLDriver.escape(
1686
- `${this.prefix}data_${etype}`
2463
+ `${this.prefix}data_${etype}`,
1687
2464
  )} ${dTable} ON ${eTable}.\`guid\`=${dTable}.\`guid\`
1688
- INNER JOIN ${MySQLDriver.escape(
1689
- `${this.prefix}comparisons_${etype}`
1690
- )} ${cTable} ON ${dTable}.\`guid\`=${cTable}.\`guid\` AND ${dTable}.\`name\`=${cTable}.\`name\`
2465
+ ${sortJoin}
1691
2466
  INNER JOIN (
1692
2467
  SELECT ${ieTable}.\`guid\`
1693
2468
  FROM ${MySQLDriver.escape(
1694
- `${this.prefix}entities_${etype}`
2469
+ `${this.prefix}entities_${etype}`,
1695
2470
  )} ${ieTable}
1696
- WHERE (${whereClause})
1697
- ORDER BY ${ieTable}.${sortBy}${limit}${offset}
2471
+ ${sortJoinInner}
2472
+ WHERE ${guidClause}(${whereClause})
2473
+ ${sortByInner}${limit}${offset}
1698
2474
  ) ${fTable} ON ${eTable}.\`guid\`=${fTable}.\`guid\`
1699
- ORDER BY ${eTable}.${sortBy}`;
2475
+ ${sortBy ? sortBy + ', ' : 'ORDER BY '}${eTable}.\`guid\``;
1700
2476
  }
1701
2477
  }
1702
2478
  } else {
@@ -1706,28 +2482,33 @@ export default class MySQLDriver extends NymphDriver {
1706
2482
  let limit = '';
1707
2483
  if ('limit' in options) {
1708
2484
  limit = ` LIMIT ${Math.floor(
1709
- isNaN(Number(options.limit)) ? 0 : Number(options.limit)
2485
+ isNaN(Number(options.limit)) ? 0 : Number(options.limit),
1710
2486
  )}`;
1711
2487
  }
1712
2488
  let offset = '';
1713
2489
  if ('offset' in options) {
1714
2490
  offset = ` OFFSET ${Math.floor(
1715
- isNaN(Number(options.offset)) ? 0 : Number(options.offset)
2491
+ isNaN(Number(options.offset)) ? 0 : Number(options.offset),
1716
2492
  )}`;
1717
2493
  }
2494
+ const guidClause = guidExplicitSelector
2495
+ ? ` WHERE ${guidExplicitSelector(`${ieTable}.\`guid\``)}`
2496
+ : guidSelector
2497
+ ? ` WHERE ${ieTable}.\`guid\`=${guidSelector}`
2498
+ : '';
1718
2499
  if (options.return === 'count') {
1719
2500
  if (limit || offset) {
1720
2501
  query = `SELECT COUNT(${countTable}.\`guid\`) AS \`count\` FROM (
1721
2502
  SELECT ${ieTable}.\`guid\` AS \`guid\`
1722
2503
  FROM ${MySQLDriver.escape(
1723
- `${this.prefix}entities_${etype}`
1724
- )} ${ieTable}${limit}${offset}
2504
+ `${this.prefix}entities_${etype}`,
2505
+ )} ${ieTable}${guidClause}${limit}${offset}
1725
2506
  ) ${countTable}`;
1726
2507
  } else {
1727
2508
  query = `SELECT COUNT(${ieTable}.\`guid\`) AS \`count\`
1728
2509
  FROM ${MySQLDriver.escape(
1729
- `${this.prefix}entities_${etype}`
1730
- )} ${ieTable}`;
2510
+ `${this.prefix}entities_${etype}`,
2511
+ )} ${ieTable}${guidClause}`;
1731
2512
  }
1732
2513
  } else if (options.return === 'guid') {
1733
2514
  const guidColumn =
@@ -1736,9 +2517,11 @@ export default class MySQLDriver extends NymphDriver {
1736
2517
  : `${ieTable}.\`guid\``;
1737
2518
  query = `SELECT ${guidColumn} AS \`guid\`
1738
2519
  FROM ${MySQLDriver.escape(
1739
- `${this.prefix}entities_${etype}`
2520
+ `${this.prefix}entities_${etype}`,
1740
2521
  )} ${ieTable}
1741
- ORDER BY ${ieTable}.${sortBy}${limit}${offset}`;
2522
+ ${sortJoinInner}
2523
+ ${guidClause}
2524
+ ${sortByInner ? sortByInner + ', ' : 'ORDER BY '}${ieTable}.\`guid\`${limit}${offset}`;
1742
2525
  } else {
1743
2526
  if (limit || offset) {
1744
2527
  query = `SELECT
@@ -1746,47 +2529,64 @@ export default class MySQLDriver extends NymphDriver {
1746
2529
  ${eTable}.\`tags\`,
1747
2530
  ${eTable}.\`cdate\`,
1748
2531
  ${eTable}.\`mdate\`,
2532
+ LOWER(HEX(${eTable}.\`user\`)) AS \`user\`,
2533
+ LOWER(HEX(${eTable}.\`group\`)) AS \`group\`,
2534
+ ${eTable}.\`acUser\`,
2535
+ ${eTable}.\`acGroup\`,
2536
+ ${eTable}.\`acOther\`,
2537
+ ${eTable}.\`acRead\`,
2538
+ ${eTable}.\`acWrite\`,
2539
+ ${eTable}.\`acFull\`,
1749
2540
  ${dTable}.\`name\`,
1750
2541
  ${dTable}.\`value\`,
1751
- ${cTable}.\`string\`,
1752
- ${cTable}.\`number\`
2542
+ ${dTable}.\`json\`,
2543
+ ${dTable}.\`string\`,
2544
+ ${dTable}.\`number\`
1753
2545
  FROM ${MySQLDriver.escape(
1754
- `${this.prefix}entities_${etype}`
2546
+ `${this.prefix}entities_${etype}`,
1755
2547
  )} ${eTable}
1756
2548
  LEFT JOIN ${MySQLDriver.escape(
1757
- `${this.prefix}data_${etype}`
2549
+ `${this.prefix}data_${etype}`,
1758
2550
  )} ${dTable} ON ${eTable}.\`guid\`=${dTable}.\`guid\`
1759
- INNER JOIN ${MySQLDriver.escape(
1760
- `${this.prefix}comparisons_${etype}`
1761
- )} ${cTable} ON ${dTable}.\`guid\`=${cTable}.\`guid\` AND ${dTable}.\`name\`=${cTable}.\`name\`
2551
+ ${sortJoin}
1762
2552
  INNER JOIN (
1763
2553
  SELECT ${ieTable}.\`guid\`
1764
2554
  FROM ${MySQLDriver.escape(
1765
- `${this.prefix}entities_${etype}`
2555
+ `${this.prefix}entities_${etype}`,
1766
2556
  )} ${ieTable}
1767
- ORDER BY ${ieTable}.${sortBy}${limit}${offset}
2557
+ ${sortJoinInner}
2558
+ ${guidClause}
2559
+ ${sortByInner}${limit}${offset}
1768
2560
  ) ${fTable} ON ${eTable}.\`guid\`=${fTable}.\`guid\`
1769
- ORDER BY ${eTable}.${sortBy}`;
2561
+ ${sortBy ? sortBy + ', ' : 'ORDER BY '}${eTable}.\`guid\``;
1770
2562
  } else {
1771
2563
  query = `SELECT
1772
2564
  LOWER(HEX(${eTable}.\`guid\`)) AS \`guid\`,
1773
2565
  ${eTable}.\`tags\`,
1774
2566
  ${eTable}.\`cdate\`,
1775
2567
  ${eTable}.\`mdate\`,
2568
+ LOWER(HEX(${eTable}.\`user\`)) AS \`user\`,
2569
+ LOWER(HEX(${eTable}.\`group\`)) AS \`group\`,
2570
+ ${eTable}.\`acUser\`,
2571
+ ${eTable}.\`acGroup\`,
2572
+ ${eTable}.\`acOther\`,
2573
+ ${eTable}.\`acRead\`,
2574
+ ${eTable}.\`acWrite\`,
2575
+ ${eTable}.\`acFull\`,
1776
2576
  ${dTable}.\`name\`,
1777
2577
  ${dTable}.\`value\`,
1778
- ${cTable}.\`string\`,
1779
- ${cTable}.\`number\`
2578
+ ${dTable}.\`json\`,
2579
+ ${dTable}.\`string\`,
2580
+ ${dTable}.\`number\`
1780
2581
  FROM ${MySQLDriver.escape(
1781
- `${this.prefix}entities_${etype}`
2582
+ `${this.prefix}entities_${etype}`,
1782
2583
  )} ${eTable}
1783
2584
  LEFT JOIN ${MySQLDriver.escape(
1784
- `${this.prefix}data_${etype}`
2585
+ `${this.prefix}data_${etype}`,
1785
2586
  )} ${dTable} ON ${eTable}.\`guid\`=${dTable}.\`guid\`
1786
- INNER JOIN ${MySQLDriver.escape(
1787
- `${this.prefix}comparisons_${etype}`
1788
- )} ${cTable} ON ${dTable}.\`guid\`=${cTable}.\`guid\` AND ${dTable}.\`name\`=${cTable}.\`name\`
1789
- ORDER BY ${eTable}.${sortBy}`;
2587
+ ${sortJoin}
2588
+ ${guidExplicitSelector ? `WHERE ${guidExplicitSelector(`${eTable}.\`guid\``)}` : guidSelector ? `WHERE ${eTable}.\`guid\`=${guidSelector}` : ''}
2589
+ ${sortBy ? sortBy + ', ' : 'ORDER BY '}${eTable}.\`guid\``;
1790
2590
  }
1791
2591
  }
1792
2592
  }
@@ -1806,38 +2606,18 @@ export default class MySQLDriver extends NymphDriver {
1806
2606
  protected performQuery(
1807
2607
  options: Options,
1808
2608
  formattedSelectors: FormattedSelector[],
1809
- etype: string
2609
+ etype: string,
1810
2610
  ): {
1811
2611
  result: any;
1812
2612
  } {
1813
2613
  const { query, params, etypes } = this.makeEntityQuery(
1814
2614
  options,
1815
2615
  formattedSelectors,
1816
- etype
1817
- );
1818
- const result = this.queryIter(query, { etypes, params }).then((val) =>
1819
- val[Symbol.iterator]()
2616
+ etype,
1820
2617
  );
1821
- return {
1822
- result,
1823
- };
1824
- }
1825
-
1826
- protected performQuerySync(
1827
- options: Options,
1828
- formattedSelectors: FormattedSelector[],
1829
- etype: string
1830
- ): {
1831
- result: any;
1832
- } {
1833
- const { query, params, etypes } = this.makeEntityQuery(
1834
- options,
1835
- formattedSelectors,
1836
- etype
2618
+ const result = this.queryArray(query, { etypes, params }).then((val) =>
2619
+ val[Symbol.iterator](),
1837
2620
  );
1838
- const result = (this.queryIterSync(query, { etypes, params }) || [])[
1839
- Symbol.iterator
1840
- ]();
1841
2621
  return {
1842
2622
  result,
1843
2623
  };
@@ -1851,20 +2631,26 @@ export default class MySQLDriver extends NymphDriver {
1851
2631
  options: Options<T> & { return: 'guid' },
1852
2632
  ...selectors: Selector[]
1853
2633
  ): Promise<string[]>;
2634
+ public async getEntities<T extends EntityConstructor = EntityConstructor>(
2635
+ options: Options<T> & { return: 'object' },
2636
+ ...selectors: Selector[]
2637
+ ): Promise<EntityObjectType<T>[]>;
1854
2638
  public async getEntities<T extends EntityConstructor = EntityConstructor>(
1855
2639
  options?: Options<T>,
1856
2640
  ...selectors: Selector[]
1857
- ): Promise<ReturnType<T['factorySync']>[]>;
2641
+ ): Promise<EntityInstanceType<T>[]>;
1858
2642
  public async getEntities<T extends EntityConstructor = EntityConstructor>(
1859
2643
  options: Options<T> = {},
1860
2644
  ...selectors: Selector[]
1861
- ): Promise<ReturnType<T['factorySync']>[] | string[] | number> {
1862
- const { result: resultPromise, process } = this.getEntitesRowLike<T>(
2645
+ ): Promise<
2646
+ EntityInstanceType<T>[] | EntityObjectType<T>[] | string[] | number
2647
+ > {
2648
+ const { result: resultPromise, process } = this.getEntitiesRowLike<T>(
1863
2649
  // @ts-ignore: options is correct here.
1864
2650
  options,
1865
2651
  selectors,
1866
- (options, formattedSelectors, etype) =>
1867
- this.performQuery(options, formattedSelectors, etype),
2652
+ ({ options, selectors, etype }) =>
2653
+ this.performQuery(options, selectors, etype),
1868
2654
  () => {
1869
2655
  const next: any = result.next();
1870
2656
  return next.done ? null : next.value;
@@ -1873,9 +2659,25 @@ export default class MySQLDriver extends NymphDriver {
1873
2659
  (row) => Number(row.count),
1874
2660
  (row) => row.guid,
1875
2661
  (row) => ({
1876
- tags: row.tags.length > 2 ? row.tags.slice(1, -1).split(' ') : [],
1877
- cdate: isNaN(Number(row.cdate)) ? null : Number(row.cdate),
1878
- mdate: isNaN(Number(row.mdate)) ? null : Number(row.mdate),
2662
+ tags:
2663
+ row.tags.length > 2
2664
+ ? MySQLDriver.unescapeTags(
2665
+ row.tags
2666
+ .slice(1, -1)
2667
+ .split(' ')
2668
+ .filter((tag: string) => tag),
2669
+ )
2670
+ : [],
2671
+ cdate: isNaN(Number(row.cdate)) ? Date.now() : Number(row.cdate),
2672
+ mdate: isNaN(Number(row.mdate)) ? Date.now() : Number(row.mdate),
2673
+ user: row.user,
2674
+ group: row.group,
2675
+ acUser: row.acUser,
2676
+ acGroup: row.acGroup,
2677
+ acOther: row.acOther,
2678
+ acRead: row.acRead?.slice(1, -1).split(' ') ?? [],
2679
+ acWrite: row.acWrite?.slice(1, -1).split(' ') ?? [],
2680
+ acFull: row.acFull?.slice(1, -1).split(' ') ?? [],
1879
2681
  }),
1880
2682
  (row) => ({
1881
2683
  name: row.name,
@@ -1883,9 +2685,11 @@ export default class MySQLDriver extends NymphDriver {
1883
2685
  row.value === 'N'
1884
2686
  ? JSON.stringify(row.number)
1885
2687
  : row.value === 'S'
1886
- ? JSON.stringify(row.string)
1887
- : row.value,
1888
- })
2688
+ ? JSON.stringify(row.string)
2689
+ : row.value === 'J'
2690
+ ? JSON.stringify(row.json)
2691
+ : row.value,
2692
+ }),
1889
2693
  );
1890
2694
 
1891
2695
  const result = await resultPromise;
@@ -1896,231 +2700,390 @@ export default class MySQLDriver extends NymphDriver {
1896
2700
  return value;
1897
2701
  }
1898
2702
 
1899
- protected getEntitiesSync<T extends EntityConstructor = EntityConstructor>(
1900
- options: Options<T> & { return: 'count' },
1901
- ...selectors: Selector[]
1902
- ): number;
1903
- protected getEntitiesSync<T extends EntityConstructor = EntityConstructor>(
1904
- options: Options<T> & { return: 'guid' },
1905
- ...selectors: Selector[]
1906
- ): string[];
1907
- protected getEntitiesSync<T extends EntityConstructor = EntityConstructor>(
1908
- options?: Options<T>,
1909
- ...selectors: Selector[]
1910
- ): ReturnType<T['factorySync']>[];
1911
- protected getEntitiesSync<T extends EntityConstructor = EntityConstructor>(
1912
- options: Options<T> = {},
1913
- ...selectors: Selector[]
1914
- ): ReturnType<T['factorySync']>[] | string[] | number {
1915
- const { result, process } = this.getEntitesRowLike<T>(
1916
- // @ts-ignore: options is correct here.
1917
- options,
1918
- selectors,
1919
- (options, formattedSelectors, etype) =>
1920
- this.performQuerySync(options, formattedSelectors, etype),
1921
- () => {
1922
- const next: any = result.next();
1923
- return next.done ? null : next.value;
1924
- },
1925
- () => undefined,
1926
- (row) => Number(row.count),
1927
- (row) => row.guid,
1928
- (row) => ({
1929
- tags: row.tags.length > 2 ? row.tags.slice(1, -1).split(',') : [],
1930
- cdate: isNaN(Number(row.cdate)) ? null : Number(row.cdate),
1931
- mdate: isNaN(Number(row.mdate)) ? null : Number(row.mdate),
1932
- }),
1933
- (row) => ({
1934
- name: row.name,
1935
- svalue:
1936
- row.value === 'N'
1937
- ? JSON.stringify(row.number)
1938
- : row.value === 'S'
1939
- ? JSON.stringify(row.string)
1940
- : row.value,
1941
- })
1942
- );
1943
- const value = process();
1944
- if (value instanceof Error) {
1945
- throw value;
1946
- }
1947
- return value;
1948
- }
1949
-
1950
2703
  public async getUID(name: string) {
1951
2704
  if (name == null) {
1952
2705
  throw new InvalidParametersError('Name not given for UID.');
1953
2706
  }
2707
+ if (name.length > 128) {
2708
+ throw new InvalidParametersError('UID name too long. 128 chars max.');
2709
+ }
1954
2710
  const result = await this.queryGet(
1955
2711
  `SELECT \`cur_uid\` FROM ${MySQLDriver.escape(
1956
- `${this.prefix}uids`
2712
+ `${this.prefix}uids`,
1957
2713
  )} WHERE \`name\`=@name;`,
1958
2714
  {
1959
2715
  params: {
1960
2716
  name: name,
1961
2717
  },
1962
- }
2718
+ },
1963
2719
  );
1964
2720
  return (result?.cur_uid as number | null) ?? null;
1965
2721
  }
1966
2722
 
1967
- public async import(filename: string) {
2723
+ public async importEntity(entity: {
2724
+ guid: string;
2725
+ cdate: number;
2726
+ mdate: number;
2727
+ tags: string[];
2728
+ sdata: SerializedEntityData;
2729
+ etype: string;
2730
+ }) {
2731
+ return await this.importEntityInternal(entity);
2732
+ }
2733
+
2734
+ public async importEntityTokens(entity: {
2735
+ guid: string;
2736
+ cdate: number;
2737
+ mdate: number;
2738
+ tags: string[];
2739
+ sdata: SerializedEntityData;
2740
+ etype: string;
2741
+ }) {
2742
+ return await this.importEntityInternal(entity, { only: 'tokens' });
2743
+ }
2744
+
2745
+ public async importEntityTilmeldAC(entity: {
2746
+ guid: string;
2747
+ cdate: number;
2748
+ mdate: number;
2749
+ tags: string[];
2750
+ sdata: SerializedEntityData;
2751
+ etype: string;
2752
+ }) {
2753
+ return await this.importEntityInternal(entity, { only: 'tilmeldAC' });
2754
+ }
2755
+
2756
+ private async importEntityInternal(
2757
+ {
2758
+ guid,
2759
+ cdate,
2760
+ mdate,
2761
+ tags,
2762
+ sdata,
2763
+ etype,
2764
+ }: {
2765
+ guid: string;
2766
+ cdate: number;
2767
+ mdate: number;
2768
+ tags: string[];
2769
+ sdata: SerializedEntityData;
2770
+ etype: string;
2771
+ },
2772
+ { only = undefined }: { only?: 'tokens' | 'tilmeldAC' } = {},
2773
+ ) {
1968
2774
  try {
1969
- const result = await this.importFromFile(
1970
- filename,
1971
- async (guid, tags, sdata, etype) => {
1972
- await this.queryRun(
1973
- `REPLACE INTO ${MySQLDriver.escape(
1974
- `${this.prefix}entities_${etype}`
1975
- )} (\`guid\`, \`tags\`, \`cdate\`, \`mdate\`) VALUES (UNHEX(@guid), @tags, @cdate, @mdate);`,
2775
+ let promises = [];
2776
+ if (only == null) {
2777
+ promises.push(
2778
+ this.queryRun(
2779
+ `DELETE FROM ${MySQLDriver.escape(
2780
+ `${this.prefix}entities_${etype}`,
2781
+ )} WHERE \`guid\`=UNHEX(@guid);`,
1976
2782
  {
1977
2783
  etypes: [etype],
1978
2784
  params: {
1979
2785
  guid,
1980
- tags: ' ' + tags.join(' ') + ' ',
1981
- cdate: isNaN(Number(JSON.parse(sdata.cdate)))
1982
- ? null
1983
- : Number(JSON.parse(sdata.cdate)),
1984
- mdate: isNaN(Number(JSON.parse(sdata.mdate)))
1985
- ? null
1986
- : Number(JSON.parse(sdata.mdate)),
1987
2786
  },
1988
- }
1989
- );
1990
- const promises = [];
1991
- promises.push(
1992
- this.queryRun(
1993
- `DELETE FROM ${MySQLDriver.escape(
1994
- `${this.prefix}data_${etype}`
1995
- )} WHERE \`guid\`=UNHEX(@guid);`,
1996
- {
1997
- etypes: [etype],
1998
- params: {
1999
- guid,
2000
- },
2001
- }
2002
- )
2003
- );
2004
- promises.push(
2005
- this.queryRun(
2006
- `DELETE FROM ${MySQLDriver.escape(
2007
- `${this.prefix}comparisons_${etype}`
2008
- )} WHERE \`guid\`=UNHEX(@guid);`,
2009
- {
2010
- etypes: [etype],
2011
- params: {
2012
- guid,
2013
- },
2014
- }
2015
- )
2016
- );
2787
+ },
2788
+ ),
2789
+ );
2790
+ promises.push(
2791
+ this.queryRun(
2792
+ `DELETE FROM ${MySQLDriver.escape(
2793
+ `${this.prefix}data_${etype}`,
2794
+ )} WHERE \`guid\`=UNHEX(@guid);`,
2795
+ {
2796
+ etypes: [etype],
2797
+ params: {
2798
+ guid,
2799
+ },
2800
+ },
2801
+ ),
2802
+ );
2803
+ promises.push(
2804
+ this.queryRun(
2805
+ `DELETE FROM ${MySQLDriver.escape(
2806
+ `${this.prefix}references_${etype}`,
2807
+ )} WHERE \`guid\`=UNHEX(@guid);`,
2808
+ {
2809
+ etypes: [etype],
2810
+ params: {
2811
+ guid,
2812
+ },
2813
+ },
2814
+ ),
2815
+ );
2816
+ }
2817
+ if (only == null || only === 'tokens') {
2818
+ promises.push(
2819
+ this.queryRun(
2820
+ `DELETE FROM ${MySQLDriver.escape(
2821
+ `${this.prefix}tokens_${etype}`,
2822
+ )} WHERE \`guid\`=UNHEX(@guid);`,
2823
+ {
2824
+ etypes: [etype],
2825
+ params: {
2826
+ guid,
2827
+ },
2828
+ },
2829
+ ),
2830
+ );
2831
+ }
2832
+ if (only == null) {
2833
+ promises.push(
2834
+ this.queryRun(
2835
+ `DELETE FROM ${MySQLDriver.escape(
2836
+ `${this.prefix}uniques_${etype}`,
2837
+ )} WHERE \`guid\`=UNHEX(@guid);`,
2838
+ {
2839
+ etypes: [etype],
2840
+ params: {
2841
+ guid,
2842
+ },
2843
+ },
2844
+ ),
2845
+ );
2846
+ }
2847
+
2848
+ await Promise.all(promises);
2849
+ promises = [];
2850
+
2851
+ if (only == null) {
2852
+ let { user, group, acUser, acGroup, acOther, acRead, acWrite, acFull } =
2853
+ this.removeAndReturnACValues(etype, {}, sdata);
2854
+
2855
+ await this.queryRun(
2856
+ `INSERT INTO ${MySQLDriver.escape(
2857
+ `${this.prefix}entities_${etype}`,
2858
+ )} (\`guid\`, \`tags\`, \`cdate\`, \`mdate\`, \`user\`, \`group\`, \`acUser\`, \`acGroup\`, \`acOther\`, \`acRead\`, \`acWrite\`, \`acFull\`) VALUES (UNHEX(@guid), @tags, @cdate, @mdate, ${user == null ? '@user' : 'UNHEX(@user)'}, ${group == null ? '@group' : 'UNHEX(@group)'}, @acUser, @acGroup, @acOther, @acRead, @acWrite, @acFull);`,
2859
+ {
2860
+ etypes: [etype],
2861
+ params: {
2862
+ guid,
2863
+ tags: ' ' + MySQLDriver.escapeTags(tags).join(' ') + ' ',
2864
+ cdate: isNaN(cdate) ? null : cdate,
2865
+ mdate: isNaN(mdate) ? null : mdate,
2866
+ user,
2867
+ group,
2868
+ acUser,
2869
+ acGroup,
2870
+ acOther,
2871
+ acRead: acRead && ' ' + acRead.join(' ') + ' ',
2872
+ acWrite: acWrite && ' ' + acWrite.join(' ') + ' ',
2873
+ acFull: acFull && ' ' + acFull.join(' ') + ' ',
2874
+ },
2875
+ },
2876
+ );
2877
+
2878
+ for (const name in sdata) {
2879
+ if (
2880
+ typeof name !== 'string' ||
2881
+ !name.length ||
2882
+ name.match(/^\s|=|\s$/)
2883
+ ) {
2884
+ throw new EntityInvalidDataError(
2885
+ 'Property names must be non-empty strings without leading or trailing spaces or equals signs.',
2886
+ );
2887
+ }
2888
+
2889
+ const value = sdata[name];
2890
+ const uvalue = JSON.parse(value);
2891
+ if (value === undefined) {
2892
+ continue;
2893
+ }
2894
+ const storageValue =
2895
+ typeof uvalue === 'number'
2896
+ ? 'N'
2897
+ : typeof uvalue === 'string'
2898
+ ? 'S'
2899
+ : 'J';
2900
+ const jsonValue = storageValue === 'J' ? value : null;
2901
+
2017
2902
  promises.push(
2018
2903
  this.queryRun(
2019
- `DELETE FROM ${MySQLDriver.escape(
2020
- `${this.prefix}references_${etype}`
2021
- )} WHERE \`guid\`=UNHEX(@guid);`,
2904
+ `INSERT INTO ${MySQLDriver.escape(
2905
+ `${this.prefix}data_${etype}`,
2906
+ )} (\`guid\`, \`name\`, \`value\`, \`json\`, \`string\`, \`number\`, \`truthy\`) VALUES (UNHEX(@guid), @name, @storageValue, @jsonValue, @string, @number, @truthy);`,
2022
2907
  {
2023
2908
  etypes: [etype],
2024
2909
  params: {
2025
2910
  guid,
2911
+ name,
2912
+ storageValue,
2913
+ jsonValue,
2914
+ string: storageValue === 'J' ? null : `${uvalue}`,
2915
+ number: isNaN(Number(uvalue)) ? null : Number(uvalue),
2916
+ truthy: !!uvalue,
2026
2917
  },
2027
- }
2028
- )
2918
+ },
2919
+ ),
2029
2920
  );
2030
- await Promise.all(promises);
2031
- delete sdata.cdate;
2032
- delete sdata.mdate;
2033
- for (const name in sdata) {
2034
- const value = sdata[name];
2035
- const uvalue = JSON.parse(value);
2036
- if (value === undefined) {
2037
- continue;
2038
- }
2039
- const storageValue =
2040
- typeof uvalue === 'number'
2041
- ? 'N'
2042
- : typeof uvalue === 'string'
2043
- ? 'S'
2044
- : value;
2045
- const promises = [];
2046
- promises.push(
2047
- this.queryRun(
2048
- `INSERT INTO ${MySQLDriver.escape(
2049
- `${this.prefix}data_${etype}`
2050
- )} (\`guid\`, \`name\`, \`value\`) VALUES (UNHEX(@guid), @name, @storageValue);`,
2051
- {
2052
- etypes: [etype],
2053
- params: {
2054
- guid,
2055
- name,
2056
- storageValue,
2057
- },
2058
- }
2059
- )
2060
- );
2921
+
2922
+ const references = this.findReferences(value);
2923
+ for (const reference of references) {
2061
2924
  promises.push(
2062
2925
  this.queryRun(
2063
2926
  `INSERT INTO ${MySQLDriver.escape(
2064
- `${this.prefix}comparisons_${etype}`
2065
- )} (\`guid\`, \`name\`, \`truthy\`, \`string\`, \`number\`) VALUES (UNHEX(@guid), @name, @truthy, @string, @number);`,
2927
+ `${this.prefix}references_${etype}`,
2928
+ )} (\`guid\`, \`name\`, \`reference\`) VALUES (UNHEX(@guid), @name, UNHEX(@reference));`,
2066
2929
  {
2067
2930
  etypes: [etype],
2068
2931
  params: {
2069
2932
  guid,
2070
2933
  name,
2071
- truthy: !!uvalue,
2072
- string: `${uvalue}`,
2073
- number: isNaN(Number(uvalue)) ? null : Number(uvalue),
2934
+ reference,
2074
2935
  },
2075
- }
2076
- )
2936
+ },
2937
+ ),
2077
2938
  );
2078
- const references = this.findReferences(value);
2079
- for (const reference of references) {
2939
+ }
2940
+ }
2941
+ }
2942
+
2943
+ if (only === 'tilmeldAC') {
2944
+ let { user, group, acUser, acGroup, acOther, acRead, acWrite, acFull } =
2945
+ this.removeAndReturnACValues(etype, {}, sdata);
2946
+
2947
+ promises.push(
2948
+ this.queryRun(
2949
+ `UPDATE ${MySQLDriver.escape(
2950
+ `${this.prefix}entities_${etype}`,
2951
+ )} SET \`user\`=${user == null ? '@user' : 'UNHEX(@user)'}, \`group\`=${group == null ? '@group' : 'UNHEX(@group)'}, \`acUser\`=@acUser, \`acGroup\`=@acGroup, \`acOther\`=@acOther, \`acRead\`=@acRead, \`acWrite\`=@acWrite, \`acFull\`=@acFull WHERE \`guid\`=UNHEX(@guid);`,
2952
+ {
2953
+ etypes: [etype],
2954
+ params: {
2955
+ user,
2956
+ group,
2957
+ acUser,
2958
+ acGroup,
2959
+ acOther,
2960
+ acRead: acRead && ' ' + acRead.join(' ') + ' ',
2961
+ acWrite: acWrite && ' ' + acWrite.join(' ') + ' ',
2962
+ acFull: acFull && ' ' + acFull.join(' ') + ' ',
2963
+ guid,
2964
+ },
2965
+ },
2966
+ ),
2967
+ );
2968
+ }
2969
+
2970
+ const EntityClass = this.nymph.getEntityClassByEtype(etype);
2971
+
2972
+ if (only == null || only === 'tokens') {
2973
+ for (let name in sdata) {
2974
+ let tokenString: string | null = null;
2975
+ try {
2976
+ tokenString = EntityClass.getFTSText(name, JSON.parse(sdata[name]));
2977
+ } catch (e: any) {
2978
+ // Ignore error.
2979
+ }
2980
+
2981
+ if (tokenString != null) {
2982
+ const tokens = this.tokenizer.tokenize(tokenString);
2983
+ while (tokens.length) {
2984
+ const currentTokens = tokens.splice(0, 100);
2985
+ const params: { [k: string]: any } = {
2986
+ guid,
2987
+ name,
2988
+ };
2989
+ const values: string[] = [];
2990
+
2991
+ for (let i = 0; i < currentTokens.length; i++) {
2992
+ const token = currentTokens[i];
2993
+ params['token' + i] = token.token;
2994
+ params['position' + i] = token.position;
2995
+ params['stem' + i] = token.stem;
2996
+ values.push(
2997
+ '(UNHEX(@guid), @name, @token' +
2998
+ i +
2999
+ ', @position' +
3000
+ i +
3001
+ ', @stem' +
3002
+ i +
3003
+ ')',
3004
+ );
3005
+ }
3006
+
2080
3007
  promises.push(
2081
3008
  this.queryRun(
2082
3009
  `INSERT INTO ${MySQLDriver.escape(
2083
- `${this.prefix}references_${etype}`
2084
- )} (\`guid\`, \`name\`, \`reference\`) VALUES (UNHEX(@guid), @name, UNHEX(@reference));`,
3010
+ `${this.prefix}tokens_${etype}`,
3011
+ )} (\`guid\`, \`name\`, \`token\`, \`position\`, \`stem\`) VALUES ${values.join(', ')};`,
2085
3012
  {
2086
3013
  etypes: [etype],
2087
- params: {
2088
- guid,
2089
- name,
2090
- reference,
2091
- },
2092
- }
2093
- )
3014
+ params,
3015
+ },
3016
+ ),
2094
3017
  );
2095
3018
  }
2096
3019
  }
2097
- await Promise.all(promises);
2098
- },
2099
- async (name, curUid) => {
2100
- await this.queryRun(
2101
- `INSERT INTO ${MySQLDriver.escape(
2102
- `${this.prefix}uids`
2103
- )} (\`name\`, \`cur_uid\`) VALUES (@name, @curUid) ON DUPLICATE KEY UPDATE \`cur_uid\`=@curUid;`,
2104
- {
2105
- params: {
2106
- name,
2107
- curUid,
3020
+ }
3021
+ }
3022
+
3023
+ if (only == null) {
3024
+ const uniques = await EntityClass.getUniques({
3025
+ guid,
3026
+ cdate,
3027
+ mdate,
3028
+ tags,
3029
+ data: {},
3030
+ sdata,
3031
+ });
3032
+ for (const unique of uniques) {
3033
+ promises.push(
3034
+ this.queryRun(
3035
+ `INSERT INTO ${MySQLDriver.escape(
3036
+ `${this.prefix}uniques_${etype}`,
3037
+ )} (\`guid\`, \`unique\`) VALUES (UNHEX(@guid), @unique);`,
3038
+ {
3039
+ etypes: [etype],
3040
+ params: {
3041
+ guid,
3042
+ unique,
3043
+ },
2108
3044
  },
2109
- }
3045
+ ).catch((e: any) => {
3046
+ if (e instanceof EntityUniqueConstraintError) {
3047
+ this.nymph.config.debugError(
3048
+ 'mysql',
3049
+ `Import entity unique constraint violation for GUID "${guid}" on etype "${etype}": "${unique}"`,
3050
+ );
3051
+ }
3052
+ return e;
3053
+ }),
2110
3054
  );
2111
- },
2112
- async () => {
2113
- await this.internalTransaction('nymph-import');
2114
- },
2115
- async () => {
2116
- await this.commit('nymph-import');
2117
3055
  }
2118
- );
3056
+ }
2119
3057
 
2120
- return result;
3058
+ await Promise.all(promises);
3059
+ } catch (e: any) {
3060
+ this.nymph.config.debugError('mysql', `Import entity error: "${e}"`);
3061
+ throw e;
3062
+ }
3063
+ }
3064
+
3065
+ public async importUID({ name, value }: { name: string; value: number }) {
3066
+ if (name.length > 128) {
3067
+ throw new InvalidParametersError('UID name too long. 128 chars max.');
3068
+ }
3069
+ try {
3070
+ await this.internalTransaction(`nymph-import-uid-${name}`);
3071
+ await this.queryRun(
3072
+ `INSERT INTO ${MySQLDriver.escape(
3073
+ `${this.prefix}uids`,
3074
+ )} (\`name\`, \`cur_uid\`) VALUES (@name, @value) ON DUPLICATE KEY UPDATE \`cur_uid\`=@value;`,
3075
+ {
3076
+ params: {
3077
+ name,
3078
+ value,
3079
+ },
3080
+ },
3081
+ );
3082
+ await this.commit(`nymph-import-uid-${name}`);
2121
3083
  } catch (e: any) {
2122
- await this.rollback('nymph-import');
2123
- return false;
3084
+ this.nymph.config.debugError('mysql', `Import UID error: "${e}"`);
3085
+ await this.rollback(`nymph-import-uid-${name}`);
3086
+ throw e;
2124
3087
  }
2125
3088
  }
2126
3089
 
@@ -2128,72 +3091,80 @@ export default class MySQLDriver extends NymphDriver {
2128
3091
  if (name == null) {
2129
3092
  throw new InvalidParametersError('Name not given for UID.');
2130
3093
  }
3094
+ if (name.length > 128) {
3095
+ throw new InvalidParametersError('UID name too long. 128 chars max.');
3096
+ }
2131
3097
  await this.internalTransaction('nymph-newuid');
3098
+ let curUid: number | null = null;
2132
3099
  try {
2133
3100
  const lock = await this.queryGet(
2134
3101
  `SELECT GET_LOCK(${MySQLDriver.escapeValue(
2135
- `${this.prefix}uids_${name}`
2136
- )}, 10) AS \`lock\`;`
3102
+ `${this.prefix}uids_${name}`,
3103
+ )}, 10) AS \`lock\`;`,
2137
3104
  );
2138
3105
  if (lock.lock !== 1) {
2139
3106
  throw new QueryFailedError("Couldn't get lock for UID: " + name);
2140
3107
  }
2141
- let curUid: number | null = null;
2142
3108
  await this.queryRun(
2143
3109
  `INSERT INTO ${MySQLDriver.escape(
2144
- `${this.prefix}uids`
3110
+ `${this.prefix}uids`,
2145
3111
  )} (\`name\`, \`cur_uid\`) VALUES (@name, 1) ON DUPLICATE KEY UPDATE \`cur_uid\`=\`cur_uid\`+1;`,
2146
3112
  {
2147
3113
  params: {
2148
3114
  name,
2149
3115
  },
2150
- }
3116
+ },
2151
3117
  );
2152
3118
  const result = await this.queryGet(
2153
3119
  `SELECT \`cur_uid\` FROM ${MySQLDriver.escape(
2154
- `${this.prefix}uids`
3120
+ `${this.prefix}uids`,
2155
3121
  )} WHERE \`name\`=@name;`,
2156
3122
  {
2157
3123
  params: {
2158
3124
  name,
2159
3125
  },
2160
- }
3126
+ },
2161
3127
  );
2162
3128
  await this.queryRun(
2163
3129
  `SELECT RELEASE_LOCK(${MySQLDriver.escapeValue(
2164
- `${this.prefix}uids_${name}`
2165
- )});`
3130
+ `${this.prefix}uids_${name}`,
3131
+ )});`,
2166
3132
  );
2167
- await this.commit('nymph-newuid');
2168
3133
  curUid = result.cur_uid ?? null;
2169
- return curUid;
2170
3134
  } catch (e: any) {
3135
+ this.nymph.config.debugError('mysql', `New UID error: "${e}"`);
2171
3136
  if (e?.message !== "Couldn't get lock for UID: " + name) {
2172
3137
  await this.queryRun(
2173
3138
  `SELECT RELEASE_LOCK(${MySQLDriver.escapeValue(
2174
- `${this.prefix}uids_${name}`
2175
- )});`
3139
+ `${this.prefix}uids_${name}`,
3140
+ )});`,
2176
3141
  );
2177
3142
  }
2178
3143
  await this.rollback('nymph-newuid');
2179
3144
  throw e;
2180
3145
  }
3146
+
3147
+ await this.commit('nymph-newuid');
3148
+ return curUid;
2181
3149
  }
2182
3150
 
2183
3151
  public async renameUID(oldName: string, newName: string) {
2184
3152
  if (oldName == null || newName == null) {
2185
3153
  throw new InvalidParametersError('Name not given for UID.');
2186
3154
  }
3155
+ if (oldName.length > 128 || newName.length > 128) {
3156
+ throw new InvalidParametersError('UID name too long. 128 chars max.');
3157
+ }
2187
3158
  await this.queryRun(
2188
3159
  `UPDATE ${MySQLDriver.escape(
2189
- `${this.prefix}uids`
3160
+ `${this.prefix}uids`,
2190
3161
  )} SET \`name\`=@newName WHERE \`name\`=@oldName;`,
2191
3162
  {
2192
3163
  params: {
2193
3164
  newName,
2194
3165
  oldName,
2195
3166
  },
2196
- }
3167
+ },
2197
3168
  );
2198
3169
  return true;
2199
3170
  }
@@ -2201,7 +3172,7 @@ export default class MySQLDriver extends NymphDriver {
2201
3172
  public async rollback(name: string) {
2202
3173
  if (name == null || typeof name !== 'string' || name.length === 0) {
2203
3174
  throw new InvalidParametersError(
2204
- 'Transaction rollback attempted without a name.'
3175
+ 'Transaction rollback attempted without a name.',
2205
3176
  );
2206
3177
  }
2207
3178
  if (!this.transaction || this.transaction.count === 0) {
@@ -2226,13 +3197,26 @@ export default class MySQLDriver extends NymphDriver {
2226
3197
  guid: string,
2227
3198
  data: EntityData,
2228
3199
  sdata: SerializedEntityData,
2229
- etype: string
3200
+ uniques: string[],
3201
+ etype: string,
2230
3202
  ) => {
3203
+ const EntityClass = this.nymph.getEntityClassByEtype(etype);
3204
+
2231
3205
  const runInsertQuery = async (
2232
3206
  name: string,
2233
3207
  value: any,
2234
- svalue: string
3208
+ svalue: string,
2235
3209
  ) => {
3210
+ if (
3211
+ typeof name !== 'string' ||
3212
+ !name.length ||
3213
+ name.match(/^\s|=|\s$/)
3214
+ ) {
3215
+ throw new EntityInvalidDataError(
3216
+ 'Property names must be non-empty strings without leading or trailing spaces or equals signs.',
3217
+ );
3218
+ }
3219
+
2236
3220
  if (value === undefined) {
2237
3221
  return;
2238
3222
  }
@@ -2240,47 +3224,38 @@ export default class MySQLDriver extends NymphDriver {
2240
3224
  typeof value === 'number'
2241
3225
  ? 'N'
2242
3226
  : typeof value === 'string'
2243
- ? 'S'
2244
- : svalue;
3227
+ ? 'S'
3228
+ : 'J';
3229
+ const jsonValue = storageValue === 'J' ? svalue : null;
3230
+
2245
3231
  const promises = [];
3232
+
2246
3233
  promises.push(
2247
3234
  this.queryRun(
2248
3235
  `INSERT INTO ${MySQLDriver.escape(
2249
- `${this.prefix}data_${etype}`
2250
- )} (\`guid\`, \`name\`, \`value\`) VALUES (UNHEX(@guid), @name, @storageValue);`,
3236
+ `${this.prefix}data_${etype}`,
3237
+ )} (\`guid\`, \`name\`, \`value\`, \`json\`, \`string\`, \`number\`, \`truthy\`) VALUES (UNHEX(@guid), @name, @storageValue, @jsonValue, @string, @number, @truthy);`,
2251
3238
  {
2252
3239
  etypes: [etype],
2253
3240
  params: {
2254
3241
  guid,
2255
3242
  name,
2256
3243
  storageValue,
2257
- },
2258
- }
2259
- )
2260
- );
2261
- promises.push(
2262
- this.queryRun(
2263
- `INSERT INTO ${MySQLDriver.escape(
2264
- `${this.prefix}comparisons_${etype}`
2265
- )} (\`guid\`, \`name\`, \`truthy\`, \`string\`, \`number\`) VALUES (UNHEX(@guid), @name, @truthy, @string, @number);`,
2266
- {
2267
- etypes: [etype],
2268
- params: {
2269
- guid,
2270
- name,
2271
- truthy: !!value,
2272
- string: `${value}`,
3244
+ jsonValue,
3245
+ string: storageValue === 'J' ? null : `${value}`,
2273
3246
  number: isNaN(Number(value)) ? null : Number(value),
3247
+ truthy: !!value,
2274
3248
  },
2275
- }
2276
- )
3249
+ },
3250
+ ),
2277
3251
  );
3252
+
2278
3253
  const references = this.findReferences(svalue);
2279
3254
  for (const reference of references) {
2280
3255
  promises.push(
2281
3256
  this.queryRun(
2282
3257
  `INSERT INTO ${MySQLDriver.escape(
2283
- `${this.prefix}references_${etype}`
3258
+ `${this.prefix}references_${etype}`,
2284
3259
  )} (\`guid\`, \`name\`, \`reference\`) VALUES (UNHEX(@guid), @name, UNHEX(@reference));`,
2285
3260
  {
2286
3261
  etypes: [etype],
@@ -2289,12 +3264,85 @@ export default class MySQLDriver extends NymphDriver {
2289
3264
  name,
2290
3265
  reference,
2291
3266
  },
2292
- }
2293
- )
3267
+ },
3268
+ ),
2294
3269
  );
2295
3270
  }
3271
+
3272
+ let tokenString: string | null = null;
3273
+ try {
3274
+ tokenString = EntityClass.getFTSText(name, value);
3275
+ } catch (e: any) {
3276
+ // Ignore error.
3277
+ }
3278
+
3279
+ if (tokenString != null) {
3280
+ const tokens = this.tokenizer.tokenize(tokenString);
3281
+ while (tokens.length) {
3282
+ const currentTokens = tokens.splice(0, 100);
3283
+ const params: { [k: string]: any } = {
3284
+ guid,
3285
+ name,
3286
+ };
3287
+ const values: string[] = [];
3288
+
3289
+ for (let i = 0; i < currentTokens.length; i++) {
3290
+ const token = currentTokens[i];
3291
+ params['token' + i] = token.token;
3292
+ params['position' + i] = token.position;
3293
+ params['stem' + i] = token.stem;
3294
+ values.push(
3295
+ '(UNHEX(@guid), @name, @token' +
3296
+ i +
3297
+ ', @position' +
3298
+ i +
3299
+ ', @stem' +
3300
+ i +
3301
+ ')',
3302
+ );
3303
+ }
3304
+
3305
+ promises.push(
3306
+ this.queryRun(
3307
+ `INSERT INTO ${MySQLDriver.escape(
3308
+ `${this.prefix}tokens_${etype}`,
3309
+ )} (\`guid\`, \`name\`, \`token\`, \`position\`, \`stem\`) VALUES ${values.join(', ')};`,
3310
+ {
3311
+ etypes: [etype],
3312
+ params,
3313
+ },
3314
+ ),
3315
+ );
3316
+ }
3317
+ }
3318
+
2296
3319
  await Promise.all(promises);
2297
3320
  };
3321
+
3322
+ for (const unique of uniques) {
3323
+ try {
3324
+ await this.queryRun(
3325
+ `INSERT INTO ${MySQLDriver.escape(
3326
+ `${this.prefix}uniques_${etype}`,
3327
+ )} (\`guid\`, \`unique\`) VALUES (UNHEX(@guid), @unique);`,
3328
+ {
3329
+ etypes: [etype],
3330
+ params: {
3331
+ guid,
3332
+ unique,
3333
+ },
3334
+ },
3335
+ );
3336
+ } catch (e: any) {
3337
+ if (e instanceof EntityUniqueConstraintError) {
3338
+ this.nymph.config.debugError(
3339
+ 'mysql',
3340
+ `Save entity unique constraint violation for GUID "${guid}" on etype "${etype}": "${unique}"`,
3341
+ );
3342
+ }
3343
+ throw e;
3344
+ }
3345
+ }
2298
3346
  for (const name in data) {
2299
3347
  await runInsertQuery(name, data[name], JSON.stringify(data[name]));
2300
3348
  }
@@ -2302,109 +3350,207 @@ export default class MySQLDriver extends NymphDriver {
2302
3350
  await runInsertQuery(name, JSON.parse(sdata[name]), sdata[name]);
2303
3351
  }
2304
3352
  };
3353
+ let inTransaction = false;
2305
3354
  try {
2306
3355
  const result = await this.saveEntityRowLike(
2307
3356
  entity,
2308
- async (_entity, guid, tags, data, sdata, cdate, etype) => {
3357
+ async ({ guid, tags, data, sdata, uniques, cdate, etype }) => {
3358
+ if (
3359
+ Object.keys(data).length === 0 &&
3360
+ Object.keys(sdata).length === 0
3361
+ ) {
3362
+ throw new EntityInvalidDataError('Entity contains no data.');
3363
+ }
3364
+ for (let tag of tags) {
3365
+ if (
3366
+ typeof tag !== 'string' ||
3367
+ !tag.length ||
3368
+ tag.match(/[\x00-\x1F\x7F\[\],]/)
3369
+ ) {
3370
+ throw new EntityInvalidDataError(
3371
+ 'Tags must be non-empty strings without square brackets, control characters, or commas.',
3372
+ );
3373
+ }
3374
+ }
3375
+ let processedData = this.removeAndReturnACValues(
3376
+ etype,
3377
+ { ...data },
3378
+ { ...sdata },
3379
+ );
3380
+ ({ data, sdata } = processedData);
3381
+ let {
3382
+ user,
3383
+ group,
3384
+ acUser,
3385
+ acGroup,
3386
+ acOther,
3387
+ acRead,
3388
+ acWrite,
3389
+ acFull,
3390
+ } = processedData;
2309
3391
  await this.queryRun(
2310
3392
  `INSERT INTO ${MySQLDriver.escape(
2311
- `${this.prefix}entities_${etype}`
2312
- )} (\`guid\`, \`tags\`, \`cdate\`, \`mdate\`) VALUES (UNHEX(@guid), @tags, @cdate, @cdate);`,
3393
+ `${this.prefix}entities_${etype}`,
3394
+ )} (\`guid\`, \`tags\`, \`cdate\`, \`mdate\`, \`user\`, \`group\`, \`acUser\`, \`acGroup\`, \`acOther\`, \`acRead\`, \`acWrite\`, \`acFull\`) VALUES (UNHEX(@guid), @tags, @cdate, @cdate, ${user == null ? '@user' : 'UNHEX(@user)'}, ${group == null ? '@group' : 'UNHEX(@group)'}, @acUser, @acGroup, @acOther, @acRead, @acWrite, @acFull);`,
2313
3395
  {
2314
3396
  etypes: [etype],
2315
3397
  params: {
2316
3398
  guid,
2317
- tags: ' ' + tags.join(' ') + ' ',
3399
+ tags: ' ' + MySQLDriver.escapeTags(tags).join(' ') + ' ',
2318
3400
  cdate,
3401
+ user,
3402
+ group,
3403
+ acUser,
3404
+ acGroup,
3405
+ acOther,
3406
+ acRead: acRead && ' ' + acRead.join(' ') + ' ',
3407
+ acWrite: acWrite && ' ' + acWrite.join(' ') + ' ',
3408
+ acFull: acFull && ' ' + acFull.join(' ') + ' ',
2319
3409
  },
2320
- }
3410
+ },
2321
3411
  );
2322
- await insertData(guid, data, sdata, etype);
3412
+ await insertData(guid, data, sdata, uniques, etype);
2323
3413
  return true;
2324
3414
  },
2325
- async (entity, guid, tags, data, sdata, mdate, etype) => {
3415
+ async ({ entity, guid, tags, data, sdata, uniques, mdate, etype }) => {
3416
+ if (
3417
+ Object.keys(data).length === 0 &&
3418
+ Object.keys(sdata).length === 0
3419
+ ) {
3420
+ throw new EntityInvalidDataError('Entity contains no data.');
3421
+ }
3422
+ for (let tag of tags) {
3423
+ if (
3424
+ typeof tag !== 'string' ||
3425
+ !tag.length ||
3426
+ tag.match(/[\x00-\x1F\x7F\[\],]/)
3427
+ ) {
3428
+ throw new EntityInvalidDataError(
3429
+ 'Tags must be non-empty strings without square brackets, control characters, or commas.',
3430
+ );
3431
+ }
3432
+ }
3433
+ let processedData = this.removeAndReturnACValues(
3434
+ etype,
3435
+ { ...data },
3436
+ { ...sdata },
3437
+ );
3438
+ ({ data, sdata } = processedData);
3439
+ let {
3440
+ user,
3441
+ group,
3442
+ acUser,
3443
+ acGroup,
3444
+ acOther,
3445
+ acRead,
3446
+ acWrite,
3447
+ acFull,
3448
+ } = processedData;
2326
3449
  if (this.config.rowLocking) {
2327
3450
  const promises = [];
2328
3451
  promises.push(
2329
3452
  this.queryRun(
2330
3453
  `SELECT 1 FROM ${MySQLDriver.escape(
2331
- `${this.prefix}entities_${etype}`
3454
+ `${this.prefix}entities_${etype}`,
2332
3455
  )} WHERE \`guid\`=UNHEX(@guid) GROUP BY 1 FOR UPDATE;`,
2333
3456
  {
2334
3457
  etypes: [etype],
2335
3458
  params: {
2336
3459
  guid,
2337
3460
  },
2338
- }
2339
- )
3461
+ },
3462
+ ),
2340
3463
  );
2341
3464
  promises.push(
2342
3465
  this.queryRun(
2343
3466
  `SELECT 1 FROM ${MySQLDriver.escape(
2344
- `${this.prefix}data_${etype}`
3467
+ `${this.prefix}data_${etype}`,
2345
3468
  )} WHERE \`guid\`=UNHEX(@guid) GROUP BY 1 FOR UPDATE;`,
2346
3469
  {
2347
3470
  etypes: [etype],
2348
3471
  params: {
2349
3472
  guid,
2350
3473
  },
2351
- }
2352
- )
3474
+ },
3475
+ ),
2353
3476
  );
2354
3477
  promises.push(
2355
3478
  this.queryRun(
2356
3479
  `SELECT 1 FROM ${MySQLDriver.escape(
2357
- `${this.prefix}comparisons_${etype}`
3480
+ `${this.prefix}references_${etype}`,
2358
3481
  )} WHERE \`guid\`=UNHEX(@guid) GROUP BY 1 FOR UPDATE;`,
2359
3482
  {
2360
3483
  etypes: [etype],
2361
3484
  params: {
2362
3485
  guid,
2363
3486
  },
2364
- }
2365
- )
3487
+ },
3488
+ ),
2366
3489
  );
2367
3490
  promises.push(
2368
3491
  this.queryRun(
2369
3492
  `SELECT 1 FROM ${MySQLDriver.escape(
2370
- `${this.prefix}references_${etype}`
3493
+ `${this.prefix}tokens_${etype}`,
2371
3494
  )} WHERE \`guid\`=UNHEX(@guid) GROUP BY 1 FOR UPDATE;`,
2372
3495
  {
2373
3496
  etypes: [etype],
2374
3497
  params: {
2375
3498
  guid,
2376
3499
  },
2377
- }
2378
- )
3500
+ },
3501
+ ),
3502
+ );
3503
+ promises.push(
3504
+ this.queryRun(
3505
+ `SELECT 1 FROM ${MySQLDriver.escape(
3506
+ `${this.prefix}uniques_${etype}`,
3507
+ )} WHERE \`guid\`=UNHEX(@guid) GROUP BY 1 FOR UPDATE;`,
3508
+ {
3509
+ etypes: [etype],
3510
+ params: {
3511
+ guid,
3512
+ },
3513
+ },
3514
+ ),
2379
3515
  );
2380
3516
  await Promise.all(promises);
2381
3517
  }
2382
3518
  if (this.config.tableLocking) {
2383
3519
  await this.queryRun(
2384
3520
  `LOCK TABLES ${MySQLDriver.escape(
2385
- `${this.prefix}entities_${etype}`
3521
+ `${this.prefix}entities_${etype}`,
2386
3522
  )} WRITE, ${MySQLDriver.escape(
2387
- `${this.prefix}data_${etype}`
3523
+ `${this.prefix}data_${etype}`,
2388
3524
  )} WRITE, ${MySQLDriver.escape(
2389
- `${this.prefix}comparisons_${etype}`
3525
+ `${this.prefix}references_${etype}`,
2390
3526
  )} WRITE, ${MySQLDriver.escape(
2391
- `${this.prefix}references_${etype}`
2392
- )} WRITE;`
3527
+ `${this.prefix}tokens_${etype}`,
3528
+ )} WRITE, ${MySQLDriver.escape(
3529
+ `${this.prefix}uniques_${etype}`,
3530
+ )} WRITE;`,
2393
3531
  );
2394
3532
  }
2395
3533
  const info = await this.queryRun(
2396
3534
  `UPDATE ${MySQLDriver.escape(
2397
- `${this.prefix}entities_${etype}`
2398
- )} SET \`tags\`=@tags, \`mdate\`=@mdate WHERE \`guid\`=UNHEX(@guid) AND \`mdate\` <= @emdate;`,
3535
+ `${this.prefix}entities_${etype}`,
3536
+ )} SET \`tags\`=@tags, \`mdate\`=@mdate, \`user\`=${user == null ? '@user' : 'UNHEX(@user)'}, \`group\`=${group == null ? '@group' : 'UNHEX(@group)'}, \`acUser\`=@acUser, \`acGroup\`=@acGroup, \`acOther\`=@acOther, \`acRead\`=@acRead, \`acWrite\`=@acWrite, \`acFull\`=@acFull WHERE \`guid\`=UNHEX(@guid) AND \`mdate\` <= @emdate;`,
2399
3537
  {
2400
3538
  etypes: [etype],
2401
3539
  params: {
2402
- tags: ' ' + tags.join(' ') + ' ',
3540
+ tags: ' ' + MySQLDriver.escapeTags(tags).join(' ') + ' ',
2403
3541
  mdate,
3542
+ user,
3543
+ group,
3544
+ acUser,
3545
+ acGroup,
3546
+ acOther,
3547
+ acRead: acRead && ' ' + acRead.join(' ') + ' ',
3548
+ acWrite: acWrite && ' ' + acWrite.join(' ') + ' ',
3549
+ acFull: acFull && ' ' + acFull.join(' ') + ' ',
2404
3550
  guid,
2405
3551
  emdate: isNaN(Number(entity.mdate)) ? 0 : Number(entity.mdate),
2406
3552
  },
2407
- }
3553
+ },
2408
3554
  );
2409
3555
  let success = false;
2410
3556
  if (info.changes === 1) {
@@ -2412,67 +3558,92 @@ export default class MySQLDriver extends NymphDriver {
2412
3558
  promises.push(
2413
3559
  this.queryRun(
2414
3560
  `DELETE FROM ${MySQLDriver.escape(
2415
- `${this.prefix}data_${etype}`
3561
+ `${this.prefix}data_${etype}`,
2416
3562
  )} WHERE \`guid\`=UNHEX(@guid);`,
2417
3563
  {
2418
3564
  etypes: [etype],
2419
3565
  params: {
2420
3566
  guid,
2421
3567
  },
2422
- }
2423
- )
3568
+ },
3569
+ ),
2424
3570
  );
2425
3571
  promises.push(
2426
3572
  this.queryRun(
2427
3573
  `DELETE FROM ${MySQLDriver.escape(
2428
- `${this.prefix}comparisons_${etype}`
3574
+ `${this.prefix}references_${etype}`,
2429
3575
  )} WHERE \`guid\`=UNHEX(@guid);`,
2430
3576
  {
2431
3577
  etypes: [etype],
2432
3578
  params: {
2433
3579
  guid,
2434
3580
  },
2435
- }
2436
- )
3581
+ },
3582
+ ),
2437
3583
  );
2438
3584
  promises.push(
2439
3585
  this.queryRun(
2440
3586
  `DELETE FROM ${MySQLDriver.escape(
2441
- `${this.prefix}references_${etype}`
3587
+ `${this.prefix}tokens_${etype}`,
2442
3588
  )} WHERE \`guid\`=UNHEX(@guid);`,
2443
3589
  {
2444
3590
  etypes: [etype],
2445
3591
  params: {
2446
3592
  guid,
2447
3593
  },
2448
- }
2449
- )
3594
+ },
3595
+ ),
3596
+ );
3597
+ promises.push(
3598
+ this.queryRun(
3599
+ `DELETE FROM ${MySQLDriver.escape(
3600
+ `${this.prefix}uniques_${etype}`,
3601
+ )} WHERE \`guid\`=UNHEX(@guid);`,
3602
+ {
3603
+ etypes: [etype],
3604
+ params: {
3605
+ guid,
3606
+ },
3607
+ },
3608
+ ),
2450
3609
  );
2451
3610
  await Promise.all(promises);
2452
- await insertData(guid, data, sdata, etype);
3611
+ await insertData(guid, data, sdata, uniques, etype);
2453
3612
  success = true;
2454
3613
  }
2455
3614
  if (this.config.tableLocking) {
2456
3615
  await this.queryRun('UNLOCK TABLES;');
2457
3616
  }
3617
+ if (!success && info.changes === 0) {
3618
+ throw new EntityConflictError(
3619
+ "Entity either doesn't exist or is newer in the DB.",
3620
+ );
3621
+ }
2458
3622
  return success;
2459
3623
  },
2460
3624
  async () => {
2461
3625
  await this.internalTransaction('nymph-save');
3626
+ inTransaction = true;
2462
3627
  },
2463
3628
  async (success) => {
2464
- if (success) {
2465
- await this.commit('nymph-save');
2466
- } else {
2467
- await this.rollback('nymph-save');
3629
+ if (inTransaction) {
3630
+ inTransaction = false;
3631
+ if (success) {
3632
+ success = await this.commit('nymph-save');
3633
+ } else {
3634
+ await this.rollback('nymph-save');
3635
+ }
2468
3636
  }
2469
3637
  return success;
2470
- }
3638
+ },
2471
3639
  );
2472
3640
 
2473
3641
  return result;
2474
3642
  } catch (e: any) {
2475
- await this.rollback('nymph-save');
3643
+ this.nymph.config.debugError('mysql', `Save entity error: "${e}"`);
3644
+ if (inTransaction) {
3645
+ await this.rollback('nymph-save');
3646
+ }
2476
3647
  throw e;
2477
3648
  }
2478
3649
  }
@@ -2481,58 +3652,214 @@ export default class MySQLDriver extends NymphDriver {
2481
3652
  if (name == null) {
2482
3653
  throw new InvalidParametersError('Name not given for UID.');
2483
3654
  }
3655
+ if (name.length > 128) {
3656
+ throw new InvalidParametersError('UID name too long. 128 chars max.');
3657
+ }
2484
3658
  await this.queryRun(
2485
3659
  `INSERT INTO ${MySQLDriver.escape(
2486
- `${this.prefix}uids`
3660
+ `${this.prefix}uids`,
2487
3661
  )} (\`name\`, \`cur_uid\`) VALUES (@name, @curUid) ON DUPLICATE KEY UPDATE \`cur_uid\`=@curUid;`,
2488
3662
  {
2489
3663
  params: {
2490
3664
  name,
2491
3665
  curUid,
2492
3666
  },
2493
- }
3667
+ },
2494
3668
  );
2495
3669
  return true;
2496
3670
  }
2497
3671
 
2498
- private async internalTransaction(name: string) {
3672
+ protected async internalTransaction(name: string, setOnSelf = true) {
2499
3673
  if (name == null || typeof name !== 'string' || name.length === 0) {
2500
3674
  throw new InvalidParametersError(
2501
- 'Transaction start attempted without a name.'
3675
+ 'Transaction start attempted without a name.',
2502
3676
  );
2503
3677
  }
2504
3678
 
2505
- if (!this.transaction || this.transaction.count === 0) {
3679
+ let transaction = this.transaction;
3680
+
3681
+ if (!transaction) {
2506
3682
  // Lock to one connection.
2507
- this.transaction = {
3683
+ transaction = {
2508
3684
  count: 0,
2509
3685
  connection: await this.getConnection(),
3686
+ latestPromise: Promise.resolve(),
2510
3687
  };
2511
- if (this.config.transactions) {
2512
- // We're not in a transaction yet, so start one.
2513
- await this.queryRun('START TRANSACTION;');
3688
+ if (setOnSelf) {
3689
+ this.transaction = transaction;
2514
3690
  }
2515
3691
  }
2516
3692
 
2517
- if (this.config.transactions) {
2518
- await this.queryRun(`SAVEPOINT ${MySQLDriver.escape(name)};`);
3693
+ if (this.config.transactions && transaction.count === 0) {
3694
+ // We're not in a transaction yet, so start one.
3695
+ await this.queryRun('START TRANSACTION;', { transaction });
2519
3696
  }
2520
3697
 
2521
- this.transaction.count++;
3698
+ transaction.count++;
3699
+
3700
+ if (this.config.transactions) {
3701
+ await this.queryRun(`SAVEPOINT ${MySQLDriver.escape(name)};`, {
3702
+ transaction,
3703
+ });
3704
+ }
2522
3705
 
2523
- return this.transaction;
3706
+ return transaction;
2524
3707
  }
2525
3708
 
2526
3709
  public async startTransaction(name: string) {
2527
- const inTransaction = this.inTransaction();
2528
- const transaction = await this.internalTransaction(name);
2529
- if (!inTransaction) {
2530
- this.transaction = null;
2531
- }
3710
+ const transaction = await this.internalTransaction(name, false);
2532
3711
 
2533
3712
  const nymph = this.nymph.clone();
2534
3713
  (nymph.driver as MySQLDriver).transaction = transaction;
2535
3714
 
2536
3715
  return nymph;
2537
3716
  }
3717
+
3718
+ private async removeTilmeldOldRows(etype: string) {
3719
+ await this.internalTransaction('nymph-remove-tilmeld-rows');
3720
+ try {
3721
+ for (let name of [
3722
+ 'user',
3723
+ 'group',
3724
+ 'acUser',
3725
+ 'acGroup',
3726
+ 'acOther',
3727
+ 'acRead',
3728
+ 'acWrite',
3729
+ 'acFull',
3730
+ ]) {
3731
+ await this.queryRun(
3732
+ `DELETE FROM ${MySQLDriver.escape(
3733
+ `${this.prefix}data_${etype}`,
3734
+ )} WHERE \`name\`=@name;`,
3735
+ {
3736
+ etypes: [etype],
3737
+ params: {
3738
+ name,
3739
+ },
3740
+ },
3741
+ );
3742
+ await this.queryRun(
3743
+ `DELETE FROM ${MySQLDriver.escape(
3744
+ `${this.prefix}references_${etype}`,
3745
+ )} WHERE \`name\`=@name;`,
3746
+ {
3747
+ etypes: [etype],
3748
+ params: {
3749
+ name,
3750
+ },
3751
+ },
3752
+ );
3753
+ await this.queryRun(
3754
+ `DELETE FROM ${MySQLDriver.escape(
3755
+ `${this.prefix}tokens_${etype}`,
3756
+ )} WHERE \`name\`=@name;`,
3757
+ {
3758
+ etypes: [etype],
3759
+ params: {
3760
+ name,
3761
+ },
3762
+ },
3763
+ );
3764
+ }
3765
+ } catch (e: any) {
3766
+ this.nymph.config.debugError(
3767
+ 'mysql',
3768
+ `Remove tilmeld rows error: "${e}"`,
3769
+ );
3770
+ await this.rollback('nymph-remove-tilmeld-rows');
3771
+ throw e;
3772
+ }
3773
+
3774
+ await this.commit('nymph-remove-tilmeld-rows');
3775
+ return true;
3776
+ }
3777
+
3778
+ public async needsMigration(): Promise<
3779
+ 'json' | 'tokens' | 'tilmeldColumns' | false
3780
+ > {
3781
+ const table = await this.queryGet(
3782
+ 'SELECT `table_name` AS `table_name` FROM `information_schema`.`tables` WHERE `table_schema`=@db AND `table_name` LIKE @prefix LIMIT 1;',
3783
+ {
3784
+ params: {
3785
+ db: this.config.database,
3786
+ prefix: this.prefix + 'data_' + '%',
3787
+ },
3788
+ },
3789
+ );
3790
+ if (table?.table_name) {
3791
+ const result = await this.queryGet(
3792
+ "SELECT 1 AS `exists` FROM `information_schema`.`columns` WHERE `table_schema`=@db AND `table_name`=@table AND `column_name`='json';",
3793
+ {
3794
+ params: {
3795
+ db: this.config.database,
3796
+ table: table.table_name,
3797
+ },
3798
+ },
3799
+ );
3800
+ if (!result?.exists) {
3801
+ return 'json';
3802
+ }
3803
+ }
3804
+ const table2 = await this.queryGet(
3805
+ 'SELECT `table_name` AS `table_name` FROM `information_schema`.`tables` WHERE `table_schema`=@db AND `table_name` LIKE @tokenTable LIMIT 1;',
3806
+ {
3807
+ params: {
3808
+ db: this.config.database,
3809
+ tokenTable: this.prefix + 'tokens_' + '%',
3810
+ },
3811
+ },
3812
+ );
3813
+ if (!table2 || !table2.table_name) {
3814
+ return 'tokens';
3815
+ }
3816
+ const table3 = await this.queryGet(
3817
+ 'SELECT `table_name` AS `table_name` FROM `information_schema`.`tables` WHERE `table_schema`=@db AND `table_name` LIKE @prefix LIMIT 1;',
3818
+ {
3819
+ params: {
3820
+ db: this.config.database,
3821
+ prefix: this.prefix + 'entities_' + '%',
3822
+ },
3823
+ },
3824
+ );
3825
+ if (table3?.table_name) {
3826
+ const result = await this.queryGet(
3827
+ "SELECT 1 AS `exists` FROM `information_schema`.`columns` WHERE `table_schema`=@db AND `table_name`=@table AND `column_name`='user';",
3828
+ {
3829
+ params: {
3830
+ db: this.config.database,
3831
+ table: table3.table_name,
3832
+ },
3833
+ },
3834
+ );
3835
+ if (!result?.exists) {
3836
+ return 'tilmeldColumns';
3837
+ }
3838
+ }
3839
+ return false;
3840
+ }
3841
+
3842
+ public async liveMigration(
3843
+ migrationType: 'tokenTables' | 'tilmeldColumns' | 'tilmeldRemoveOldRows',
3844
+ ) {
3845
+ if (migrationType === 'tokenTables') {
3846
+ const etypes = await this.getEtypes();
3847
+
3848
+ for (let etype of etypes) {
3849
+ await this.createTokensTable(etype);
3850
+ }
3851
+ } else if (migrationType === 'tilmeldColumns') {
3852
+ const etypes = await this.getEtypes();
3853
+
3854
+ for (let etype of etypes) {
3855
+ await this.addTilmeldColumnsAndIndexes(etype);
3856
+ }
3857
+ } else if (migrationType === 'tilmeldRemoveOldRows') {
3858
+ const etypes = await this.getEtypes();
3859
+
3860
+ for (let etype of etypes) {
3861
+ await this.removeTilmeldOldRows(etype);
3862
+ }
3863
+ }
3864
+ }
2538
3865
  }