Add feature to add multiple unique constraints to db tables + remove trailing commas

This commit is contained in:
AbegaM
2024-02-13 17:44:17 +03:00
parent 12656b3d7a
commit 3fa13e6d5b
3 changed files with 28 additions and 19 deletions

View File

@@ -52,7 +52,7 @@ module.exports = {
},
{
name: 'tableName',
name: 'table_name',
type: 'TEXT',
primaryKey: false,
notNull: true,

View File

@@ -18,16 +18,22 @@ const createDefaultTables = async () => {
tableService.createTable('_users', dbTables.userSchema);
}
if (!usersRolesTable) {
tableService.createTable('_users_roles', dbTables.usersRoleSchema);
}
if (!rolesPermissionTable) {
tableService.createTable(
'_roles_permissions',
dbTables.rolePermissionSchema,
{
multipleUniqueConstraints: {
name: 'unique_role_table',
fields: ['role_id', 'table_name'],
},
},
);
}
if (!usersRolesTable) {
tableService.createTable('_users_roles', dbTables.usersRoleSchema);
}
};
module.exports = { createDefaultTables };

View File

@@ -1,11 +1,12 @@
module.exports = (db) => {
return {
createTable(
tableName,
schema,
createTable(tableName, schema, options = {}) {
const {
autoAddCreatedAt = true,
autoAddUpdatedAt = true,
) {
multipleUniqueConstraints,
} = options;
let indices = [];
let schemaString = schema
@@ -45,17 +46,19 @@ module.exports = (db) => {
// add created at and updated at
if (autoAddCreatedAt) {
schemaString = `
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
${schemaString}
`;
schemaString = `${schemaString}, createdAt DATETIME DEFAULT CURRENT_TIMESTAMP`;
}
if (autoAddUpdatedAt) {
schemaString = `
updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP,
${schemaString}
`;
schemaString = `${schemaString}, updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP`;
}
if (multipleUniqueConstraints) {
schemaString = `${schemaString}, CONSTRAINT ${
multipleUniqueConstraints.name
} UNIQUE (${multipleUniqueConstraints.fields
.map((field) => field)
.join(' ,')})`;
}
let indicesString = indices