Skip to content

Commit cdda7d5

Browse files
vitaly-tflovilmart
authored andcommitted
refactoring method createClass (#4465)
* refactoring method createClass Removing error-analysis conditions that are irrelevant, i.e. since we are only returning the batch, the error will always have `data` set to the size of the input array, as per [the library's API](http://vitaly-t.github.io/spex/errors.BatchError.html). * Update PostgresStorageAdapter.js removing the use of the default separator.
1 parent 836b768 commit cdda7d5

File tree

1 file changed

+32
-34
lines changed

1 file changed

+32
-34
lines changed

src/Adapters/Storage/Postgres/PostgresStorageAdapter.js

Lines changed: 32 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ const buildWhereClause = ({ schema, query, index }) => {
244244
inPatterns.push(`${listElem}`);
245245
}
246246
});
247-
patterns.push(`(${name})::jsonb @> '[${inPatterns.join(',')}]'::jsonb`);
247+
patterns.push(`(${name})::jsonb @> '[${inPatterns.join()}]'::jsonb`);
248248
} else if (fieldValue.$regex) {
249249
// Handle later
250250
} else {
@@ -327,9 +327,9 @@ const buildWhereClause = ({ schema, query, index }) => {
327327
}
328328
});
329329
if (allowNull) {
330-
patterns.push(`($${index}:name IS NULL OR $${index}:name && ARRAY[${inPatterns.join(',')}])`);
330+
patterns.push(`($${index}:name IS NULL OR $${index}:name && ARRAY[${inPatterns.join()}])`);
331331
} else {
332-
patterns.push(`$${index}:name && ARRAY[${inPatterns.join(',')}]`);
332+
patterns.push(`$${index}:name && ARRAY[${inPatterns.join()}]`);
333333
}
334334
index = index + 1 + inPatterns.length;
335335
} else if (isInOrNin) {
@@ -353,7 +353,7 @@ const buildWhereClause = ({ schema, query, index }) => {
353353
inPatterns.push(`$${index + 1 + listIndex}`);
354354
}
355355
});
356-
patterns.push(`$${index}:name ${not} IN (${inPatterns.join(',')})`);
356+
patterns.push(`$${index}:name ${not} IN (${inPatterns.join()})`);
357357
index = index + 1 + inPatterns.length;
358358
}
359359
} else if (!notIn) {
@@ -673,17 +673,15 @@ export class PostgresStorageAdapter implements StorageAdapter {
673673
const q1 = this.createTable(className, schema, t);
674674
const q2 = t.none('INSERT INTO "_SCHEMA" ("className", "schema", "isParseClass") VALUES ($<className>, $<schema>, true)', { className, schema });
675675
const q3 = this.setIndexesWithSchemaFormat(className, schema.indexes, {}, schema.fields, t);
676-
677676
return t.batch([q1, q2, q3]);
678677
})
679678
.then(() => {
680-
return toParseSchema(schema)
679+
return toParseSchema(schema);
681680
})
682-
.catch((err) => {
683-
if (Array.isArray(err.data) && err.data.length > 1 && err.data[0].result.code === PostgresTransactionAbortedError) {
681+
.catch(err => {
682+
if (err.data[0].result.code === PostgresTransactionAbortedError) {
684683
err = err.data[1].result;
685684
}
686-
687685
if (err.code === PostgresUniqueIndexViolationError && err.detail.includes(className)) {
688686
throw new Parse.Error(Parse.Error.DUPLICATE_VALUE, `Class ${className} already exists.`)
689687
}
@@ -730,17 +728,17 @@ export class PostgresStorageAdapter implements StorageAdapter {
730728
}
731729
index = index + 2;
732730
});
733-
const qs = `CREATE TABLE IF NOT EXISTS $1:name (${patternsArray.join(',')})`;
731+
const qs = `CREATE TABLE IF NOT EXISTS $1:name (${patternsArray.join()})`;
734732
const values = [className, ...valuesArray];
735-
733+
736734
return conn.task('create-table', function * (t) {
737735
try {
738736
yield self._ensureSchemaCollectionExists(t);
739737
yield t.none(qs, values);
740738
} catch(error) {
741-
if (error.code !== PostgresDuplicateRelationError) {
742-
throw error;
743-
}
739+
if (error.code !== PostgresDuplicateRelationError) {
740+
throw error;
741+
}
744742
// ELSE: Table already exists, must have been created by a different request. Ignore the error.
745743
}
746744
yield t.tx('create-table-tx', tx => {
@@ -764,14 +762,14 @@ export class PostgresStorageAdapter implements StorageAdapter {
764762
postgresType: parseTypeToPostgresType(type)
765763
});
766764
} catch(error) {
767-
if (error.code === PostgresRelationDoesNotExistError) {
768-
return yield self.createClass(className, {fields: {[fieldName]: type}}, t);
769-
}
770-
if (error.code !== PostgresDuplicateColumnError) {
771-
throw error;
772-
}
773-
// Column already exists, created by other request. Carry on to see if it's the right type.
774-
};
765+
if (error.code === PostgresRelationDoesNotExistError) {
766+
return yield self.createClass(className, {fields: {[fieldName]: type}}, t);
767+
}
768+
if (error.code !== PostgresDuplicateColumnError) {
769+
throw error;
770+
}
771+
// Column already exists, created by other request. Carry on to see if it's the right type.
772+
}
775773
} else {
776774
yield t.none('CREATE TABLE IF NOT EXISTS $<joinTable:name> ("relatedId" varChar(120), "owningId" varChar(120), PRIMARY KEY("relatedId", "owningId") )', {joinTable: `_Join:${fieldName}:${className}`});
777775
}
@@ -803,7 +801,7 @@ export class PostgresStorageAdapter implements StorageAdapter {
803801
const now = new Date().getTime();
804802
const helpers = this._pgp.helpers;
805803
debug('deleteAllClasses');
806-
804+
807805
return this._client.task('delete-all-classes', function * (t) {
808806
try {
809807
const results = yield t.any('SELECT * FROM "_SCHEMA"');
@@ -820,8 +818,8 @@ export class PostgresStorageAdapter implements StorageAdapter {
820818
// No _SCHEMA collection. Don't delete anything.
821819
}
822820
}).then(() => {
823-
debug(`deleteAllClasses done in ${new Date().getTime() - now}`);
824-
});
821+
debug(`deleteAllClasses done in ${new Date().getTime() - now}`);
822+
});
825823
}
826824

827825
// Remove the column and all the data. For Relations, the _Join collection is handled
@@ -869,7 +867,7 @@ export class PostgresStorageAdapter implements StorageAdapter {
869867
return this._client.task('get-all-classes', function * (t) {
870868
yield self._ensureSchemaCollectionExists(t);
871869
return yield t.map('SELECT * FROM "_SCHEMA"', null, row => toParseSchema({ className: row.className, ...row.schema }));
872-
});
870+
});
873871
}
874872

875873
// Return a promise for the schema with the given name, in Parse format. If
@@ -1001,8 +999,8 @@ export class PostgresStorageAdapter implements StorageAdapter {
1001999
return `POINT($${l}, $${l + 1})`;
10021000
});
10031001

1004-
const columnsPattern = columnsArray.map((col, index) => `$${index + 2}:name`).join(',');
1005-
const valuesPattern = initialValues.concat(geoPointsInjects).join(',')
1002+
const columnsPattern = columnsArray.map((col, index) => `$${index + 2}:name`).join();
1003+
const valuesPattern = initialValues.concat(geoPointsInjects).join()
10061004

10071005
const qs = `INSERT INTO $1:name (${columnsPattern}) VALUES (${valuesPattern})`
10081006
const values = [className, ...columnsArray, ...valuesArray]
@@ -1240,7 +1238,7 @@ export class PostgresStorageAdapter implements StorageAdapter {
12401238
values.push(...where.values);
12411239

12421240
const whereClause = where.pattern.length > 0 ? `WHERE ${where.pattern}` : '';
1243-
const qs = `UPDATE $1:name SET ${updatePatterns.join(',')} ${whereClause} RETURNING *`;
1241+
const qs = `UPDATE $1:name SET ${updatePatterns.join()} ${whereClause} RETURNING *`;
12441242
debug('update: ', qs, values);
12451243
return this._client.any(qs, values);
12461244
}
@@ -1284,11 +1282,11 @@ export class PostgresStorageAdapter implements StorageAdapter {
12841282
return `"${key}" ASC`;
12851283
}
12861284
return `"${key}" DESC`;
1287-
}).join(',');
1285+
}).join();
12881286
sortPattern = sort !== undefined && Object.keys(sort).length > 0 ? `ORDER BY ${sorting}` : '';
12891287
}
12901288
if (where.sorts && Object.keys((where.sorts: any)).length > 0) {
1291-
sortPattern = `ORDER BY ${where.sorts.join(',')}`;
1289+
sortPattern = `ORDER BY ${where.sorts.join()}`;
12921290
}
12931291

12941292
let columns = '*';
@@ -1302,7 +1300,7 @@ export class PostgresStorageAdapter implements StorageAdapter {
13021300
return `ts_rank_cd(to_tsvector($${2}, $${3}:name), to_tsquery($${4}, $${5}), 32) as score`;
13031301
}
13041302
return `$${index + values.length + 1}:name`;
1305-
}).join(',');
1303+
}).join();
13061304
values = values.concat(keys);
13071305
}
13081306

@@ -1405,7 +1403,7 @@ export class PostgresStorageAdapter implements StorageAdapter {
14051403
// Will happily create the same index with multiple names.
14061404
const constraintName = `unique_${fieldNames.sort().join('_')}`;
14071405
const constraintPatterns = fieldNames.map((fieldName, index) => `$${index + 3}:name`);
1408-
const qs = `ALTER TABLE $1:name ADD CONSTRAINT $2:name UNIQUE (${constraintPatterns.join(',')})`;
1406+
const qs = `ALTER TABLE $1:name ADD CONSTRAINT $2:name UNIQUE (${constraintPatterns.join()})`;
14091407
return this._client.none(qs, [className, constraintName, ...fieldNames])
14101408
.catch(error => {
14111409
if (error.code === PostgresDuplicateRelationError && error.message.includes(constraintName)) {
@@ -1549,7 +1547,7 @@ export class PostgresStorageAdapter implements StorageAdapter {
15491547
return `"${key}" ASC`;
15501548
}
15511549
return `"${key}" DESC`;
1552-
}).join(',');
1550+
}).join();
15531551
sortPattern = sort !== undefined && Object.keys(sort).length > 0 ? `ORDER BY ${sorting}` : '';
15541552
}
15551553
}

0 commit comments

Comments
 (0)