From 7facb8dcd71157789971b22aed0b5ddfc2e7e751 Mon Sep 17 00:00:00 2001 From: mipo Date: Mon, 9 May 2022 00:06:33 +0200 Subject: [PATCH] fix(createTableAndIndexes): do not try to create table and indexes when already exists --- src/repository.ts | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/src/repository.ts b/src/repository.ts index ee85dd7..963649c 100644 --- a/src/repository.ts +++ b/src/repository.ts @@ -158,6 +158,21 @@ export class Repository { */ private async createTable(): Promise { + const selectTable = await this.queryService.querySingle<{ + name: string; + }>( + [ + `SELECT i.name`, + `FROM information_schema.user_tables AS i`, + `WHERE i.name = ? AND i.status = ?`, + ].join(' '), + this.config.tableName, + 'ACTIVE', + ); + if (selectTable?.name === this.config.tableName) { + return 1; + } + const result = await this.queryService.execute( `CREATE TABLE ${this.config.tableName}`, ); @@ -172,7 +187,25 @@ export class Repository { private async createIndexes(indexFields: string[]) { const results: Result[] = []; - for (const field of indexFields) { + + const selectIndex = await this.queryService.query<{ + expr: string; + indexId: string; + status: string; + }>( + [ + `SELECT VALUE indexes`, + `FROM information_schema.user_tables AS i, i.indexes AS indexes`, + `WHERE i.name = ?`, + ].join(' '), + ); + + const currentIndex = selectIndex.map(val => val.expr); + const newIndexFields = indexFields.filter( + field => currentIndex.indexOf(field) === -1, + ); + + for (const field of newIndexFields) { try { const result = await this.queryService.execute( `CREATE INDEX ON ${this.config.tableName} (${field})`,