Refactoring method createTable (#4456)
* Refactoring method createTable Replacing the weird task + transaction chain, by replacing it with just one transaction that encapsulates the complete logic. * Update PostgresStorageAdapter.js correcting the sequence to match the original exactly. * Update PostgresStorageAdapter.js Nesting the transaction inside a task, so it can execute successfully no matter if the containing task succeeds or fails. * Update PostgresStorageAdapter.js adding the missing bracket.
This commit is contained in:
@@ -684,6 +684,7 @@ export class PostgresStorageAdapter {
|
|||||||
// Just create a table, do not insert in schema
|
// Just create a table, do not insert in schema
|
||||||
createTable(className, schema, conn) {
|
createTable(className, schema, conn) {
|
||||||
conn = conn || this._client;
|
conn = conn || this._client;
|
||||||
|
const self = this;
|
||||||
debug('createTable', className, schema);
|
debug('createTable', className, schema);
|
||||||
const valuesArray = [];
|
const valuesArray = [];
|
||||||
const patternsArray = [];
|
const patternsArray = [];
|
||||||
@@ -721,22 +722,21 @@ export class PostgresStorageAdapter {
|
|||||||
});
|
});
|
||||||
const qs = `CREATE TABLE IF NOT EXISTS $1:name (${patternsArray.join(',')})`;
|
const qs = `CREATE TABLE IF NOT EXISTS $1:name (${patternsArray.join(',')})`;
|
||||||
const values = [className, ...valuesArray];
|
const values = [className, ...valuesArray];
|
||||||
return conn.task(t => {
|
|
||||||
return this._ensureSchemaCollectionExists(t)
|
return conn.task('create-table', function * (t) {
|
||||||
.then(() => t.none(qs, values))
|
try {
|
||||||
.catch(error => {
|
yield self._ensureSchemaCollectionExists(t);
|
||||||
if (error.code === PostgresDuplicateRelationError) {
|
yield t.none(qs, values);
|
||||||
// Table already exists, must have been created by a different request. Ignore error.
|
} catch(error) {
|
||||||
} else {
|
if (error.code !== PostgresDuplicateRelationError) {
|
||||||
throw error;
|
throw error;
|
||||||
}})
|
}
|
||||||
})
|
// ELSE: Table already exists, must have been created by a different request. Ignore the error.
|
||||||
.then(() => {
|
}
|
||||||
return conn.tx('create-relation-tables', t => {
|
yield t.tx('create-table-tx', tx => {
|
||||||
const queries = relations.map((fieldName) => {
|
return tx.batch(relations.map(fieldName => {
|
||||||
return t.none('CREATE TABLE IF NOT EXISTS $<joinTable:name> ("relatedId" varChar(120), "owningId" varChar(120), PRIMARY KEY("relatedId", "owningId") )', {joinTable: `_Join:${fieldName}:${className}`});
|
return tx.none('CREATE TABLE IF NOT EXISTS $<joinTable:name> ("relatedId" varChar(120), "owningId" varChar(120), PRIMARY KEY("relatedId", "owningId") )', {joinTable: `_Join:${fieldName}:${className}`});
|
||||||
});
|
}));
|
||||||
return t.batch(queries);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user