using System.Data; using System.Text.RegularExpressions; using Database.Common; using Insight.Database; namespace Database.RolesPermissionSystem { public class Setup { private readonly IDbConnection _db; public Setup(IDbConnection db) { _db = db ?? throw new ArgumentNullException(nameof(db)); } /// /// Creates the system tables in the specified schema within a transaction. /// /// The schema name where the tables will be created. public void CreateSystem(string schema) { if (!Validations.IsValidSchemaName(schema)) throw new ArgumentException("Invalid schema name", nameof(schema)); using (var transaction = _db.BeginTransaction()) { try { CreateRolesTable(schema, transaction); CreatePermissionsTable(schema, transaction); CreatePermissionTypesTable(schema, transaction); CreateRolePermissionsTable(schema, transaction); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); throw new InvalidOperationException("Failed to create system tables.", ex); } } } private void ExecuteSql(string sql, IDbTransaction transaction) { if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException(nameof(sql)); _db.Execute(sql, transaction: transaction); } private void CreatePermissionTypesTable(string schema, IDbTransaction transaction) { var sql = $@" CREATE TABLE IF NOT EXISTS {schema}.permission_types ( id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL UNIQUE )"; ExecuteSql(sql, transaction); } private void CreatePermissionsTable(string schema, IDbTransaction transaction) { var sql = $@" CREATE TABLE IF NOT EXISTS {schema}.permissions ( id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL UNIQUE, type_id INTEGER NOT NULL, FOREIGN KEY (type_id) REFERENCES {schema}.permission_types(id) )"; ExecuteSql(sql, transaction); } private void CreateRolesTable(string schema, IDbTransaction transaction) { var sql = $@" CREATE TABLE IF NOT EXISTS {schema}.roles ( id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL UNIQUE )"; ExecuteSql(sql, transaction); } private void CreateRolePermissionsTable(string schema, IDbTransaction transaction) { var sql = $@" CREATE TABLE IF NOT EXISTS {schema}.role_permissions ( role_id INTEGER NOT NULL, permission_id INTEGER NOT NULL, PRIMARY KEY (role_id, permission_id), FOREIGN KEY (role_id) REFERENCES {schema}.roles(id), FOREIGN KEY (permission_id) REFERENCES {schema}.permissions(id) )"; ExecuteSql(sql, transaction); } } }