Skip to content

Commit a868bed

Browse files
authored
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.
1 parent 34453bf commit a868bed

File tree

1 file changed

+16
-16
lines changed

1 file changed

+16
-16
lines changed

src/Adapters/Storage/Postgres/PostgresStorageAdapter.js

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -684,6 +684,7 @@ export class PostgresStorageAdapter {
684684
// Just create a table, do not insert in schema
685685
createTable(className, schema, conn) {
686686
conn = conn || this._client;
687+
const self = this;
687688
debug('createTable', className, schema);
688689
const valuesArray = [];
689690
const patternsArray = [];
@@ -721,24 +722,23 @@ export class PostgresStorageAdapter {
721722
});
722723
const qs = `CREATE TABLE IF NOT EXISTS $1:name (${patternsArray.join(',')})`;
723724
const values = [className, ...valuesArray];
724-
return conn.task(t => {
725-
return this._ensureSchemaCollectionExists(t)
726-
.then(() => t.none(qs, values))
727-
.catch(error => {
728-
if (error.code === PostgresDuplicateRelationError) {
729-
// Table already exists, must have been created by a different request. Ignore error.
730-
} else {
725+
726+
return conn.task('create-table', function * (t) {
727+
try {
728+
yield self._ensureSchemaCollectionExists(t);
729+
yield t.none(qs, values);
730+
} catch(error) {
731+
if (error.code !== PostgresDuplicateRelationError) {
731732
throw error;
732-
}})
733-
})
734-
.then(() => {
735-
return conn.tx('create-relation-tables', t => {
736-
const queries = relations.map((fieldName) => {
737-
return t.none('CREATE TABLE IF NOT EXISTS $<joinTable:name> ("relatedId" varChar(120), "owningId" varChar(120), PRIMARY KEY("relatedId", "owningId") )', {joinTable: `_Join:${fieldName}:${className}`});
738-
});
739-
return t.batch(queries);
740-
});
733+
}
734+
// ELSE: Table already exists, must have been created by a different request. Ignore the error.
735+
}
736+
yield t.tx('create-table-tx', tx => {
737+
return tx.batch(relations.map(fieldName => {
738+
return tx.none('CREATE TABLE IF NOT EXISTS $<joinTable:name> ("relatedId" varChar(120), "owningId" varChar(120), PRIMARY KEY("relatedId", "owningId") )', {joinTable: `_Join:${fieldName}:${className}`});
739+
}));
741740
});
741+
});
742742
}
743743

744744
addFieldIfNotExists(className, fieldName, type) {

0 commit comments

Comments
 (0)