typeorm 0.3.6-dev.4687be8 → 0.3.6-dev.62518ae

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/README.md +33 -4
  2. package/browser/cache/DbQueryResultCache.js +9 -1
  3. package/browser/cache/DbQueryResultCache.js.map +1 -1
  4. package/browser/data-source/DataSourceOptions.d.ts +2 -1
  5. package/browser/data-source/DataSourceOptions.js.map +1 -1
  6. package/browser/decorator/Index.js +1 -0
  7. package/browser/decorator/Index.js.map +1 -1
  8. package/browser/decorator/columns/PrimaryColumn.js +4 -1
  9. package/browser/decorator/columns/PrimaryColumn.js.map +1 -1
  10. package/browser/decorator/options/IndexOptions.d.ts +8 -0
  11. package/browser/decorator/options/IndexOptions.js.map +1 -1
  12. package/browser/driver/DriverFactory.js +4 -0
  13. package/browser/driver/DriverFactory.js.map +1 -1
  14. package/browser/driver/spanner/SpannerConnectionCredentialsOptions.d.ts +17 -0
  15. package/browser/driver/spanner/SpannerConnectionCredentialsOptions.js +3 -0
  16. package/browser/driver/spanner/SpannerConnectionCredentialsOptions.js.map +1 -0
  17. package/browser/driver/spanner/SpannerConnectionOptions.d.ts +120 -0
  18. package/browser/driver/spanner/SpannerConnectionOptions.js +3 -0
  19. package/browser/driver/spanner/SpannerConnectionOptions.js.map +1 -0
  20. package/browser/driver/spanner/SpannerDriver.d.ts +240 -0
  21. package/browser/driver/spanner/SpannerDriver.js +565 -0
  22. package/browser/driver/spanner/SpannerDriver.js.map +1 -0
  23. package/browser/driver/spanner/SpannerQueryRunner.d.ts +350 -0
  24. package/browser/driver/spanner/SpannerQueryRunner.js +1359 -0
  25. package/browser/driver/spanner/SpannerQueryRunner.js.map +1 -0
  26. package/browser/driver/types/ColumnTypes.d.ts +1 -1
  27. package/browser/driver/types/ColumnTypes.js.map +1 -1
  28. package/browser/driver/types/DatabaseType.d.ts +1 -1
  29. package/browser/driver/types/DatabaseType.js.map +1 -1
  30. package/browser/entity-schema/EntitySchemaIndexOptions.d.ts +8 -0
  31. package/browser/entity-schema/EntitySchemaIndexOptions.js.map +1 -1
  32. package/browser/entity-schema/EntitySchemaTransformer.js +1 -0
  33. package/browser/entity-schema/EntitySchemaTransformer.js.map +1 -1
  34. package/browser/logger/AdvancedConsoleLogger.d.ts +1 -1
  35. package/browser/logger/AdvancedConsoleLogger.js +1 -1
  36. package/browser/logger/AdvancedConsoleLogger.js.map +1 -1
  37. package/browser/metadata/IndexMetadata.d.ts +8 -0
  38. package/browser/metadata/IndexMetadata.js +9 -0
  39. package/browser/metadata/IndexMetadata.js.map +1 -1
  40. package/browser/metadata-args/IndexMetadataArgs.d.ts +8 -0
  41. package/browser/metadata-args/IndexMetadataArgs.js.map +1 -1
  42. package/browser/metadata-builder/EntityMetadataBuilder.js +13 -6
  43. package/browser/metadata-builder/EntityMetadataBuilder.js.map +1 -1
  44. package/browser/metadata-builder/JunctionEntityMetadataBuilder.js +13 -6
  45. package/browser/metadata-builder/JunctionEntityMetadataBuilder.js.map +1 -1
  46. package/browser/platform/PlatformTools.js +5 -0
  47. package/browser/platform/PlatformTools.js.map +1 -1
  48. package/browser/query-builder/InsertQueryBuilder.js +15 -3
  49. package/browser/query-builder/InsertQueryBuilder.js.map +1 -1
  50. package/browser/query-builder/SelectQueryBuilder.js +14 -2
  51. package/browser/query-builder/SelectQueryBuilder.js.map +1 -1
  52. package/browser/query-builder/UpdateQueryBuilder.js +18 -7
  53. package/browser/query-builder/UpdateQueryBuilder.js.map +1 -1
  54. package/browser/schema-builder/RdbmsSchemaBuilder.js +15 -1
  55. package/browser/schema-builder/RdbmsSchemaBuilder.js.map +1 -1
  56. package/browser/schema-builder/options/TableIndexOptions.d.ts +8 -0
  57. package/browser/schema-builder/options/TableIndexOptions.js.map +1 -1
  58. package/browser/schema-builder/table/TableIndex.d.ts +8 -0
  59. package/browser/schema-builder/table/TableIndex.js +3 -0
  60. package/browser/schema-builder/table/TableIndex.js.map +1 -1
  61. package/cache/DbQueryResultCache.js +9 -1
  62. package/cache/DbQueryResultCache.js.map +1 -1
  63. package/data-source/DataSourceOptions.d.ts +2 -1
  64. package/data-source/DataSourceOptions.js.map +1 -1
  65. package/decorator/Index.js +1 -0
  66. package/decorator/Index.js.map +1 -1
  67. package/decorator/columns/PrimaryColumn.js +4 -1
  68. package/decorator/columns/PrimaryColumn.js.map +1 -1
  69. package/decorator/options/IndexOptions.d.ts +8 -0
  70. package/decorator/options/IndexOptions.js.map +1 -1
  71. package/driver/DriverFactory.js +4 -0
  72. package/driver/DriverFactory.js.map +1 -1
  73. package/driver/spanner/SpannerConnectionCredentialsOptions.d.ts +17 -0
  74. package/driver/spanner/SpannerConnectionCredentialsOptions.js +4 -0
  75. package/driver/spanner/SpannerConnectionCredentialsOptions.js.map +1 -0
  76. package/driver/spanner/SpannerConnectionOptions.d.ts +120 -0
  77. package/driver/spanner/SpannerConnectionOptions.js +4 -0
  78. package/driver/spanner/SpannerConnectionOptions.js.map +1 -0
  79. package/driver/spanner/SpannerDriver.d.ts +240 -0
  80. package/driver/spanner/SpannerDriver.js +569 -0
  81. package/driver/spanner/SpannerDriver.js.map +1 -0
  82. package/driver/spanner/SpannerQueryRunner.d.ts +350 -0
  83. package/driver/spanner/SpannerQueryRunner.js +1363 -0
  84. package/driver/spanner/SpannerQueryRunner.js.map +1 -0
  85. package/driver/types/ColumnTypes.d.ts +1 -1
  86. package/driver/types/ColumnTypes.js.map +1 -1
  87. package/driver/types/DatabaseType.d.ts +1 -1
  88. package/driver/types/DatabaseType.js.map +1 -1
  89. package/entity-schema/EntitySchemaIndexOptions.d.ts +8 -0
  90. package/entity-schema/EntitySchemaIndexOptions.js.map +1 -1
  91. package/entity-schema/EntitySchemaTransformer.js +1 -0
  92. package/entity-schema/EntitySchemaTransformer.js.map +1 -1
  93. package/logger/AdvancedConsoleLogger.d.ts +1 -1
  94. package/logger/AdvancedConsoleLogger.js +1 -1
  95. package/logger/AdvancedConsoleLogger.js.map +1 -1
  96. package/metadata/IndexMetadata.d.ts +8 -0
  97. package/metadata/IndexMetadata.js +9 -0
  98. package/metadata/IndexMetadata.js.map +1 -1
  99. package/metadata-args/IndexMetadataArgs.d.ts +8 -0
  100. package/metadata-args/IndexMetadataArgs.js.map +1 -1
  101. package/metadata-builder/EntityMetadataBuilder.js +13 -6
  102. package/metadata-builder/EntityMetadataBuilder.js.map +1 -1
  103. package/metadata-builder/JunctionEntityMetadataBuilder.js +13 -6
  104. package/metadata-builder/JunctionEntityMetadataBuilder.js.map +1 -1
  105. package/package.json +1 -1
  106. package/platform/PlatformTools.js +5 -0
  107. package/platform/PlatformTools.js.map +1 -1
  108. package/query-builder/InsertQueryBuilder.js +15 -3
  109. package/query-builder/InsertQueryBuilder.js.map +1 -1
  110. package/query-builder/SelectQueryBuilder.js +14 -2
  111. package/query-builder/SelectQueryBuilder.js.map +1 -1
  112. package/query-builder/UpdateQueryBuilder.js +18 -7
  113. package/query-builder/UpdateQueryBuilder.js.map +1 -1
  114. package/schema-builder/RdbmsSchemaBuilder.js +15 -1
  115. package/schema-builder/RdbmsSchemaBuilder.js.map +1 -1
  116. package/schema-builder/options/TableIndexOptions.d.ts +8 -0
  117. package/schema-builder/options/TableIndexOptions.js.map +1 -1
  118. package/schema-builder/table/TableIndex.d.ts +8 -0
  119. package/schema-builder/table/TableIndex.js +3 -0
  120. package/schema-builder/table/TableIndex.js.map +1 -1
@@ -0,0 +1,1359 @@
1
+ import { QueryFailedError } from "../../error/QueryFailedError";
2
+ import { QueryRunnerAlreadyReleasedError } from "../../error/QueryRunnerAlreadyReleasedError";
3
+ import { TransactionNotStartedError } from "../../error/TransactionNotStartedError";
4
+ import { BaseQueryRunner } from "../../query-runner/BaseQueryRunner";
5
+ import { Table } from "../../schema-builder/table/Table";
6
+ import { TableCheck } from "../../schema-builder/table/TableCheck";
7
+ import { TableColumn } from "../../schema-builder/table/TableColumn";
8
+ import { TableForeignKey } from "../../schema-builder/table/TableForeignKey";
9
+ import { TableIndex } from "../../schema-builder/table/TableIndex";
10
+ import { TableUnique } from "../../schema-builder/table/TableUnique";
11
+ import { View } from "../../schema-builder/view/View";
12
+ import { Broadcaster } from "../../subscriber/Broadcaster";
13
+ import { OrmUtils } from "../../util/OrmUtils";
14
+ import { Query } from "../Query";
15
+ import { TypeORMError } from "../../error";
16
+ import { QueryResult } from "../../query-runner/QueryResult";
17
+ import { MetadataTableType } from "../types/MetadataTableType";
18
+ /**
19
+ * Runs queries on a single postgres database connection.
20
+ */
21
+ export class SpannerQueryRunner extends BaseQueryRunner {
22
+ // -------------------------------------------------------------------------
23
+ // Constructor
24
+ // -------------------------------------------------------------------------
25
+ constructor(driver, mode) {
26
+ super();
27
+ this.driver = driver;
28
+ this.connection = driver.connection;
29
+ this.mode = mode;
30
+ this.broadcaster = new Broadcaster(this);
31
+ }
32
+ // -------------------------------------------------------------------------
33
+ // Public Methods
34
+ // -------------------------------------------------------------------------
35
+ /**
36
+ * Creates/uses database connection from the connection pool to perform further operations.
37
+ * Returns obtained database connection.
38
+ */
39
+ async connect() {
40
+ if (this.session) {
41
+ return Promise.resolve(this.session);
42
+ }
43
+ const [session] = await this.driver.instanceDatabase.createSession({});
44
+ this.session = session;
45
+ this.sessionTransaction = await session.transaction();
46
+ return this.session;
47
+ }
48
+ /**
49
+ * Releases used database connection.
50
+ * You cannot use query runner methods once its released.
51
+ */
52
+ async release() {
53
+ this.isReleased = true;
54
+ if (this.session) {
55
+ await this.session.delete();
56
+ }
57
+ this.session = undefined;
58
+ return Promise.resolve();
59
+ }
60
+ /**
61
+ * Starts transaction.
62
+ */
63
+ async startTransaction(isolationLevel) {
64
+ this.isTransactionActive = true;
65
+ try {
66
+ await this.broadcaster.broadcast("BeforeTransactionStart");
67
+ }
68
+ catch (err) {
69
+ this.isTransactionActive = false;
70
+ throw err;
71
+ }
72
+ await this.connect();
73
+ await this.sessionTransaction.begin();
74
+ this.connection.logger.logQuery("START TRANSACTION");
75
+ await this.broadcaster.broadcast("AfterTransactionStart");
76
+ }
77
+ /**
78
+ * Commits transaction.
79
+ * Error will be thrown if transaction was not started.
80
+ */
81
+ async commitTransaction() {
82
+ if (!this.isTransactionActive || !this.sessionTransaction)
83
+ throw new TransactionNotStartedError();
84
+ await this.broadcaster.broadcast("BeforeTransactionCommit");
85
+ await this.sessionTransaction.commit();
86
+ this.connection.logger.logQuery("COMMIT");
87
+ this.isTransactionActive = false;
88
+ await this.broadcaster.broadcast("AfterTransactionCommit");
89
+ }
90
+ /**
91
+ * Rollbacks transaction.
92
+ * Error will be thrown if transaction was not started.
93
+ */
94
+ async rollbackTransaction() {
95
+ if (!this.isTransactionActive || !this.sessionTransaction)
96
+ throw new TransactionNotStartedError();
97
+ await this.broadcaster.broadcast("BeforeTransactionRollback");
98
+ await this.sessionTransaction.rollback();
99
+ this.connection.logger.logQuery("ROLLBACK");
100
+ this.isTransactionActive = false;
101
+ await this.broadcaster.broadcast("AfterTransactionRollback");
102
+ }
103
+ /**
104
+ * Executes a given SQL query.
105
+ */
106
+ async query(query, parameters, useStructuredResult = false) {
107
+ if (this.isReleased)
108
+ throw new QueryRunnerAlreadyReleasedError();
109
+ try {
110
+ const queryStartTime = +new Date();
111
+ await this.connect();
112
+ let rawResult = undefined;
113
+ const isSelect = query.startsWith("SELECT");
114
+ const executor = isSelect && !this.isTransactionActive
115
+ ? this.driver.instanceDatabase
116
+ : this.sessionTransaction;
117
+ if (!this.isTransactionActive && !isSelect) {
118
+ await this.sessionTransaction.begin();
119
+ }
120
+ try {
121
+ this.driver.connection.logger.logQuery(query, parameters, this);
122
+ rawResult = await executor.run({
123
+ sql: query,
124
+ params: parameters
125
+ ? parameters.reduce((params, value, index) => {
126
+ params["param" + index] = value;
127
+ return params;
128
+ }, {})
129
+ : undefined,
130
+ json: true,
131
+ });
132
+ if (!this.isTransactionActive && !isSelect) {
133
+ await this.sessionTransaction.commit();
134
+ }
135
+ }
136
+ catch (error) {
137
+ try {
138
+ // we throw original error even if rollback thrown an error
139
+ if (!this.isTransactionActive && !isSelect)
140
+ await this.sessionTransaction.rollback();
141
+ }
142
+ catch (rollbackError) { }
143
+ throw error;
144
+ }
145
+ // log slow queries if maxQueryExecution time is set
146
+ const maxQueryExecutionTime = this.driver.options.maxQueryExecutionTime;
147
+ const queryEndTime = +new Date();
148
+ const queryExecutionTime = queryEndTime - queryStartTime;
149
+ if (maxQueryExecutionTime &&
150
+ queryExecutionTime > maxQueryExecutionTime)
151
+ this.driver.connection.logger.logQuerySlow(queryExecutionTime, query, parameters, this);
152
+ const result = new QueryResult();
153
+ result.raw = rawResult;
154
+ result.records = rawResult ? rawResult[0] : [];
155
+ if (rawResult && rawResult[1] && rawResult[1].rowCountExact) {
156
+ result.affected = parseInt(rawResult[1].rowCountExact);
157
+ }
158
+ if (!useStructuredResult) {
159
+ return result.records;
160
+ }
161
+ return result;
162
+ }
163
+ catch (err) {
164
+ this.driver.connection.logger.logQueryError(err, query, parameters, this);
165
+ throw new QueryFailedError(query, parameters, err);
166
+ }
167
+ finally {
168
+ }
169
+ }
170
+ /**
171
+ * Update database schema.
172
+ * Used for creating/altering/dropping tables, columns, indexes, etc.
173
+ *
174
+ * DDL changing queries should be executed by `updateSchema()` method.
175
+ */
176
+ async updateDDL(query, parameters) {
177
+ if (this.isReleased)
178
+ throw new QueryRunnerAlreadyReleasedError();
179
+ this.driver.connection.logger.logQuery(query, parameters, this);
180
+ try {
181
+ const queryStartTime = +new Date();
182
+ const [operation] = await this.driver.instanceDatabase.updateSchema(query);
183
+ await operation.promise();
184
+ // log slow queries if maxQueryExecution time is set
185
+ const maxQueryExecutionTime = this.driver.options.maxQueryExecutionTime;
186
+ const queryEndTime = +new Date();
187
+ const queryExecutionTime = queryEndTime - queryStartTime;
188
+ if (maxQueryExecutionTime &&
189
+ queryExecutionTime > maxQueryExecutionTime)
190
+ this.driver.connection.logger.logQuerySlow(queryExecutionTime, query, parameters, this);
191
+ }
192
+ catch (err) {
193
+ this.driver.connection.logger.logQueryError(err, query, parameters, this);
194
+ throw new QueryFailedError(query, parameters, err);
195
+ }
196
+ }
197
+ /**
198
+ * Returns raw data stream.
199
+ */
200
+ async stream(query, parameters, onEnd, onError) {
201
+ if (this.isReleased)
202
+ throw new QueryRunnerAlreadyReleasedError();
203
+ try {
204
+ this.driver.connection.logger.logQuery(query, parameters, this);
205
+ const request = {
206
+ sql: query,
207
+ params: parameters
208
+ ? parameters.reduce((params, value, index) => {
209
+ params["param" + index] = value;
210
+ return params;
211
+ }, {})
212
+ : undefined,
213
+ json: true,
214
+ };
215
+ const stream = this.driver.instanceDatabase.runStream(request);
216
+ if (onEnd) {
217
+ stream.on("end", onEnd);
218
+ }
219
+ if (onError) {
220
+ stream.on("error", onError);
221
+ }
222
+ return stream;
223
+ }
224
+ catch (err) {
225
+ this.driver.connection.logger.logQueryError(err, query, parameters, this);
226
+ throw new QueryFailedError(query, parameters, err);
227
+ }
228
+ }
229
+ /**
230
+ * Returns all available database names including system databases.
231
+ */
232
+ async getDatabases() {
233
+ return Promise.resolve([]);
234
+ }
235
+ /**
236
+ * Returns all available schema names including system schemas.
237
+ * If database parameter specified, returns schemas of that database.
238
+ */
239
+ async getSchemas(database) {
240
+ return Promise.resolve([]);
241
+ }
242
+ /**
243
+ * Checks if database with the given name exist.
244
+ */
245
+ async hasDatabase(database) {
246
+ throw new TypeORMError(`Check database queries are not supported by Spanner driver.`);
247
+ }
248
+ /**
249
+ * Loads currently using database
250
+ */
251
+ async getCurrentDatabase() {
252
+ throw new TypeORMError(`Check database queries are not supported by Spanner driver.`);
253
+ }
254
+ /**
255
+ * Checks if schema with the given name exist.
256
+ */
257
+ async hasSchema(schema) {
258
+ const result = await this.query(`SELECT * FROM "information_schema"."schemata" WHERE "schema_name" = '${schema}'`);
259
+ return result.length ? true : false;
260
+ }
261
+ /**
262
+ * Loads currently using database schema
263
+ */
264
+ async getCurrentSchema() {
265
+ throw new TypeORMError(`Check schema queries are not supported by Spanner driver.`);
266
+ }
267
+ /**
268
+ * Checks if table with the given name exist in the database.
269
+ */
270
+ async hasTable(tableOrName) {
271
+ const tableName = tableOrName instanceof Table ? tableOrName.name : tableOrName;
272
+ const sql = `SELECT * FROM \`INFORMATION_SCHEMA\`.\`TABLES\` ` +
273
+ `WHERE \`TABLE_CATALOG\` = '' AND \`TABLE_SCHEMA\` = '' AND \`TABLE_TYPE\` = 'BASE TABLE' ` +
274
+ `AND \`TABLE_NAME\` = '${tableName}'`;
275
+ const result = await this.query(sql);
276
+ return result.length ? true : false;
277
+ }
278
+ /**
279
+ * Checks if column with the given name exist in the given table.
280
+ */
281
+ async hasColumn(tableOrName, columnName) {
282
+ const tableName = tableOrName instanceof Table ? tableOrName.name : tableOrName;
283
+ const sql = `SELECT * FROM \`INFORMATION_SCHEMA\`.\`COLUMNS\` ` +
284
+ `WHERE \`TABLE_CATALOG\` = '' AND \`TABLE_SCHEMA\` = '' ` +
285
+ `AND \`TABLE_NAME\` = '${tableName}' AND \`COLUMN_NAME\` = '${columnName}'`;
286
+ const result = await this.query(sql);
287
+ return result.length ? true : false;
288
+ }
289
+ /**
290
+ * Creates a new database.
291
+ * Note: Spanner does not support database creation inside a transaction block.
292
+ */
293
+ async createDatabase(database, ifNotExist) {
294
+ if (ifNotExist) {
295
+ const databaseAlreadyExists = await this.hasDatabase(database);
296
+ if (databaseAlreadyExists)
297
+ return Promise.resolve();
298
+ }
299
+ const up = `CREATE DATABASE "${database}"`;
300
+ const down = `DROP DATABASE "${database}"`;
301
+ await this.executeQueries(new Query(up), new Query(down));
302
+ }
303
+ /**
304
+ * Drops database.
305
+ * Note: Spanner does not support database dropping inside a transaction block.
306
+ */
307
+ async dropDatabase(database, ifExist) {
308
+ const up = ifExist
309
+ ? `DROP DATABASE IF EXISTS "${database}"`
310
+ : `DROP DATABASE "${database}"`;
311
+ const down = `CREATE DATABASE "${database}"`;
312
+ await this.executeQueries(new Query(up), new Query(down));
313
+ }
314
+ /**
315
+ * Creates a new table schema.
316
+ */
317
+ async createSchema(schemaPath, ifNotExist) {
318
+ return Promise.resolve();
319
+ }
320
+ /**
321
+ * Drops table schema.
322
+ */
323
+ async dropSchema(schemaPath, ifExist, isCascade) {
324
+ return Promise.resolve();
325
+ }
326
+ /**
327
+ * Creates a new table.
328
+ */
329
+ async createTable(table, ifNotExist = false, createForeignKeys = true, createIndices = true) {
330
+ if (ifNotExist) {
331
+ const isTableExist = await this.hasTable(table);
332
+ if (isTableExist)
333
+ return Promise.resolve();
334
+ }
335
+ const upQueries = [];
336
+ const downQueries = [];
337
+ upQueries.push(this.createTableSql(table, createForeignKeys));
338
+ downQueries.push(this.dropTableSql(table));
339
+ // if createForeignKeys is true, we must drop created foreign keys in down query.
340
+ // createTable does not need separate method to create foreign keys, because it create fk's in the same query with table creation.
341
+ if (createForeignKeys)
342
+ table.foreignKeys.forEach((foreignKey) => downQueries.push(this.dropForeignKeySql(table, foreignKey)));
343
+ if (createIndices) {
344
+ table.indices.forEach((index) => {
345
+ // new index may be passed without name. In this case we generate index name manually.
346
+ if (!index.name)
347
+ index.name = this.connection.namingStrategy.indexName(table, index.columnNames, index.where);
348
+ upQueries.push(this.createIndexSql(table, index));
349
+ downQueries.push(this.dropIndexSql(table, index));
350
+ });
351
+ }
352
+ await this.executeQueries(upQueries, downQueries);
353
+ }
354
+ /**
355
+ * Drops the table.
356
+ */
357
+ async dropTable(target, ifExist, dropForeignKeys = true, dropIndices = true) {
358
+ // It needs because if table does not exist and dropForeignKeys or dropIndices is true, we don't need
359
+ // to perform drop queries for foreign keys and indices.
360
+ if (ifExist) {
361
+ const isTableExist = await this.hasTable(target);
362
+ if (!isTableExist)
363
+ return Promise.resolve();
364
+ }
365
+ // if dropTable called with dropForeignKeys = true, we must create foreign keys in down query.
366
+ const createForeignKeys = dropForeignKeys;
367
+ const tablePath = this.getTablePath(target);
368
+ const table = await this.getCachedTable(tablePath);
369
+ const upQueries = [];
370
+ const downQueries = [];
371
+ if (dropIndices) {
372
+ table.indices.forEach((index) => {
373
+ upQueries.push(this.dropIndexSql(table, index));
374
+ downQueries.push(this.createIndexSql(table, index));
375
+ });
376
+ }
377
+ if (dropForeignKeys)
378
+ table.foreignKeys.forEach((foreignKey) => upQueries.push(this.dropForeignKeySql(table, foreignKey)));
379
+ upQueries.push(this.dropTableSql(table));
380
+ downQueries.push(this.createTableSql(table, createForeignKeys));
381
+ await this.executeQueries(upQueries, downQueries);
382
+ }
383
+ /**
384
+ * Creates a new view.
385
+ */
386
+ async createView(view) {
387
+ const upQueries = [];
388
+ const downQueries = [];
389
+ upQueries.push(this.createViewSql(view));
390
+ upQueries.push(await this.insertViewDefinitionSql(view));
391
+ downQueries.push(this.dropViewSql(view));
392
+ downQueries.push(await this.deleteViewDefinitionSql(view));
393
+ await this.executeQueries(upQueries, downQueries);
394
+ }
395
+ /**
396
+ * Drops the view.
397
+ */
398
+ async dropView(target) {
399
+ const viewName = target instanceof View ? target.name : target;
400
+ const view = await this.getCachedView(viewName);
401
+ const upQueries = [];
402
+ const downQueries = [];
403
+ upQueries.push(await this.deleteViewDefinitionSql(view));
404
+ upQueries.push(this.dropViewSql(view));
405
+ downQueries.push(await this.insertViewDefinitionSql(view));
406
+ downQueries.push(this.createViewSql(view));
407
+ await this.executeQueries(upQueries, downQueries);
408
+ }
409
+ /**
410
+ * Renames the given table.
411
+ */
412
+ async renameTable(oldTableOrName, newTableName) {
413
+ throw new TypeORMError(`Rename table queries are not supported by Spanner driver.`);
414
+ }
415
+ /**
416
+ * Creates a new column from the column in the table.
417
+ */
418
+ async addColumn(tableOrName, column) {
419
+ const table = tableOrName instanceof Table
420
+ ? tableOrName
421
+ : await this.getCachedTable(tableOrName);
422
+ const clonedTable = table.clone();
423
+ const upQueries = [];
424
+ const downQueries = [];
425
+ upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ADD ${this.buildCreateColumnSql(column)}`));
426
+ downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} DROP COLUMN ${this.driver.escape(column.name)}`));
427
+ // create column index
428
+ const columnIndex = clonedTable.indices.find((index) => index.columnNames.length === 1 &&
429
+ index.columnNames[0] === column.name);
430
+ if (columnIndex) {
431
+ upQueries.push(this.createIndexSql(table, columnIndex));
432
+ downQueries.push(this.dropIndexSql(table, columnIndex));
433
+ }
434
+ else if (column.isUnique) {
435
+ const uniqueIndex = new TableIndex({
436
+ name: this.connection.namingStrategy.indexName(table, [
437
+ column.name,
438
+ ]),
439
+ columnNames: [column.name],
440
+ isUnique: true,
441
+ });
442
+ clonedTable.indices.push(uniqueIndex);
443
+ clonedTable.uniques.push(new TableUnique({
444
+ name: uniqueIndex.name,
445
+ columnNames: uniqueIndex.columnNames,
446
+ }));
447
+ upQueries.push(this.createIndexSql(table, uniqueIndex));
448
+ downQueries.push(this.dropIndexSql(table, uniqueIndex));
449
+ }
450
+ await this.executeQueries(upQueries, downQueries);
451
+ clonedTable.addColumn(column);
452
+ this.replaceCachedTable(table, clonedTable);
453
+ }
454
+ /**
455
+ * Creates a new columns from the column in the table.
456
+ */
457
+ async addColumns(tableOrName, columns) {
458
+ for (const column of columns) {
459
+ await this.addColumn(tableOrName, column);
460
+ }
461
+ }
462
+ /**
463
+ * Renames column in the given table.
464
+ */
465
+ async renameColumn(tableOrName, oldTableColumnOrName, newTableColumnOrName) {
466
+ const table = tableOrName instanceof Table
467
+ ? tableOrName
468
+ : await this.getCachedTable(tableOrName);
469
+ const oldColumn = oldTableColumnOrName instanceof TableColumn
470
+ ? oldTableColumnOrName
471
+ : table.columns.find((c) => c.name === oldTableColumnOrName);
472
+ if (!oldColumn)
473
+ throw new TypeORMError(`Column "${oldTableColumnOrName}" was not found in the "${table.name}" table.`);
474
+ let newColumn;
475
+ if (newTableColumnOrName instanceof TableColumn) {
476
+ newColumn = newTableColumnOrName;
477
+ }
478
+ else {
479
+ newColumn = oldColumn.clone();
480
+ newColumn.name = newTableColumnOrName;
481
+ }
482
+ return this.changeColumn(table, oldColumn, newColumn);
483
+ }
484
+ /**
485
+ * Changes a column in the table.
486
+ */
487
+ async changeColumn(tableOrName, oldTableColumnOrName, newColumn) {
488
+ const table = tableOrName instanceof Table
489
+ ? tableOrName
490
+ : await this.getCachedTable(tableOrName);
491
+ let clonedTable = table.clone();
492
+ const upQueries = [];
493
+ const downQueries = [];
494
+ const oldColumn = oldTableColumnOrName instanceof TableColumn
495
+ ? oldTableColumnOrName
496
+ : table.columns.find((column) => column.name === oldTableColumnOrName);
497
+ if (!oldColumn)
498
+ throw new TypeORMError(`Column "${oldTableColumnOrName}" was not found in the "${table.name}" table.`);
499
+ if (oldColumn.name !== newColumn.name ||
500
+ oldColumn.type !== newColumn.type ||
501
+ oldColumn.length !== newColumn.length ||
502
+ newColumn.isArray !== oldColumn.isArray ||
503
+ oldColumn.generatedType !== newColumn.generatedType) {
504
+ // To avoid data conversion, we just recreate column
505
+ await this.dropColumn(table, oldColumn);
506
+ await this.addColumn(table, newColumn);
507
+ // update cloned table
508
+ clonedTable = table.clone();
509
+ }
510
+ else {
511
+ if (newColumn.precision !== oldColumn.precision ||
512
+ newColumn.scale !== oldColumn.scale) {
513
+ upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" TYPE ${this.driver.createFullType(newColumn)}`));
514
+ downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" TYPE ${this.driver.createFullType(oldColumn)}`));
515
+ }
516
+ if (oldColumn.isNullable !== newColumn.isNullable) {
517
+ if (newColumn.isNullable) {
518
+ upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${oldColumn.name}" DROP NOT NULL`));
519
+ downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${oldColumn.name}" SET NOT NULL`));
520
+ }
521
+ else {
522
+ upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${oldColumn.name}" SET NOT NULL`));
523
+ downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${oldColumn.name}" DROP NOT NULL`));
524
+ }
525
+ }
526
+ if (newColumn.isUnique !== oldColumn.isUnique) {
527
+ if (newColumn.isUnique === true) {
528
+ const uniqueIndex = new TableIndex({
529
+ name: this.connection.namingStrategy.indexName(table, [
530
+ newColumn.name,
531
+ ]),
532
+ columnNames: [newColumn.name],
533
+ isUnique: true,
534
+ });
535
+ clonedTable.indices.push(uniqueIndex);
536
+ clonedTable.uniques.push(new TableUnique({
537
+ name: uniqueIndex.name,
538
+ columnNames: uniqueIndex.columnNames,
539
+ }));
540
+ upQueries.push(this.createIndexSql(table, uniqueIndex));
541
+ downQueries.push(this.dropIndexSql(table, uniqueIndex));
542
+ }
543
+ else {
544
+ const uniqueIndex = clonedTable.indices.find((index) => {
545
+ return (index.columnNames.length === 1 &&
546
+ index.isUnique === true &&
547
+ !!index.columnNames.find((columnName) => columnName === newColumn.name));
548
+ });
549
+ clonedTable.indices.splice(clonedTable.indices.indexOf(uniqueIndex), 1);
550
+ const tableUnique = clonedTable.uniques.find((unique) => unique.name === uniqueIndex.name);
551
+ clonedTable.uniques.splice(clonedTable.uniques.indexOf(tableUnique), 1);
552
+ upQueries.push(this.dropIndexSql(table, uniqueIndex));
553
+ downQueries.push(this.createIndexSql(table, uniqueIndex));
554
+ }
555
+ }
556
+ if (newColumn.generatedType !== oldColumn.generatedType) {
557
+ }
558
+ }
559
+ await this.executeQueries(upQueries, downQueries);
560
+ this.replaceCachedTable(table, clonedTable);
561
+ }
562
+ /**
563
+ * Changes a column in the table.
564
+ */
565
+ async changeColumns(tableOrName, changedColumns) {
566
+ for (const { oldColumn, newColumn } of changedColumns) {
567
+ await this.changeColumn(tableOrName, oldColumn, newColumn);
568
+ }
569
+ }
570
+ /**
571
+ * Drops column in the table.
572
+ */
573
+ async dropColumn(tableOrName, columnOrName) {
574
+ const table = tableOrName instanceof Table
575
+ ? tableOrName
576
+ : await this.getCachedTable(tableOrName);
577
+ const column = columnOrName instanceof TableColumn
578
+ ? columnOrName
579
+ : table.findColumnByName(columnOrName);
580
+ if (!column)
581
+ throw new TypeORMError(`Column "${columnOrName}" was not found in table "${table.name}"`);
582
+ const clonedTable = table.clone();
583
+ const upQueries = [];
584
+ const downQueries = [];
585
+ // drop column index
586
+ const columnIndex = clonedTable.indices.find((index) => index.columnNames.length === 1 &&
587
+ index.columnNames[0] === column.name);
588
+ if (columnIndex) {
589
+ clonedTable.indices.splice(clonedTable.indices.indexOf(columnIndex), 1);
590
+ upQueries.push(this.dropIndexSql(table, columnIndex));
591
+ downQueries.push(this.createIndexSql(table, columnIndex));
592
+ }
593
+ // drop column check
594
+ const columnCheck = clonedTable.checks.find((check) => !!check.columnNames &&
595
+ check.columnNames.length === 1 &&
596
+ check.columnNames[0] === column.name);
597
+ if (columnCheck) {
598
+ clonedTable.checks.splice(clonedTable.checks.indexOf(columnCheck), 1);
599
+ upQueries.push(this.dropCheckConstraintSql(table, columnCheck));
600
+ downQueries.push(this.createCheckConstraintSql(table, columnCheck));
601
+ }
602
+ upQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} DROP COLUMN ${this.driver.escape(column.name)}`));
603
+ downQueries.push(new Query(`ALTER TABLE ${this.escapePath(table)} ADD ${this.buildCreateColumnSql(column)}`));
604
+ await this.executeQueries(upQueries, downQueries);
605
+ clonedTable.removeColumn(column);
606
+ this.replaceCachedTable(table, clonedTable);
607
+ }
608
+ /**
609
+ * Drops the columns in the table.
610
+ */
611
+ async dropColumns(tableOrName, columns) {
612
+ for (const column of columns) {
613
+ await this.dropColumn(tableOrName, column);
614
+ }
615
+ }
616
+ /**
617
+ * Creates a new primary key.
618
+ *
619
+ * Not supported in Spanner.
620
+ * @see https://cloud.google.com/spanner/docs/schema-and-data-model#notes_about_key_columns
621
+ */
622
+ async createPrimaryKey(tableOrName, columnNames) {
623
+ throw new Error("The keys of a table can't change; you can't add a key column to an existing table or remove a key column from an existing table.");
624
+ }
625
+ /**
626
+ * Updates composite primary keys.
627
+ */
628
+ async updatePrimaryKeys(tableOrName, columns) {
629
+ throw new Error("The keys of a table can't change; you can't add a key column to an existing table or remove a key column from an existing table.");
630
+ }
631
+ /**
632
+ * Creates a new primary key.
633
+ *
634
+ * Not supported in Spanner.
635
+ * @see https://cloud.google.com/spanner/docs/schema-and-data-model#notes_about_key_columns
636
+ */
637
+ async dropPrimaryKey(tableOrName) {
638
+ throw new Error("The keys of a table can't change; you can't add a key column to an existing table or remove a key column from an existing table.");
639
+ }
640
+ /**
641
+ * Creates new unique constraint.
642
+ */
643
+ async createUniqueConstraint(tableOrName, uniqueConstraint) {
644
+ throw new TypeORMError(`Spanner does not support unique constraints. Use unique index instead.`);
645
+ }
646
+ /**
647
+ * Creates new unique constraints.
648
+ */
649
+ async createUniqueConstraints(tableOrName, uniqueConstraints) {
650
+ throw new TypeORMError(`Spanner does not support unique constraints. Use unique index instead.`);
651
+ }
652
+ /**
653
+ * Drops unique constraint.
654
+ */
655
+ async dropUniqueConstraint(tableOrName, uniqueOrName) {
656
+ throw new TypeORMError(`Spanner does not support unique constraints. Use unique index instead.`);
657
+ }
658
+ /**
659
+ * Drops unique constraints.
660
+ */
661
+ async dropUniqueConstraints(tableOrName, uniqueConstraints) {
662
+ throw new TypeORMError(`Spanner does not support unique constraints. Use unique index instead.`);
663
+ }
664
+ /**
665
+ * Creates new check constraint.
666
+ */
667
+ async createCheckConstraint(tableOrName, checkConstraint) {
668
+ const table = tableOrName instanceof Table
669
+ ? tableOrName
670
+ : await this.getCachedTable(tableOrName);
671
+ // new check constraint may be passed without name. In this case we generate unique name manually.
672
+ if (!checkConstraint.name)
673
+ checkConstraint.name =
674
+ this.connection.namingStrategy.checkConstraintName(table, checkConstraint.expression);
675
+ const up = this.createCheckConstraintSql(table, checkConstraint);
676
+ const down = this.dropCheckConstraintSql(table, checkConstraint);
677
+ await this.executeQueries(up, down);
678
+ table.addCheckConstraint(checkConstraint);
679
+ }
680
+ /**
681
+ * Creates new check constraints.
682
+ */
683
+ async createCheckConstraints(tableOrName, checkConstraints) {
684
+ const promises = checkConstraints.map((checkConstraint) => this.createCheckConstraint(tableOrName, checkConstraint));
685
+ await Promise.all(promises);
686
+ }
687
+ /**
688
+ * Drops check constraint.
689
+ */
690
+ async dropCheckConstraint(tableOrName, checkOrName) {
691
+ const table = tableOrName instanceof Table
692
+ ? tableOrName
693
+ : await this.getCachedTable(tableOrName);
694
+ const checkConstraint = checkOrName instanceof TableCheck
695
+ ? checkOrName
696
+ : table.checks.find((c) => c.name === checkOrName);
697
+ if (!checkConstraint)
698
+ throw new TypeORMError(`Supplied check constraint was not found in table ${table.name}`);
699
+ const up = this.dropCheckConstraintSql(table, checkConstraint);
700
+ const down = this.createCheckConstraintSql(table, checkConstraint);
701
+ await this.executeQueries(up, down);
702
+ table.removeCheckConstraint(checkConstraint);
703
+ }
704
+ /**
705
+ * Drops check constraints.
706
+ */
707
+ async dropCheckConstraints(tableOrName, checkConstraints) {
708
+ const promises = checkConstraints.map((checkConstraint) => this.dropCheckConstraint(tableOrName, checkConstraint));
709
+ await Promise.all(promises);
710
+ }
711
+ /**
712
+ * Creates new exclusion constraint.
713
+ */
714
+ async createExclusionConstraint(tableOrName, exclusionConstraint) {
715
+ throw new TypeORMError(`Spanner does not support exclusion constraints.`);
716
+ }
717
+ /**
718
+ * Creates new exclusion constraints.
719
+ */
720
+ async createExclusionConstraints(tableOrName, exclusionConstraints) {
721
+ throw new TypeORMError(`Spanner does not support exclusion constraints.`);
722
+ }
723
+ /**
724
+ * Drops exclusion constraint.
725
+ */
726
+ async dropExclusionConstraint(tableOrName, exclusionOrName) {
727
+ throw new TypeORMError(`Spanner does not support exclusion constraints.`);
728
+ }
729
+ /**
730
+ * Drops exclusion constraints.
731
+ */
732
+ async dropExclusionConstraints(tableOrName, exclusionConstraints) {
733
+ throw new TypeORMError(`Spanner does not support exclusion constraints.`);
734
+ }
735
+ /**
736
+ * Creates a new foreign key.
737
+ */
738
+ async createForeignKey(tableOrName, foreignKey) {
739
+ const table = tableOrName instanceof Table
740
+ ? tableOrName
741
+ : await this.getCachedTable(tableOrName);
742
+ // new FK may be passed without name. In this case we generate FK name manually.
743
+ if (!foreignKey.name)
744
+ foreignKey.name = this.connection.namingStrategy.foreignKeyName(table, foreignKey.columnNames, this.getTablePath(foreignKey), foreignKey.referencedColumnNames);
745
+ const up = this.createForeignKeySql(table, foreignKey);
746
+ const down = this.dropForeignKeySql(table, foreignKey);
747
+ await this.executeQueries(up, down);
748
+ table.addForeignKey(foreignKey);
749
+ }
750
+ /**
751
+ * Creates a new foreign keys.
752
+ */
753
+ async createForeignKeys(tableOrName, foreignKeys) {
754
+ for (const foreignKey of foreignKeys) {
755
+ await this.createForeignKey(tableOrName, foreignKey);
756
+ }
757
+ }
758
+ /**
759
+ * Drops a foreign key from the table.
760
+ */
761
+ async dropForeignKey(tableOrName, foreignKeyOrName) {
762
+ const table = tableOrName instanceof Table
763
+ ? tableOrName
764
+ : await this.getCachedTable(tableOrName);
765
+ const foreignKey = foreignKeyOrName instanceof TableForeignKey
766
+ ? foreignKeyOrName
767
+ : table.foreignKeys.find((fk) => fk.name === foreignKeyOrName);
768
+ if (!foreignKey)
769
+ throw new TypeORMError(`Supplied foreign key was not found in table ${table.name}`);
770
+ const up = this.dropForeignKeySql(table, foreignKey);
771
+ const down = this.createForeignKeySql(table, foreignKey);
772
+ await this.executeQueries(up, down);
773
+ table.removeForeignKey(foreignKey);
774
+ }
775
+ /**
776
+ * Drops a foreign keys from the table.
777
+ */
778
+ async dropForeignKeys(tableOrName, foreignKeys) {
779
+ for (const foreignKey of foreignKeys) {
780
+ await this.dropForeignKey(tableOrName, foreignKey);
781
+ }
782
+ }
783
+ /**
784
+ * Creates a new index.
785
+ */
786
+ async createIndex(tableOrName, index) {
787
+ const table = tableOrName instanceof Table
788
+ ? tableOrName
789
+ : await this.getCachedTable(tableOrName);
790
+ // new index may be passed without name. In this case we generate index name manually.
791
+ if (!index.name)
792
+ index.name = this.connection.namingStrategy.indexName(table, index.columnNames, index.where);
793
+ const up = this.createIndexSql(table, index);
794
+ const down = this.dropIndexSql(table, index);
795
+ await this.executeQueries(up, down);
796
+ table.addIndex(index);
797
+ }
798
+ /**
799
+ * Creates a new indices
800
+ */
801
+ async createIndices(tableOrName, indices) {
802
+ for (const index of indices) {
803
+ await this.createIndex(tableOrName, index);
804
+ }
805
+ }
806
+ /**
807
+ * Drops an index from the table.
808
+ */
809
+ async dropIndex(tableOrName, indexOrName) {
810
+ const table = tableOrName instanceof Table
811
+ ? tableOrName
812
+ : await this.getCachedTable(tableOrName);
813
+ const index = indexOrName instanceof TableIndex
814
+ ? indexOrName
815
+ : table.indices.find((i) => i.name === indexOrName);
816
+ if (!index)
817
+ throw new TypeORMError(`Supplied index ${indexOrName} was not found in table ${table.name}`);
818
+ const up = this.dropIndexSql(table, index);
819
+ const down = this.createIndexSql(table, index);
820
+ await this.executeQueries(up, down);
821
+ table.removeIndex(index);
822
+ }
823
+ /**
824
+ * Drops an indices from the table.
825
+ */
826
+ async dropIndices(tableOrName, indices) {
827
+ for (const index of indices) {
828
+ await this.dropIndex(tableOrName, index);
829
+ }
830
+ }
831
+ /**
832
+ * Clears all table contents.
833
+ * Spanner does not support TRUNCATE TABLE statement, so we use DELETE FROM.
834
+ */
835
+ async clearTable(tableName) {
836
+ await this.query(`DELETE FROM ${this.escapePath(tableName)} WHERE true`);
837
+ }
838
+ /**
839
+ * Removes all tables from the currently connected database.
840
+ */
841
+ async clearDatabase() {
842
+ // drop index queries
843
+ const selectIndexDropsQuery = `SELECT concat('DROP INDEX \`', INDEX_NAME, '\`') AS \`query\` ` +
844
+ `FROM \`INFORMATION_SCHEMA\`.\`INDEXES\` ` +
845
+ `WHERE \`TABLE_CATALOG\` = '' AND \`TABLE_SCHEMA\` = '' AND \`INDEX_TYPE\` = 'INDEX' AND \`SPANNER_IS_MANAGED\` = false`;
846
+ const dropIndexQueries = await this.query(selectIndexDropsQuery);
847
+ // drop foreign key queries
848
+ const selectFKDropsQuery = `SELECT concat('ALTER TABLE \`', TABLE_NAME, '\`', ' DROP CONSTRAINT \`', CONSTRAINT_NAME, '\`') AS \`query\` ` +
849
+ `FROM \`INFORMATION_SCHEMA\`.\`TABLE_CONSTRAINTS\` ` +
850
+ `WHERE \`TABLE_CATALOG\` = '' AND \`TABLE_SCHEMA\` = '' AND \`CONSTRAINT_TYPE\` = 'FOREIGN KEY'`;
851
+ const dropFKQueries = await this.query(selectFKDropsQuery);
852
+ // drop view queries
853
+ const selectViewDropsQuery = `SELECT concat('DROP VIEW \`', TABLE_NAME, '\`') AS \`query\` FROM \`INFORMATION_SCHEMA\`.\`VIEWS\``;
854
+ const dropViewQueries = await this.query(selectViewDropsQuery);
855
+ // drop table queries
856
+ const dropTablesQuery = `SELECT concat('DROP TABLE \`', TABLE_NAME, '\`') AS \`query\` ` +
857
+ `FROM \`INFORMATION_SCHEMA\`.\`TABLES\` ` +
858
+ `WHERE \`TABLE_CATALOG\` = '' AND \`TABLE_SCHEMA\` = '' AND \`TABLE_TYPE\` = 'BASE TABLE'`;
859
+ const dropTableQueries = await this.query(dropTablesQuery);
860
+ if (!dropIndexQueries.length &&
861
+ !dropFKQueries.length &&
862
+ !dropViewQueries.length &&
863
+ !dropTableQueries.length)
864
+ return;
865
+ const isAnotherTransactionActive = this.isTransactionActive;
866
+ if (!isAnotherTransactionActive)
867
+ await this.startTransaction();
868
+ try {
869
+ for (let query of dropIndexQueries) {
870
+ await this.updateDDL(query["query"]);
871
+ }
872
+ for (let query of dropFKQueries) {
873
+ await this.updateDDL(query["query"]);
874
+ }
875
+ for (let query of dropViewQueries) {
876
+ await this.updateDDL(query["query"]);
877
+ }
878
+ for (let query of dropTableQueries) {
879
+ await this.updateDDL(query["query"]);
880
+ }
881
+ await this.commitTransaction();
882
+ }
883
+ catch (error) {
884
+ try {
885
+ // we throw original error even if rollback thrown an error
886
+ if (!isAnotherTransactionActive)
887
+ await this.rollbackTransaction();
888
+ }
889
+ catch (rollbackError) { }
890
+ throw error;
891
+ }
892
+ }
893
+ // -------------------------------------------------------------------------
894
+ // Override Methods
895
+ // -------------------------------------------------------------------------
896
+ /**
897
+ * Executes up sql queries.
898
+ */
899
+ async executeMemoryUpSql() {
900
+ for (const { query, parameters } of this.sqlInMemory.upQueries) {
901
+ if (this.isDMLQuery(query)) {
902
+ await this.query(query, parameters);
903
+ }
904
+ else {
905
+ await this.updateDDL(query, parameters);
906
+ }
907
+ }
908
+ }
909
+ /**
910
+ * Executes down sql queries.
911
+ */
912
+ async executeMemoryDownSql() {
913
+ for (const { query, parameters, } of this.sqlInMemory.downQueries.reverse()) {
914
+ if (this.isDMLQuery(query)) {
915
+ await this.query(query, parameters);
916
+ }
917
+ else {
918
+ await this.updateDDL(query, parameters);
919
+ }
920
+ }
921
+ }
922
+ // -------------------------------------------------------------------------
923
+ // Protected Methods
924
+ // -------------------------------------------------------------------------
925
+ async loadViews(viewNames) {
926
+ const hasTable = await this.hasTable(this.getTypeormMetadataTableName());
927
+ if (!hasTable) {
928
+ return [];
929
+ }
930
+ if (!viewNames) {
931
+ viewNames = [];
932
+ }
933
+ const escapedViewNames = viewNames
934
+ .map((viewName) => `'${viewName}'`)
935
+ .join(", ");
936
+ const query = `SELECT \`T\`.*, \`V\`.\`VIEW_DEFINITION\` FROM ${this.escapePath(this.getTypeormMetadataTableName())} \`T\` ` +
937
+ `INNER JOIN \`INFORMATION_SCHEMA\`.\`VIEWS\` \`V\` ON \`V\`.\`TABLE_NAME\` = \`T\`.\`NAME\` ` +
938
+ `WHERE \`T\`.\`TYPE\` = '${MetadataTableType.VIEW}' ${viewNames.length
939
+ ? ` AND \`T\`.\`NAME\` IN (${escapedViewNames})`
940
+ : ""}`;
941
+ const dbViews = await this.query(query);
942
+ return dbViews.map((dbView) => {
943
+ const view = new View();
944
+ view.database = dbView["NAME"];
945
+ view.name = this.driver.buildTableName(dbView["NAME"]);
946
+ view.expression = dbView["NAME"];
947
+ return view;
948
+ });
949
+ }
950
+ /**
951
+ * Loads all tables (with given names) from the database and creates a Table from them.
952
+ */
953
+ async loadTables(tableNames) {
954
+ if (tableNames && tableNames.length === 0) {
955
+ return [];
956
+ }
957
+ const dbTables = [];
958
+ if (!tableNames || !tableNames.length) {
959
+ // Since we don't have any of this data we have to do a scan
960
+ const tablesSql = `SELECT \`TABLE_NAME\` ` +
961
+ `FROM \`INFORMATION_SCHEMA\`.\`TABLES\` ` +
962
+ `WHERE \`TABLE_CATALOG\` = '' AND \`TABLE_SCHEMA\` = '' AND \`TABLE_TYPE\` = 'BASE TABLE'`;
963
+ dbTables.push(...(await this.query(tablesSql)));
964
+ }
965
+ else {
966
+ const tablesSql = `SELECT \`TABLE_NAME\` ` +
967
+ `FROM \`INFORMATION_SCHEMA\`.\`TABLES\` ` +
968
+ `WHERE \`TABLE_CATALOG\` = '' AND \`TABLE_SCHEMA\` = '' AND \`TABLE_TYPE\` = 'BASE TABLE' ` +
969
+ `AND \`TABLE_NAME\` IN (${tableNames
970
+ .map((tableName) => `'${tableName}'`)
971
+ .join(", ")})`;
972
+ dbTables.push(...(await this.query(tablesSql)));
973
+ }
974
+ // if tables were not found in the db, no need to proceed
975
+ if (!dbTables.length)
976
+ return [];
977
+ const loadedTableNames = dbTables
978
+ .map((dbTable) => `'${dbTable.TABLE_NAME}'`)
979
+ .join(", ");
980
+ const columnsSql = `SELECT * FROM \`INFORMATION_SCHEMA\`.\`COLUMNS\` WHERE \`TABLE_CATALOG\` = '' AND \`TABLE_SCHEMA\` = '' AND \`TABLE_NAME\` IN (${loadedTableNames})`;
981
+ const primaryKeySql = `SELECT \`KCU\`.\`TABLE_NAME\`, \`KCU\`.\`COLUMN_NAME\` ` +
982
+ `FROM \`INFORMATION_SCHEMA\`.\`TABLE_CONSTRAINTS\` \`TC\` ` +
983
+ `INNER JOIN \`INFORMATION_SCHEMA\`.\`KEY_COLUMN_USAGE\` \`KCU\` ON \`KCU\`.\`CONSTRAINT_NAME\` = \`TC\`.\`CONSTRAINT_NAME\` ` +
984
+ `WHERE \`TC\`.\`TABLE_CATALOG\` = '' AND \`TC\`.\`TABLE_SCHEMA\` = '' AND \`TC\`.\`CONSTRAINT_TYPE\` = 'PRIMARY KEY' ` +
985
+ `AND \`TC\`.\`TABLE_NAME\` IN (${loadedTableNames})`;
986
+ const indicesSql = `SELECT \`I\`.\`TABLE_NAME\`, \`I\`.\`INDEX_NAME\`, \`I\`.\`IS_UNIQUE\`, \`I\`.\`IS_NULL_FILTERED\`, \`IC\`.\`COLUMN_NAME\` ` +
987
+ `FROM \`INFORMATION_SCHEMA\`.\`INDEXES\` \`I\` ` +
988
+ `INNER JOIN \`INFORMATION_SCHEMA\`.\`INDEX_COLUMNS\` \`IC\` ON \`IC\`.\`INDEX_NAME\` = \`I\`.\`INDEX_NAME\` ` +
989
+ `AND \`IC\`.\`TABLE_NAME\` = \`I\`.\`TABLE_NAME\` ` +
990
+ `WHERE \`I\`.\`TABLE_CATALOG\` = '' AND \`I\`.\`TABLE_SCHEMA\` = '' AND \`I\`.\`TABLE_NAME\` IN (${loadedTableNames}) ` +
991
+ `AND \`I\`.\`INDEX_TYPE\` = 'INDEX' AND \`I\`.\`SPANNER_IS_MANAGED\` = false`;
992
+ const checksSql = `SELECT \`TC\`.\`TABLE_NAME\`, \`TC\`.\`CONSTRAINT_NAME\`, \`CC\`.\`CHECK_CLAUSE\`, \`CCU\`.\`COLUMN_NAME\`` +
993
+ `FROM \`INFORMATION_SCHEMA\`.\`TABLE_CONSTRAINTS\` \`TC\` ` +
994
+ `INNER JOIN \`INFORMATION_SCHEMA\`.\`CONSTRAINT_COLUMN_USAGE\` \`CCU\` ON \`CCU\`.\`CONSTRAINT_NAME\` = \`TC\`.\`CONSTRAINT_NAME\` ` +
995
+ `INNER JOIN \`INFORMATION_SCHEMA\`.\`CHECK_CONSTRAINTS\` \`CC\` ON \`CC\`.\`CONSTRAINT_NAME\` = \`TC\`.\`CONSTRAINT_NAME\` ` +
996
+ `WHERE \`TC\`.\`TABLE_CATALOG\` = '' AND \`TC\`.\`TABLE_SCHEMA\` = '' AND \`TC\`.\`CONSTRAINT_TYPE\` = 'CHECK' ` +
997
+ `AND \`TC\`.\`TABLE_NAME\` IN (${loadedTableNames}) AND \`TC\`.\`CONSTRAINT_NAME\` NOT LIKE 'CK_IS_NOT_NULL%'`;
998
+ const foreignKeysSql = `SELECT \`TC\`.\`TABLE_NAME\`, \`TC\`.\`CONSTRAINT_NAME\`, \`KCU\`.\`COLUMN_NAME\`, ` +
999
+ `\`CTU\`.\`TABLE_NAME\` AS \`REFERENCED_TABLE_NAME\`, \`CCU\`.\`COLUMN_NAME\` AS \`REFERENCED_COLUMN_NAME\`, ` +
1000
+ `\`RC\`.\`UPDATE_RULE\`, \`RC\`.\`DELETE_RULE\` ` +
1001
+ `FROM \`INFORMATION_SCHEMA\`.\`TABLE_CONSTRAINTS\` \`TC\` ` +
1002
+ `INNER JOIN \`INFORMATION_SCHEMA\`.\`KEY_COLUMN_USAGE\` \`KCU\` ON \`KCU\`.\`CONSTRAINT_NAME\` = \`TC\`.\`CONSTRAINT_NAME\` ` +
1003
+ `INNER JOIN \`INFORMATION_SCHEMA\`.\`CONSTRAINT_TABLE_USAGE\` \`CTU\` ON \`CTU\`.\`CONSTRAINT_NAME\` = \`TC\`.\`CONSTRAINT_NAME\` ` +
1004
+ `INNER JOIN \`INFORMATION_SCHEMA\`.\`REFERENTIAL_CONSTRAINTS\` \`RC\` ON \`RC\`.\`CONSTRAINT_NAME\` = \`TC\`.\`CONSTRAINT_NAME\` ` +
1005
+ `INNER JOIN \`INFORMATION_SCHEMA\`.\`CONSTRAINT_COLUMN_USAGE\` \`CCU\` ON \`CCU\`.\`CONSTRAINT_NAME\` = \`TC\`.\`CONSTRAINT_NAME\` ` +
1006
+ `WHERE \`TC\`.\`TABLE_CATALOG\` = '' AND \`TC\`.\`TABLE_SCHEMA\` = '' AND \`TC\`.\`CONSTRAINT_TYPE\` = 'FOREIGN KEY' ` +
1007
+ `AND \`TC\`.\`TABLE_NAME\` IN (${loadedTableNames})`;
1008
+ const [dbColumns, dbPrimaryKeys, dbIndices, dbChecks, dbForeignKeys,] = await Promise.all([
1009
+ this.query(columnsSql),
1010
+ this.query(primaryKeySql),
1011
+ this.query(indicesSql),
1012
+ this.query(checksSql),
1013
+ this.query(foreignKeysSql),
1014
+ ]);
1015
+ // create tables for loaded tables
1016
+ return Promise.all(dbTables.map(async (dbTable) => {
1017
+ const table = new Table();
1018
+ table.name = this.driver.buildTableName(dbTable["TABLE_NAME"]);
1019
+ // create columns from the loaded columns
1020
+ table.columns = dbColumns
1021
+ .filter((dbColumn) => dbColumn["TABLE_NAME"] === dbTable["TABLE_NAME"])
1022
+ .map((dbColumn) => {
1023
+ const columnUniqueIndices = dbIndices.filter((dbIndex) => {
1024
+ return (dbIndex["TABLE_NAME"] ===
1025
+ dbTable["TABLE_NAME"] &&
1026
+ dbIndex["COLUMN_NAME"] ===
1027
+ dbColumn["COLUMN_NAME"] &&
1028
+ dbIndex["IS_UNIQUE"] === true);
1029
+ });
1030
+ const tableMetadata = this.connection.entityMetadatas.find((metadata) => this.getTablePath(table) ===
1031
+ this.getTablePath(metadata));
1032
+ const hasIgnoredIndex = columnUniqueIndices.length > 0 &&
1033
+ tableMetadata &&
1034
+ tableMetadata.indices.some((index) => {
1035
+ return columnUniqueIndices.some((uniqueIndex) => {
1036
+ return (index.name ===
1037
+ uniqueIndex["INDEX_NAME"] &&
1038
+ index.synchronize === false);
1039
+ });
1040
+ });
1041
+ const isConstraintComposite = columnUniqueIndices.every((uniqueIndex) => {
1042
+ return dbIndices.some((dbIndex) => dbIndex["INDEX_NAME"] ===
1043
+ uniqueIndex["INDEX_NAME"] &&
1044
+ dbIndex["COLUMN_NAME"] !==
1045
+ dbColumn["COLUMN_NAME"]);
1046
+ });
1047
+ const tableColumn = new TableColumn();
1048
+ tableColumn.name = dbColumn["COLUMN_NAME"];
1049
+ let fullType = dbColumn["SPANNER_TYPE"].toLowerCase();
1050
+ if (fullType.indexOf("array") !== -1) {
1051
+ tableColumn.isArray = true;
1052
+ fullType = fullType.substring(fullType.indexOf("<") + 1, fullType.indexOf(">"));
1053
+ }
1054
+ if (fullType.indexOf("(") !== -1) {
1055
+ tableColumn.type = fullType.substring(0, fullType.indexOf("("));
1056
+ }
1057
+ else {
1058
+ tableColumn.type = fullType;
1059
+ }
1060
+ if (this.driver.withLengthColumnTypes.indexOf(tableColumn.type) !== -1) {
1061
+ tableColumn.length = fullType.substring(fullType.indexOf("(") + 1, fullType.indexOf(")"));
1062
+ }
1063
+ if (dbColumn["IS_GENERATED"] === "ALWAYS") {
1064
+ tableColumn.asExpression =
1065
+ dbColumn["GENERATION_EXPRESSION"];
1066
+ tableColumn.generatedType =
1067
+ dbColumn["IS_STORED"] === "YES"
1068
+ ? "STORED"
1069
+ : "VIRTUAL";
1070
+ }
1071
+ tableColumn.isUnique =
1072
+ columnUniqueIndices.length > 0 &&
1073
+ !hasIgnoredIndex &&
1074
+ !isConstraintComposite;
1075
+ tableColumn.isNullable =
1076
+ dbColumn["IS_NULLABLE"] === "YES";
1077
+ tableColumn.isPrimary = dbPrimaryKeys.some((dbPrimaryKey) => {
1078
+ return (dbPrimaryKey["TABLE_NAME"] ===
1079
+ dbColumn["TABLE_NAME"] &&
1080
+ dbPrimaryKey["COLUMN_NAME"] ===
1081
+ dbColumn["COLUMN_NAME"]);
1082
+ });
1083
+ return tableColumn;
1084
+ });
1085
+ const tableForeignKeys = dbForeignKeys.filter((dbForeignKey) => {
1086
+ return (dbForeignKey["TABLE_NAME"] === dbTable["TABLE_NAME"]);
1087
+ });
1088
+ table.foreignKeys = OrmUtils.uniq(tableForeignKeys, (dbForeignKey) => dbForeignKey["CONSTRAINT_NAME"]).map((dbForeignKey) => {
1089
+ const foreignKeys = tableForeignKeys.filter((dbFk) => dbFk["CONSTRAINT_NAME"] ===
1090
+ dbForeignKey["CONSTRAINT_NAME"]);
1091
+ return new TableForeignKey({
1092
+ name: dbForeignKey["CONSTRAINT_NAME"],
1093
+ columnNames: OrmUtils.uniq(foreignKeys.map((dbFk) => dbFk["COLUMN_NAME"])),
1094
+ referencedDatabase: dbForeignKey["REFERENCED_TABLE_SCHEMA"],
1095
+ referencedTableName: dbForeignKey["REFERENCED_TABLE_NAME"],
1096
+ referencedColumnNames: OrmUtils.uniq(foreignKeys.map((dbFk) => dbFk["REFERENCED_COLUMN_NAME"])),
1097
+ onDelete: dbForeignKey["DELETE_RULE"],
1098
+ onUpdate: dbForeignKey["UPDATE_RULE"],
1099
+ });
1100
+ });
1101
+ const tableIndices = dbIndices.filter((dbIndex) => dbIndex["TABLE_NAME"] === dbTable["TABLE_NAME"]);
1102
+ table.indices = OrmUtils.uniq(tableIndices, (dbIndex) => dbIndex["INDEX_NAME"]).map((constraint) => {
1103
+ const indices = tableIndices.filter((index) => {
1104
+ return index["INDEX_NAME"] === constraint["INDEX_NAME"];
1105
+ });
1106
+ return new TableIndex({
1107
+ table: table,
1108
+ name: constraint["INDEX_NAME"],
1109
+ columnNames: indices.map((i) => i["COLUMN_NAME"]),
1110
+ isUnique: constraint["IS_UNIQUE"],
1111
+ isNullFiltered: constraint["IS_NULL_FILTERED"],
1112
+ });
1113
+ });
1114
+ const tableChecks = dbChecks.filter((dbCheck) => dbCheck["TABLE_NAME"] === dbTable["TABLE_NAME"]);
1115
+ table.checks = OrmUtils.uniq(tableChecks, (dbIndex) => dbIndex["CONSTRAINT_NAME"]).map((constraint) => {
1116
+ const checks = tableChecks.filter((dbC) => dbC["CONSTRAINT_NAME"] ===
1117
+ constraint["CONSTRAINT_NAME"]);
1118
+ return new TableCheck({
1119
+ name: constraint["CONSTRAINT_NAME"],
1120
+ columnNames: checks.map((c) => c["COLUMN_NAME"]),
1121
+ expression: constraint["CHECK_CLAUSE"],
1122
+ });
1123
+ });
1124
+ return table;
1125
+ }));
1126
+ }
1127
+ /**
1128
+ * Builds create table sql.
1129
+ */
1130
+ createTableSql(table, createForeignKeys) {
1131
+ const columnDefinitions = table.columns
1132
+ .map((column) => this.buildCreateColumnSql(column))
1133
+ .join(", ");
1134
+ let sql = `CREATE TABLE ${this.escapePath(table)} (${columnDefinitions}`;
1135
+ // we create unique indexes instead of unique constraints, because Spanner does not have unique constraints.
1136
+ // if we mark column as Unique, it means that we create UNIQUE INDEX.
1137
+ table.columns
1138
+ .filter((column) => column.isUnique)
1139
+ .forEach((column) => {
1140
+ const isUniqueIndexExist = table.indices.some((index) => {
1141
+ return (index.columnNames.length === 1 &&
1142
+ !!index.isUnique &&
1143
+ index.columnNames.indexOf(column.name) !== -1);
1144
+ });
1145
+ const isUniqueConstraintExist = table.uniques.some((unique) => {
1146
+ return (unique.columnNames.length === 1 &&
1147
+ unique.columnNames.indexOf(column.name) !== -1);
1148
+ });
1149
+ if (!isUniqueIndexExist && !isUniqueConstraintExist)
1150
+ table.indices.push(new TableIndex({
1151
+ name: this.connection.namingStrategy.uniqueConstraintName(table, [column.name]),
1152
+ columnNames: [column.name],
1153
+ isUnique: true,
1154
+ }));
1155
+ });
1156
+ // as Spanner does not have unique constraints, we must create table indices from table uniques and mark them as unique.
1157
+ if (table.uniques.length > 0) {
1158
+ table.uniques.forEach((unique) => {
1159
+ const uniqueExist = table.indices.some((index) => index.name === unique.name);
1160
+ if (!uniqueExist) {
1161
+ table.indices.push(new TableIndex({
1162
+ name: unique.name,
1163
+ columnNames: unique.columnNames,
1164
+ isUnique: true,
1165
+ }));
1166
+ }
1167
+ });
1168
+ }
1169
+ if (table.checks.length > 0) {
1170
+ const checksSql = table.checks
1171
+ .map((check) => {
1172
+ const checkName = check.name
1173
+ ? check.name
1174
+ : this.connection.namingStrategy.checkConstraintName(table, check.expression);
1175
+ return `CONSTRAINT \`${checkName}\` CHECK (${check.expression})`;
1176
+ })
1177
+ .join(", ");
1178
+ sql += `, ${checksSql}`;
1179
+ }
1180
+ if (table.foreignKeys.length > 0 && createForeignKeys) {
1181
+ const foreignKeysSql = table.foreignKeys
1182
+ .map((fk) => {
1183
+ const columnNames = fk.columnNames
1184
+ .map((columnName) => `\`${columnName}\``)
1185
+ .join(", ");
1186
+ if (!fk.name)
1187
+ fk.name = this.connection.namingStrategy.foreignKeyName(table, fk.columnNames, this.getTablePath(fk), fk.referencedColumnNames);
1188
+ const referencedColumnNames = fk.referencedColumnNames
1189
+ .map((columnName) => `\`${columnName}\``)
1190
+ .join(", ");
1191
+ return `CONSTRAINT \`${fk.name}\` FOREIGN KEY (${columnNames}) REFERENCES ${this.escapePath(this.getTablePath(fk))} (${referencedColumnNames})`;
1192
+ })
1193
+ .join(", ");
1194
+ sql += `, ${foreignKeysSql}`;
1195
+ }
1196
+ sql += `)`;
1197
+ const primaryColumns = table.columns.filter((column) => column.isPrimary);
1198
+ if (primaryColumns.length > 0) {
1199
+ const columnNames = primaryColumns
1200
+ .map((column) => this.driver.escape(column.name))
1201
+ .join(", ");
1202
+ sql += ` PRIMARY KEY (${columnNames})`;
1203
+ }
1204
+ return new Query(sql);
1205
+ }
1206
+ /**
1207
+ * Builds drop table sql.
1208
+ */
1209
+ dropTableSql(tableOrPath) {
1210
+ return new Query(`DROP TABLE ${this.escapePath(tableOrPath)}`);
1211
+ }
1212
+ createViewSql(view) {
1213
+ const materializedClause = view.materialized ? "MATERIALIZED " : "";
1214
+ const viewName = this.escapePath(view);
1215
+ const expression = typeof view.expression === "string"
1216
+ ? view.expression
1217
+ : view.expression(this.connection).getQuery();
1218
+ return new Query(`CREATE ${materializedClause}VIEW ${viewName} SQL SECURITY INVOKER AS ${expression}`);
1219
+ }
1220
+ async insertViewDefinitionSql(view) {
1221
+ let { schema, tableName: name } = this.driver.parseTableName(view);
1222
+ const type = view.materialized
1223
+ ? MetadataTableType.MATERIALIZED_VIEW
1224
+ : MetadataTableType.VIEW;
1225
+ const expression = typeof view.expression === "string"
1226
+ ? view.expression.trim()
1227
+ : view.expression(this.connection).getQuery();
1228
+ return this.insertTypeormMetadataSql({
1229
+ type,
1230
+ schema,
1231
+ name,
1232
+ value: expression,
1233
+ });
1234
+ }
1235
+ /**
1236
+ * Builds drop view sql.
1237
+ */
1238
+ dropViewSql(view) {
1239
+ const materializedClause = view.materialized ? "MATERIALIZED " : "";
1240
+ return new Query(`DROP ${materializedClause}VIEW ${this.escapePath(view)}`);
1241
+ }
1242
+ /**
1243
+ * Builds remove view sql.
1244
+ */
1245
+ async deleteViewDefinitionSql(view) {
1246
+ let { schema, tableName: name } = this.driver.parseTableName(view);
1247
+ const type = view.materialized
1248
+ ? MetadataTableType.MATERIALIZED_VIEW
1249
+ : MetadataTableType.VIEW;
1250
+ return this.deleteTypeormMetadataSql({ type, schema, name });
1251
+ }
1252
+ /**
1253
+ * Builds create index sql.
1254
+ */
1255
+ createIndexSql(table, index) {
1256
+ const columns = index.columnNames
1257
+ .map((columnName) => this.driver.escape(columnName))
1258
+ .join(", ");
1259
+ let indexType = "";
1260
+ if (index.isUnique)
1261
+ indexType += "UNIQUE ";
1262
+ if (index.isNullFiltered)
1263
+ indexType += "NULL_FILTERED ";
1264
+ return new Query(`CREATE ${indexType}INDEX \`${index.name}\` ON ${this.escapePath(table)} (${columns})`);
1265
+ }
1266
+ /**
1267
+ * Builds drop index sql.
1268
+ */
1269
+ dropIndexSql(table, indexOrName) {
1270
+ let indexName = indexOrName instanceof TableIndex ? indexOrName.name : indexOrName;
1271
+ return new Query(`DROP INDEX \`${indexName}\``);
1272
+ }
1273
+ /**
1274
+ * Builds create check constraint sql.
1275
+ */
1276
+ createCheckConstraintSql(table, checkConstraint) {
1277
+ return new Query(`ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT \`${checkConstraint.name}\` CHECK (${checkConstraint.expression})`);
1278
+ }
1279
+ /**
1280
+ * Builds drop check constraint sql.
1281
+ */
1282
+ dropCheckConstraintSql(table, checkOrName) {
1283
+ const checkName = checkOrName instanceof TableCheck ? checkOrName.name : checkOrName;
1284
+ return new Query(`ALTER TABLE ${this.escapePath(table)} DROP CONSTRAINT \`${checkName}\``);
1285
+ }
1286
+ /**
1287
+ * Builds create foreign key sql.
1288
+ */
1289
+ createForeignKeySql(table, foreignKey) {
1290
+ const columnNames = foreignKey.columnNames
1291
+ .map((column) => this.driver.escape(column))
1292
+ .join(", ");
1293
+ const referencedColumnNames = foreignKey.referencedColumnNames
1294
+ .map((column) => this.driver.escape(column))
1295
+ .join(",");
1296
+ let sql = `ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT \`${foreignKey.name}\` FOREIGN KEY (${columnNames}) ` +
1297
+ `REFERENCES ${this.escapePath(this.getTablePath(foreignKey))} (${referencedColumnNames})`;
1298
+ return new Query(sql);
1299
+ }
1300
+ /**
1301
+ * Builds drop foreign key sql.
1302
+ */
1303
+ dropForeignKeySql(table, foreignKeyOrName) {
1304
+ const foreignKeyName = foreignKeyOrName instanceof TableForeignKey
1305
+ ? foreignKeyOrName.name
1306
+ : foreignKeyOrName;
1307
+ return new Query(`ALTER TABLE ${this.escapePath(table)} DROP CONSTRAINT \`${foreignKeyName}\``);
1308
+ }
1309
+ /**
1310
+ * Escapes given table or view path.
1311
+ */
1312
+ escapePath(target) {
1313
+ const { tableName } = this.driver.parseTableName(target);
1314
+ return `\`${tableName}\``;
1315
+ }
1316
+ /**
1317
+ * Builds a part of query to create/change a column.
1318
+ */
1319
+ buildCreateColumnSql(column) {
1320
+ let c = `${this.driver.escape(column.name)} ${this.connection.driver.createFullType(column)}`;
1321
+ if (column.asExpression) {
1322
+ c += ` AS (${column.asExpression}) ${column.generatedType ? column.generatedType : "STORED"}`;
1323
+ }
1324
+ else {
1325
+ if (!column.isNullable)
1326
+ c += " NOT NULL";
1327
+ }
1328
+ return c;
1329
+ }
1330
+ /**
1331
+ * Executes sql used special for schema build.
1332
+ */
1333
+ async executeQueries(upQueries, downQueries) {
1334
+ if (upQueries instanceof Query)
1335
+ upQueries = [upQueries];
1336
+ if (downQueries instanceof Query)
1337
+ downQueries = [downQueries];
1338
+ this.sqlInMemory.upQueries.push(...upQueries);
1339
+ this.sqlInMemory.downQueries.push(...downQueries);
1340
+ // if sql-in-memory mode is enabled then simply store sql in memory and return
1341
+ if (this.sqlMemoryMode === true)
1342
+ return Promise.resolve();
1343
+ for (const { query, parameters } of upQueries) {
1344
+ if (this.isDMLQuery(query)) {
1345
+ await this.query(query, parameters);
1346
+ }
1347
+ else {
1348
+ await this.updateDDL(query, parameters);
1349
+ }
1350
+ }
1351
+ }
1352
+ isDMLQuery(query) {
1353
+ return (query.startsWith("INSERT") ||
1354
+ query.startsWith("UPDATE") ||
1355
+ query.startsWith("DELETE"));
1356
+ }
1357
+ }
1358
+
1359
+ //# sourceMappingURL=SpannerQueryRunner.js.map