import { DSQL_DATASQUIREL_MARIADB_USER_DATABASES, DSQL_DATASQUIREL_MARIADB_USER_PRIVILEGES, DSQL_DATASQUIREL_MARIADB_USER_TABLES, DSQL_DATASQUIREL_MARIADB_USERS, DsqlTables, } from "../../../types/dsql"; import { DatabaseScopedAccessObject, UserSQLPermissions, UserType, } from "../../../types"; import dsqlCrud from "../../../utils/data-fetching/crud"; import _n from "../../../utils/numberfy"; type Params = { currentAccessedDatabase: DatabaseScopedAccessObject; user: UserType; updatedRecord: DSQL_DATASQUIREL_MARIADB_USERS; }; type Return = { msg?: string; success?: boolean; }; export default async function handleMariadbUserGrantsForDatabasesRecreateRecordsForDatabase({ currentAccessedDatabase, user, updatedRecord, }: Params): Promise { const { accessedDatabase, dbSlug, allGrants, allTables, grants, tables } = currentAccessedDatabase; const insertSQLDbRecord = await dsqlCrud< DSQL_DATASQUIREL_MARIADB_USER_DATABASES, (typeof DsqlTables)[number] >({ action: "insert", table: "mariadb_user_databases", data: { all_privileges: allGrants ? 1 : 0, all_tables: allTables ? 1 : 0, db_id: _n(accessedDatabase.dbId), db_slug: accessedDatabase.dbSlug, db_schema_id: _n(accessedDatabase.dbSchemaId), user_id: user.id, mariadb_user_id: updatedRecord.id, }, }); if (tables?.[0]) { for (let t = 0; t < tables.length; t++) { const table = tables[t]; const insertTable = await dsqlCrud< DSQL_DATASQUIREL_MARIADB_USER_TABLES, (typeof DsqlTables)[number] >({ action: "insert", table: "mariadb_user_tables", data: { all_privileges: allGrants ? 1 : 0, all_fields: 1, user_id: user.id, mariadb_user_id: updatedRecord.id, table_slug: table.tableSlug, db_id: _n(table.dbId), db_slug: table.dbSlug, db_schema_id: _n(table.dbSchemaId), }, }); } } if (grants?.[0]) { const isGrantsInalid = grants.find( (g) => !UserSQLPermissions.includes(g) ); if (isGrantsInalid) { return { msg: `grants is/are invalid!` }; } for (let t = 0; t < grants.length; t++) { const grant = grants[t]; await dsqlCrud< DSQL_DATASQUIREL_MARIADB_USER_PRIVILEGES, (typeof DsqlTables)[number] >({ action: "insert", table: "mariadb_user_privileges", data: { user_id: user.id, mariadb_user_id: updatedRecord.id, privilege: grant, db_id: _n(accessedDatabase.dbId), db_slug: accessedDatabase.dbSlug, db_schema_id: _n(accessedDatabase.dbSchemaId), }, }); } } return { success: true }; }