@dqcai/sqlite 2.0.2 → 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.mjs CHANGED
@@ -1,16 +1,16 @@
1
- class O{constructor(t,e,i){var s,a;this.adapter=t,this.dbPath=e,this.options=i,this.connection=null,this.isConnected=!1,this.inTransaction=!1,this.typeMappingConfig=null,this.createIfNotExists=!1,this.forceRecreate=!1,this.createIfNotExists=(s=i==null?void 0:i.createIfNotExists)!==null&&s!==void 0?s:!1,this.forceRecreate=(a=i==null?void 0:i.forceRecreate)!==null&&a!==void 0?a:!1}async connect(){this.isConnected||(this.connection=await this.adapter.connect(this.dbPath),this.isConnected=!0)}async disconnect(){this.connection&&this.isConnected&&(await this.connection.close(),this.connection=null,this.isConnected=!1)}async close(){await this.disconnect()}setTypeMappingConfig(t){this.typeMappingConfig=t}convertToSQLiteType(t){return!this.typeMappingConfig||!this.typeMappingConfig.sqlite?this.getDefaultSQLiteType(t):this.typeMappingConfig.sqlite[t.toLowerCase()]||"TEXT"}getDefaultSQLiteType(t){return{string:"TEXT",varchar:"TEXT",char:"TEXT",email:"TEXT",url:"TEXT",uuid:"TEXT",integer:"INTEGER",bigint:"INTEGER",smallint:"INTEGER",tinyint:"INTEGER",decimal:"REAL",numeric:"REAL",float:"REAL",double:"REAL",boolean:"INTEGER",timestamp:"TEXT",datetime:"TEXT",date:"TEXT",time:"TEXT",json:"TEXT",array:"TEXT",blob:"BLOB",binary:"BLOB"}[t.toLowerCase()]||"TEXT"}processColumnDefinition(t){const e=Object.assign({},t);e.type=this.convertToSQLiteType(t.type);const i=[];if(t.constraints){const s=t.constraints.toUpperCase().split(" ");s.includes("PRIMARY")&&(i.push("PRIMARY KEY"),e.primary_key=!0),(s.includes("AUTO_INCREMENT")||s.includes("AUTOINCREMENT"))&&(e.primary_key&&i.push("AUTOINCREMENT"),e.auto_increment=!0),s.includes("NOT")&&s.includes("NULL")&&(i.push("NOT NULL"),e.nullable=!1),s.includes("UNIQUE")&&(e.primary_key||i.push("UNIQUE"),e.unique=!0);const a=s.indexOf("DEFAULT");if(a!==-1&&s.length>a+1){const r=s[a+1];i.push(`DEFAULT ${r}`),e.default=r}}return e.option_key=i.join(" ").trim(),e}async initializeFromSchema(t){var e;this.ensureConnected();let i=!1;try{i=(await this.execute("SELECT version FROM _schema_info ORDER BY applied_at DESC LIMIT 1")).rows.length>0}catch(s){i=!1}if(i&&!this.createIfNotExists&&!this.forceRecreate){t.type_mapping&&this.setTypeMappingConfig(t.type_mapping);return}i&&this.forceRecreate&&await this.dropAllTables(),t.type_mapping&&this.setTypeMappingConfig(t.type_mapping);try{await this.execute("PRAGMA foreign_keys = ON")}catch(s){}await this.beginTransaction();try{for(const[s,a]of Object.entries(t.schemas)){const r={name:s,cols:a.cols.map(n=>this.processColumnDefinition(n)),description:a.description,indexes:a.indexes,foreign_keys:a.foreign_keys};await this.createTableWithForeignKeys(r)}for(const[s,a]of Object.entries(t.schemas))!((e=a.indexes)===null||e===void 0)&&e.length&&await this.createIndexesForTable(s,a.indexes);await this.setSchemaVersion(t.version),await this.commitTransaction()}catch(s){throw await this.rollbackTransaction(),s}}async dropAllTables(){const t=await this.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");await this.beginTransaction();try{for(const e of t.rows)await this.execute(`DROP TABLE IF EXISTS ${e.name}`);await this.commitTransaction()}catch(e){throw await this.rollbackTransaction(),e}}async createTableWithForeignKeys(t){const e=t.cols.map(r=>`${r.name} ${r.type} ${r.option_key||""}`.trim()),i=[];if(t.foreign_keys)for(const r of t.foreign_keys){let n=`FOREIGN KEY (${r.column}) REFERENCES ${r.references.table}(${r.references.column})`;r.on_delete&&(n+=` ON DELETE ${r.on_delete}`),r.on_update&&(n+=` ON UPDATE ${r.on_update}`),i.push(n)}const s=[...e,...i],a=`CREATE TABLE IF NOT EXISTS ${t.name} (${s.join(", ")})`;await this.execute(a)}async createIndexesForTable(t,e){for(const i of e){const s=i.columns.join(", "),a=`CREATE ${i.unique?"UNIQUE":""} INDEX IF NOT EXISTS ${i.name} ON ${t} (${s})`;await this.execute(a)}}async beginTransaction(){if(this.inTransaction)throw new Error("Transaction already in progress");await this.execute("BEGIN TRANSACTION"),this.inTransaction=!0}async commitTransaction(){if(!this.inTransaction)throw new Error("No transaction in progress");await this.execute("COMMIT"),this.inTransaction=!1}async rollbackTransaction(){if(!this.inTransaction)throw new Error("No transaction in progress");await this.execute("ROLLBACK"),this.inTransaction=!1}async getSchemaVersion(){try{return(await this.getRst("SELECT version FROM _schema_info ORDER BY applied_at DESC LIMIT 1")).version||"0"}catch(t){return"0"}}async setSchemaVersion(t){await this.execute(`CREATE TABLE IF NOT EXISTS _schema_info (
1
+ class O{constructor(e,t,i){var s,a;this.adapter=e,this.dbPath=t,this.options=i,this.connection=null,this.isConnected=!1,this.inTransaction=!1,this.typeMappingConfig=null,this.createIfNotExists=!1,this.forceRecreate=!1,this.createIfNotExists=(s=i==null?void 0:i.createIfNotExists)!==null&&s!==void 0?s:!1,this.forceRecreate=(a=i==null?void 0:i.forceRecreate)!==null&&a!==void 0?a:!1}async connect(){this.isConnected||(this.connection=await this.adapter.connect(this.dbPath),this.isConnected=!0)}async disconnect(){this.connection&&this.isConnected&&(await this.connection.close(),this.connection=null,this.isConnected=!1)}async close(){await this.disconnect()}setTypeMappingConfig(e){this.typeMappingConfig=e}convertToSQLiteType(e){return!this.typeMappingConfig||!this.typeMappingConfig.sqlite?this.getDefaultSQLiteType(e):this.typeMappingConfig.sqlite[e.toLowerCase()]||"TEXT"}getDefaultSQLiteType(e){return{string:"TEXT",varchar:"TEXT",char:"TEXT",email:"TEXT",url:"TEXT",uuid:"TEXT",integer:"INTEGER",bigint:"INTEGER",smallint:"INTEGER",tinyint:"INTEGER",decimal:"REAL",numeric:"REAL",float:"REAL",double:"REAL",boolean:"INTEGER",timestamp:"TEXT",datetime:"TEXT",date:"TEXT",time:"TEXT",json:"TEXT",array:"TEXT",blob:"BLOB",binary:"BLOB"}[e.toLowerCase()]||"TEXT"}processColumnDefinition(e){const t=Object.assign({},e);t.type=this.convertToSQLiteType(e.type);const i=[];if(e.constraints){const s=e.constraints.toUpperCase().split(" ");s.includes("PRIMARY")&&(i.push("PRIMARY KEY"),t.primary_key=!0),(s.includes("AUTO_INCREMENT")||s.includes("AUTOINCREMENT"))&&(t.primary_key&&i.push("AUTOINCREMENT"),t.auto_increment=!0),s.includes("NOT")&&s.includes("NULL")&&(i.push("NOT NULL"),t.nullable=!1),s.includes("UNIQUE")&&(t.primary_key||i.push("UNIQUE"),t.unique=!0);const a=s.indexOf("DEFAULT");if(a!==-1&&s.length>a+1){const n=s[a+1];i.push(`DEFAULT ${n}`),t.default=n}}return t.option_key=i.join(" ").trim(),t}async initializeFromSchema(e){var t;this.ensureConnected();let i=!1;try{i=(await this.execute("SELECT version FROM _schema_info ORDER BY applied_at DESC LIMIT 1")).rows.length>0}catch(s){i=!1}if(i&&!this.createIfNotExists&&!this.forceRecreate){e.type_mapping&&this.setTypeMappingConfig(e.type_mapping);return}i&&this.forceRecreate&&await this.dropAllTables(),e.type_mapping&&this.setTypeMappingConfig(e.type_mapping);try{await this.execute("PRAGMA foreign_keys = ON")}catch(s){}await this.beginTransaction();try{for(const[s,a]of Object.entries(e.schemas)){const n={name:s,cols:a.cols.map(r=>this.processColumnDefinition(r)),description:a.description,indexes:a.indexes,foreign_keys:a.foreign_keys};await this.createTableWithForeignKeys(n)}for(const[s,a]of Object.entries(e.schemas))!((t=a.indexes)===null||t===void 0)&&t.length&&await this.createIndexesForTable(s,a.indexes);await this.setSchemaVersion(e.version),await this.commitTransaction()}catch(s){throw await this.rollbackTransaction(),s}}async dropAllTables(){const e=await this.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");await this.beginTransaction();try{for(const t of e.rows)await this.execute(`DROP TABLE IF EXISTS ${t.name}`);await this.commitTransaction()}catch(t){throw await this.rollbackTransaction(),t}}async createTableWithForeignKeys(e){const t=e.cols.map(n=>`${n.name} ${n.type} ${n.option_key||""}`.trim()),i=[];if(e.foreign_keys)for(const n of e.foreign_keys){let r=`FOREIGN KEY (${n.column}) REFERENCES ${n.references.table}(${n.references.column})`;n.on_delete&&(r+=` ON DELETE ${n.on_delete}`),n.on_update&&(r+=` ON UPDATE ${n.on_update}`),i.push(r)}const s=[...t,...i],a=`CREATE TABLE IF NOT EXISTS ${e.name} (${s.join(", ")})`;await this.execute(a)}async createIndexesForTable(e,t){for(const i of t){const s=i.columns.join(", "),a=`CREATE ${i.unique?"UNIQUE":""} INDEX IF NOT EXISTS ${i.name} ON ${e} (${s})`;await this.execute(a)}}async beginTransaction(){if(this.inTransaction)throw new Error("Transaction already in progress");await this.execute("BEGIN TRANSACTION"),this.inTransaction=!0}async commitTransaction(){if(!this.inTransaction)throw new Error("No transaction in progress");await this.execute("COMMIT"),this.inTransaction=!1}async rollbackTransaction(){if(!this.inTransaction)throw new Error("No transaction in progress");await this.execute("ROLLBACK"),this.inTransaction=!1}async getSchemaVersion(){try{return(await this.getRst("SELECT version FROM _schema_info ORDER BY applied_at DESC LIMIT 1")).version||"0"}catch(e){return"0"}}async setSchemaVersion(e){await this.execute(`CREATE TABLE IF NOT EXISTS _schema_info (
2
2
  version TEXT NOT NULL,
3
3
  applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
4
- )`),await this.execute("INSERT INTO _schema_info (version) VALUES (?)",[t])}async insert(t){const e=t.cols.filter(n=>n.value!==void 0&&n.value!==null);if(e.length===0)throw new Error("No valid columns to insert");const i=e.map(n=>n.name).join(", "),s=e.map(()=>"?").join(", "),a=e.map(n=>typeof n.value=="object"?JSON.stringify(n.value):n.value),r=`INSERT INTO ${t.name} (${i}) VALUES (${s})`;return await this.execute(r,a)}async update(t){const e=t.cols.filter(n=>{var o;return n.value!==void 0&&!(!((o=t.wheres)===null||o===void 0)&&o.some(l=>l.name===n.name))});if(e.length===0)throw new Error("No columns to update");const i=e.map(n=>`${n.name} = ?`).join(", "),s=e.map(n=>typeof n.value=="object"?JSON.stringify(n.value):n.value);let a=`UPDATE ${t.name} SET ${i}`;const r=this.buildWhereClause(t.wheres);if(!r.sql)throw new Error("WHERE clause is required for UPDATE operation");return a+=r.sql,s.push(...r.params),await this.execute(a,s)}async delete(t){let e=`DELETE FROM ${t.name}`;const i=this.buildWhereClause(t.wheres);if(!i.sql)throw new Error("WHERE clause is required for DELETE operation");return e+=i.sql,await this.execute(e,i.params)}async select(t){const{sql:e,params:i}=this.buildSelectQuery(t," LIMIT 1");return(await this.execute(e,i)).rows[0]||{}}async selectAll(t){const{sql:e,params:i}=this.buildSelectQuery(t);return(await this.execute(e,i)).rows}buildSelectQuery(t,e=""){var i;let s=`SELECT ${t.cols.length>0?t.cols.map(r=>r.name).join(", "):"*"} FROM ${t.name}`;const a=this.buildWhereClause(t.wheres);if(s+=a.sql,!((i=t.orderbys)===null||i===void 0)&&i.length){const r=t.orderbys.map(n=>`${n.name} ${n.direction||"ASC"}`).join(", ");s+=` ORDER BY ${r}`}return t.limitOffset&&(t.limitOffset.limit&&(s+=` LIMIT ${t.limitOffset.limit}`),t.limitOffset.offset&&(s+=` OFFSET ${t.limitOffset.offset}`)),s+=e,{sql:s,params:a.params}}buildWhereClause(t,e="WHERE"){if(!t||t.length===0)return{sql:"",params:[]};const i=[],s=[];for(const a of t){const r=a.operator||"=";i.push(`${a.name} ${r} ?`),s.push(a.value)}return{sql:` ${e} ${i.join(" AND ")}`,params:s}}convertJsonToQueryTable(t,e,i=["id"]){var s;const a={name:t,cols:[],wheres:[]};for(const[r,n]of Object.entries(e))a.cols.push({name:r,value:n}),i.includes(r)&&n!==void 0&&((s=a.wheres)===null||s===void 0||s.push({name:r,value:n}));return a}async importData(t){const e=Date.now(),i={totalRows:t.data.length,successRows:0,errorRows:0,errors:[],executionTime:0};if(!this.isConnected)throw new Error("Database is not connected");if(!t.data||t.data.length===0)return i.executionTime=Date.now()-e,i;const s=await this.getTableInfo(t.tableName);if(s.length===0)throw new Error(`Table '${t.tableName}' does not exist`);const a=new Map(s.map(l=>[l.name.toLowerCase(),l])),r=t.batchSize||1e3;let n=0;const o=!t.includeAutoIncrementPK;try{await this.beginTransaction();for(let l=0;l<t.data.length;l+=r){const c=t.data.slice(l,l+r);for(let f=0;f<c.length;f++){const u=l+f,m=c[f];try{const p=t.validateData?this.validateAndTransformRow(m,a,t.tableName,o):this.transformRowData(m,a,o);t.updateOnConflict&&t.conflictColumns?await this.insertOrUpdate(t.tableName,p,t.conflictColumns):await this.insertRow(t.tableName,p),i.successRows++}catch(p){i.errorRows++;const y={rowIndex:u,error:p instanceof Error?p.message:String(p),rowData:m};if(i.errors.push(y),t.onError&&t.onError(p instanceof Error?p:new Error(String(p)),u,m),!t.skipErrors)throw p}n++,t.onProgress&&n%100===0&&t.onProgress(n,t.data.length)}}await this.commitTransaction()}catch(l){throw await this.rollbackTransaction(),l}return t.onProgress&&t.onProgress(n,t.data.length),i.executionTime=Date.now()-e,i}async importDataWithMapping(t,e,i,s={}){const a=e.map(r=>{const n={};return i.forEach(o=>{if(r.hasOwnProperty(o.sourceColumn)){let l=r[o.sourceColumn];o.transform&&(l=o.transform(l)),n[o.targetColumn]=l}}),n});return await this.importData(Object.assign({tableName:t,data:a},s))}async importFromCSV(t,e,i={}){const s=i.delimiter||",",a=i.hasHeader!==!1,r=e.split(`
5
- `).filter(c=>c.trim());if(r.length===0)throw new Error("CSV data is empty");let n=[],o=0;if(a)n=r[0].split(s).map(c=>c.trim().replace(/^["']|["']$/g,"")),o=1;else{const c=r[0].split(s).length;n=Array.from({length:c},(f,u)=>`column_${u+1}`)}const l=[];for(let c=o;c<r.length;c++){const f=r[c].split(s).map(m=>m.trim().replace(/^["']|["']$/g,"")),u={};n.forEach((m,p)=>{u[m]=f[p]||null}),l.push(u)}return i.columnMappings?await this.importDataWithMapping(t,l,i.columnMappings,i):await this.importData(Object.assign({tableName:t,data:l},i))}validateAndTransformRow(t,e,i,s=!0){const a={};for(const[r,n]of e.entries()){const o=n.notnull===1&&!n.dflt_value,l=n.pk===1&&n.type.toLowerCase().includes("integer");if(s&&l)continue;const c=this.findValueForColumn(t,r);if(o&&c==null)throw new Error(`Required column '${r}' is missing or null in table '${i}'`);c!=null&&(a[r]=this.convertValueToColumnType(c,n.type))}return a}transformRowData(t,e,i=!0){const s={};for(const[a,r]of Object.entries(t)){const n=a.toLowerCase(),o=e.get(n);if(!o)continue;const l=o.pk===1&&o.type.toLowerCase().includes("integer");i&&l||r!=null&&(s[a]=this.convertValueToColumnType(r,o.type))}return s}findValueForColumn(t,e){if(t.hasOwnProperty(e))return t[e];const i=e.toLowerCase();for(const[s,a]of Object.entries(t))if(s.toLowerCase()===i)return a}convertValueToColumnType(t,e){if(t==null)return null;const i=e.toLowerCase();try{if(i.includes("integer")||i.includes("int")){if(typeof t=="boolean")return t?1:0;const s=parseInt(String(t));return isNaN(s)?null:s}if(i.includes("real")||i.includes("float")||i.includes("decimal")){const s=parseFloat(String(t));return isNaN(s)?null:s}if(i.includes("boolean")){if(typeof t=="boolean")return t?1:0;if(typeof t=="string"){const s=t.toLowerCase();return s==="true"||s==="1"||s==="yes"?1:0}return t?1:0}if(i.includes("json")){if(typeof t=="object")return JSON.stringify(t);if(typeof t=="string")try{return JSON.parse(t),t}catch(s){throw new Error(`Invalid JSON format for column type '${e}'`)}return JSON.stringify(t)}if(i.includes("timestamp")||i.includes("datetime")){if(t instanceof Date)return t.toISOString();if(typeof t=="string"||typeof t=="number"){const s=new Date(t);return isNaN(s.getTime())?t:s.toISOString()}return String(t)}return String(t)}catch(s){throw new Error(`Cannot convert value '${t}' to column type '${e}'`)}}async insertRow(t,e){const i=Object.keys(e),s=Object.values(e),a=i.map(()=>"?").join(", "),r=`INSERT INTO ${t} (${i.join(", ")}) VALUES (${a})`;await this.execute(r,s)}async insertOrUpdate(t,e,i){try{await this.insertRow(t,e)}catch(s){if(this.isConflictError(s))await this.updateRowByColumns(t,e,i);else throw s}}async updateRowByColumns(t,e,i){const s=Object.keys(e).filter(u=>!i.includes(u)),a=i;if(s.length===0)return;const r=s.map(u=>`${u} = ?`).join(", "),n=a.map(u=>`${u} = ?`).join(" AND "),o=s.map(u=>e[u]),l=a.map(u=>e[u]),c=[...o,...l],f=`UPDATE ${t} SET ${r} WHERE ${n}`;await this.execute(f,c)}isConflictError(t){return t.code==="SQLITE_CONSTRAINT_UNIQUE"||t.code==="SQLITE_CONSTRAINT_PRIMARYKEY"||t.message&&t.message.includes("UNIQUE constraint failed")}async getDatabaseInfo(){const t=await this.execute("SELECT name FROM sqlite_master WHERE type='table'"),e=await this.getSchemaVersion();return{name:this.dbPath,tables:t.rows.map(i=>i.name),isConnected:this.isConnected,version:e}}async getTableInfo(t){return(await this.execute(`PRAGMA table_info(${t})`)).rows}async dropTable(t){const e=`DROP TABLE IF EXISTS ${t}`;await this.execute(e)}isConnectionOpen(){return this.isConnected&&!!this.connection}async ensureConnected(){this.isConnectionOpen()||await this.connect()}async execute(t,e=[]){return this.ensureConnected(),await this.connection.execute(t,e)}async getRst(t,e=[]){return(await this.execute(t,e)).rows[0]||{}}async getRsts(t,e=[]){return(await this.execute(t,e)).rows}}class g{static registerAdapter(t){this.adapters.push(t)}static getEnvironmentInfo(){return typeof navigator!="undefined"&&navigator.product==="ReactNative"?"React Native":typeof globalThis.Bun!="undefined"?"Bun":typeof globalThis.Deno!="undefined"?"Deno":typeof window!="undefined"?"Browser":typeof process!="undefined"?"Node.js":"Unknown"}static detectBestAdapter(){for(const t of this.adapters)if(t.isSupported())return t;throw new Error("No supported SQLite adapter found")}static async validateSchemaVersion(t,e){try{const i=await t.getDatabaseInfo();if(i.version!==e.version)throw new Error(`Schema version mismatch: database (${i.version}) vs config (${e.version})`)}catch(i){throw new Error(`Error validating schema version for ${e.database_name}: ${i.message}`)}}static validateSchema(t){if(!t)throw new Error("Schema configuration is null or undefined.");if(typeof t.database_name!="string"||t.database_name.trim()==="")throw new Error("Invalid or missing 'database_name' in schema. This is required to name the database file.");if(typeof t.schemas!="object"||t.schemas===null||Object.keys(t.schemas).length===0)throw new Error("Invalid or missing 'schemas' object in schema. At least one table definition is required.");return!0}static createDAO(t,e){var i,s;let a;return e!=null&&e.adapter?a=e.adapter:a=this.detectBestAdapter(),new O(a,t,{createIfNotExists:(i=e==null?void 0:e.createIfNotExists)!==null&&i!==void 0?i:!1,forceRecreate:(s=e==null?void 0:e.forceRecreate)!==null&&s!==void 0?s:!1})}static async openExisting(t,e={}){const i=t.endsWith(".db")?t:`${t}.db`,s=this.createDAO(i,e);try{return await s.connect(),await s.execute("PRAGMA integrity_check"),s}catch(a){throw await s.close(),new Error(`Error opening database '${i}': ${a.message}`)}}static async createOrOpenInternal(t,e=!1,i=!1){let s;if(t.config)s=t.config;else if(t.configAsset)s=t.configAsset;else throw new Error("Either 'config', 'configAsset', or 'configPath' must be provided to the factory.");this.validateSchema(s);const a=s.database_name.endsWith(".db")?s.database_name:`${s.database_name}.db`,r=this.createDAO(a,{adapter:t.adapter,createIfNotExists:e,forceRecreate:i});try{await r.connect(),await r.initializeFromSchema(s);try{await this.validateSchemaVersion(r,s)}catch(n){throw await r.close(),new Error(`Schema mismatch in existing database. Use forceRecreate=true to recreate with updated schema. Error: ${n.message}`)}return r}catch(n){throw r.isConnectionOpen()&&await r.close(),n}}static async create(t){return this.createOrOpenInternal(t,!0,!0)}static async createOrOpen(t,e=!1){return this.createOrOpenInternal(t,e)}static async createFromAsset(t,e={}){try{return await this.create(Object.assign(Object.assign({},e),{configAsset:t}))}catch(i){throw new Error(`Error creating database from asset: ${i.message}`)}}static async createFromConfig(t,e={}){try{return await this.create(Object.assign(Object.assign({},e),{config:t}))}catch(i){throw new Error(`Error creating database from config: ${i.message}`)}}}g.adapters=[];class h{static setSchemaManager(t){this.schemaManager=t}static registerSchema(t,e){this.schemaConfigurations[t]=e}static registerSchemas(t){Object.entries(t).forEach(([e,i])=>{this.registerSchema(e,i)})}static getSchema(t){if(this.schemaConfigurations[t])return this.schemaConfigurations[t];if(this.schemaManager)return this.schemaManager.getSchema(t)}static getAvailableSchemas(){var t;const e=Object.keys(this.schemaConfigurations),i=((t=this.schemaManager)===null||t===void 0?void 0:t.getAllSchemaKeys())||[];return[...new Set([...e,...i])]}static registerRole(t){this.roleRegistry[t.roleName]=t}static registerRoles(t){t.forEach(e=>this.registerRole(e))}static getRegisteredRoles(){return Object.assign({},this.roleRegistry)}static getRoleDatabases(t){const e=this.roleRegistry[t];if(!e)throw new Error(`Role '${t}' is not registered.`);return[...e.requiredDatabases,...e.optionalDatabases||[]]}static getCurrentUserDatabases(){const t=new Set;t.add("core");for(const e of this.currentUserRoles){const i=this.roleRegistry[e];i&&(i.requiredDatabases.forEach(s=>t.add(s)),i.optionalDatabases&&i.optionalDatabases.forEach(s=>t.add(s)))}return Array.from(t)}static async initializeCoreConnection(){if(!this.connections.core)try{const t=this.getSchema("core");if(!t)throw new Error("Core database schema not found.");const e=await g.createOrOpen({config:t},!1);await e.execute("PRAGMA integrity_check"),this.connections.core=e}catch(t){throw new Error(`Error initializing core database: ${t.message}`)}}static async setCurrentUserRoles(t,e){for(const s of t)if(!this.roleRegistry[s])throw new Error(`Role '${s}' is not registered. Please register it first.`);const i=[...this.currentUserRoles];this.currentUserRoles=t,this.currentRole=e||t[0]||null,await this.initializeUserRoleConnections(),await this.cleanupUnusedConnections(i)}static getCurrentUserRoles(){return[...this.currentUserRoles]}static getCurrentRole(){return this.currentRole}static async initializeUserRoleConnections(){const t=this.getCurrentUserDatabases(),e=[],i=t.map(async s=>{if(!this.connections[s])try{const a=this.getSchema(s);if(!a)throw new Error(`Database key '${s}' not found in schema configurations.`);const r=await g.createOrOpen({config:a},!1);await r.execute("PRAGMA integrity_check"),this.connections[s]=r}catch(a){const r=a instanceof Error?a:new Error(String(a));this.currentUserRoles.some(n=>{const o=this.roleRegistry[n];return o&&o.requiredDatabases.includes(s)})&&e.push({key:s,error:r})}});if(await Promise.all(i),e.length>0){const s=e.map(a=>` - ${a.key}: ${a.error.message}`).join(`
4
+ )`),await this.execute("INSERT INTO _schema_info (version) VALUES (?)",[e])}async insert(e){const t=e.cols.filter(r=>r.value!==void 0&&r.value!==null);if(t.length===0)throw new Error("No valid columns to insert");const i=t.map(r=>r.name).join(", "),s=t.map(()=>"?").join(", "),a=t.map(r=>typeof r.value=="object"?JSON.stringify(r.value):r.value),n=`INSERT INTO ${e.name} (${i}) VALUES (${s})`;return await this.execute(n,a)}async update(e){const t=e.cols.filter(r=>{var o;return r.value!==void 0&&!(!((o=e.wheres)===null||o===void 0)&&o.some(l=>l.name===r.name))});if(t.length===0)throw new Error("No columns to update");const i=t.map(r=>`${r.name} = ?`).join(", "),s=t.map(r=>typeof r.value=="object"?JSON.stringify(r.value):r.value);let a=`UPDATE ${e.name} SET ${i}`;const n=this.buildWhereClause(e.wheres);if(!n.sql)throw new Error("WHERE clause is required for UPDATE operation");return a+=n.sql,s.push(...n.params),await this.execute(a,s)}async delete(e){let t=`DELETE FROM ${e.name}`;const i=this.buildWhereClause(e.wheres);if(!i.sql)throw new Error("WHERE clause is required for DELETE operation");return t+=i.sql,await this.execute(t,i.params)}async select(e){const{sql:t,params:i}=this.buildSelectQuery(e," LIMIT 1");return(await this.execute(t,i)).rows[0]||{}}async selectAll(e){const{sql:t,params:i}=this.buildSelectQuery(e);return(await this.execute(t,i)).rows}buildSelectQuery(e,t=""){var i;let s=`SELECT ${e.cols.length>0?e.cols.map(n=>n.name).join(", "):"*"} FROM ${e.name}`;const a=this.buildWhereClause(e.wheres);if(s+=a.sql,!((i=e.orderbys)===null||i===void 0)&&i.length){const n=e.orderbys.map(r=>`${r.name} ${r.direction||"ASC"}`).join(", ");s+=` ORDER BY ${n}`}return e.limitOffset&&(e.limitOffset.limit&&(s+=` LIMIT ${e.limitOffset.limit}`),e.limitOffset.offset&&(s+=` OFFSET ${e.limitOffset.offset}`)),s+=t,{sql:s,params:a.params}}buildWhereClause(e,t="WHERE"){if(!e||e.length===0)return{sql:"",params:[]};const i=[],s=[];for(const a of e){const n=a.operator||"=";i.push(`${a.name} ${n} ?`),s.push(a.value)}return{sql:` ${t} ${i.join(" AND ")}`,params:s}}convertJsonToQueryTable(e,t,i=["id"]){var s;const a={name:e,cols:[],wheres:[]};for(const[n,r]of Object.entries(t))a.cols.push({name:n,value:r}),i.includes(n)&&r!==void 0&&((s=a.wheres)===null||s===void 0||s.push({name:n,value:r}));return a}async importData(e){const t=Date.now(),i={totalRows:e.data.length,successRows:0,errorRows:0,errors:[],executionTime:0};if(!this.isConnected)throw new Error("Database is not connected");if(!e.data||e.data.length===0)return i.executionTime=Date.now()-t,i;const s=await this.getTableInfo(e.tableName);if(s.length===0)throw new Error(`Table '${e.tableName}' does not exist`);const a=new Map(s.map(l=>[l.name.toLowerCase(),l])),n=e.batchSize||1e3;let r=0;const o=!e.includeAutoIncrementPK;try{await this.beginTransaction();for(let l=0;l<e.data.length;l+=n){const c=e.data.slice(l,l+n);for(let f=0;f<c.length;f++){const u=l+f,m=c[f];try{const p=e.validateData?this.validateAndTransformRow(m,a,e.tableName,o):this.transformRowData(m,a,o);e.updateOnConflict&&e.conflictColumns?await this.insertOrUpdate(e.tableName,p,e.conflictColumns):await this.insertRow(e.tableName,p),i.successRows++}catch(p){i.errorRows++;const y={rowIndex:u,error:p instanceof Error?p.message:String(p),rowData:m};if(i.errors.push(y),e.onError&&e.onError(p instanceof Error?p:new Error(String(p)),u,m),!e.skipErrors)throw p}r++,e.onProgress&&r%100===0&&e.onProgress(r,e.data.length)}}await this.commitTransaction()}catch(l){throw await this.rollbackTransaction(),l}return e.onProgress&&e.onProgress(r,e.data.length),i.executionTime=Date.now()-t,i}async importDataWithMapping(e,t,i,s={}){const a=t.map(n=>{const r={};return i.forEach(o=>{if(n.hasOwnProperty(o.sourceColumn)){let l=n[o.sourceColumn];o.transform&&(l=o.transform(l)),r[o.targetColumn]=l}}),r});return await this.importData(Object.assign({tableName:e,data:a},s))}async importFromCSV(e,t,i={}){const s=i.delimiter||",",a=i.hasHeader!==!1,n=t.split(`
5
+ `).filter(c=>c.trim());if(n.length===0)throw new Error("CSV data is empty");let r=[],o=0;if(a)r=n[0].split(s).map(c=>c.trim().replace(/^["']|["']$/g,"")),o=1;else{const c=n[0].split(s).length;r=Array.from({length:c},(f,u)=>`column_${u+1}`)}const l=[];for(let c=o;c<n.length;c++){const f=n[c].split(s).map(m=>m.trim().replace(/^["']|["']$/g,"")),u={};r.forEach((m,p)=>{u[m]=f[p]||null}),l.push(u)}return i.columnMappings?await this.importDataWithMapping(e,l,i.columnMappings,i):await this.importData(Object.assign({tableName:e,data:l},i))}validateAndTransformRow(e,t,i,s=!0){const a={};for(const[n,r]of t.entries()){const o=r.notnull===1&&!r.dflt_value,l=r.pk===1&&r.type.toLowerCase().includes("integer");if(s&&l)continue;const c=this.findValueForColumn(e,n);if(o&&c==null)throw new Error(`Required column '${n}' is missing or null in table '${i}'`);c!=null&&(a[n]=this.convertValueToColumnType(c,r.type))}return a}transformRowData(e,t,i=!0){const s={};for(const[a,n]of Object.entries(e)){const r=a.toLowerCase(),o=t.get(r);if(!o)continue;const l=o.pk===1&&o.type.toLowerCase().includes("integer");i&&l||n!=null&&(s[a]=this.convertValueToColumnType(n,o.type))}return s}findValueForColumn(e,t){if(e.hasOwnProperty(t))return e[t];const i=t.toLowerCase();for(const[s,a]of Object.entries(e))if(s.toLowerCase()===i)return a}convertValueToColumnType(e,t){if(e==null)return null;const i=t.toLowerCase();try{if(i.includes("integer")||i.includes("int")){if(typeof e=="boolean")return e?1:0;const s=parseInt(String(e));return isNaN(s)?null:s}if(i.includes("real")||i.includes("float")||i.includes("decimal")){const s=parseFloat(String(e));return isNaN(s)?null:s}if(i.includes("boolean")){if(typeof e=="boolean")return e?1:0;if(typeof e=="string"){const s=e.toLowerCase();return s==="true"||s==="1"||s==="yes"?1:0}return e?1:0}if(i.includes("json")){if(typeof e=="object")return JSON.stringify(e);if(typeof e=="string")try{return JSON.parse(e),e}catch(s){throw new Error(`Invalid JSON format for column type '${t}'`)}return JSON.stringify(e)}if(i.includes("timestamp")||i.includes("datetime")){if(e instanceof Date)return e.toISOString();if(typeof e=="string"||typeof e=="number"){const s=new Date(e);return isNaN(s.getTime())?e:s.toISOString()}return String(e)}return String(e)}catch(s){throw new Error(`Cannot convert value '${e}' to column type '${t}'`)}}async insertRow(e,t){const i=Object.keys(t),s=Object.values(t),a=i.map(()=>"?").join(", "),n=`INSERT INTO ${e} (${i.join(", ")}) VALUES (${a})`;await this.execute(n,s)}async insertOrUpdate(e,t,i){try{await this.insertRow(e,t)}catch(s){if(this.isConflictError(s))await this.updateRowByColumns(e,t,i);else throw s}}async updateRowByColumns(e,t,i){const s=Object.keys(t).filter(u=>!i.includes(u)),a=i;if(s.length===0)return;const n=s.map(u=>`${u} = ?`).join(", "),r=a.map(u=>`${u} = ?`).join(" AND "),o=s.map(u=>t[u]),l=a.map(u=>t[u]),c=[...o,...l],f=`UPDATE ${e} SET ${n} WHERE ${r}`;await this.execute(f,c)}isConflictError(e){return e.code==="SQLITE_CONSTRAINT_UNIQUE"||e.code==="SQLITE_CONSTRAINT_PRIMARYKEY"||e.message&&e.message.includes("UNIQUE constraint failed")}async getDatabaseInfo(){const e=await this.execute("SELECT name FROM sqlite_master WHERE type='table'"),t=await this.getSchemaVersion();return{name:this.dbPath,tables:e.rows.map(i=>i.name),isConnected:this.isConnected,version:t}}async getTableInfo(e){return(await this.execute(`PRAGMA table_info(${e})`)).rows}async dropTable(e){const t=`DROP TABLE IF EXISTS ${e}`;await this.execute(t)}isConnectionOpen(){return this.isConnected&&!!this.connection}async ensureConnected(){this.isConnectionOpen()||await this.connect()}async execute(e,t=[]){return this.ensureConnected(),await this.connection.execute(e,t)}async getRst(e,t=[]){return(await this.execute(e,t)).rows[0]||{}}async getRsts(e,t=[]){return(await this.execute(e,t)).rows}}class g{static registerAdapter(e){this.adapters.push(e)}static getEnvironmentInfo(){return typeof navigator!="undefined"&&navigator.product==="ReactNative"?"React Native":typeof globalThis.Bun!="undefined"?"Bun":typeof globalThis.Deno!="undefined"?"Deno":typeof window!="undefined"?"Browser":typeof process!="undefined"?"Node.js":"Unknown"}static detectBestAdapter(){for(const e of this.adapters)if(e.isSupported())return e;throw new Error("No supported SQLite adapter found")}static async validateSchemaVersion(e,t){try{const i=await e.getDatabaseInfo();if(i.version!==t.version)throw new Error(`Schema version mismatch: database (${i.version}) vs config (${t.version})`)}catch(i){throw new Error(`Error validating schema version for ${t.database_name}: ${i.message}`)}}static validateSchema(e){if(!e)throw new Error("Schema configuration is null or undefined.");if(typeof e.database_name!="string"||e.database_name.trim()==="")throw new Error("Invalid or missing 'database_name' in schema. This is required to name the database file.");if(typeof e.schemas!="object"||e.schemas===null||Object.keys(e.schemas).length===0)throw new Error("Invalid or missing 'schemas' object in schema. At least one table definition is required.");return!0}static createDAO(e,t){var i,s;let a;return t!=null&&t.adapter?a=t.adapter:a=this.detectBestAdapter(),new O(a,e,{createIfNotExists:(i=t==null?void 0:t.createIfNotExists)!==null&&i!==void 0?i:!1,forceRecreate:(s=t==null?void 0:t.forceRecreate)!==null&&s!==void 0?s:!1})}static async openExisting(e,t={}){const i=e.endsWith(".db")?e:`${e}.db`,s=this.createDAO(i,t);try{return await s.connect(),await s.execute("PRAGMA integrity_check"),s}catch(a){throw await s.close(),new Error(`Error opening database '${i}': ${a.message}`)}}static async createOrOpenInternal(e,t=!1,i=!1){let s;if(e.config)s=e.config;else if(e.configAsset)s=e.configAsset;else throw new Error("Either 'config', 'configAsset', or 'configPath' must be provided to the factory.");this.validateSchema(s);const a=s.database_name.endsWith(".db")?s.database_name:`${s.database_name}.db`,n=this.createDAO(a,{adapter:e.adapter,createIfNotExists:t,forceRecreate:i});try{await n.connect(),await n.initializeFromSchema(s);try{await this.validateSchemaVersion(n,s)}catch(r){throw await n.close(),new Error(`Schema mismatch in existing database. Use forceRecreate=true to recreate with updated schema. Error: ${r.message}`)}return n}catch(r){throw n.isConnectionOpen()&&await n.close(),r}}static async create(e){return this.createOrOpenInternal(e,!0,!0)}static async createOrOpen(e,t=!1){return this.createOrOpenInternal(e,t)}static async createFromAsset(e,t={}){try{return await this.create(Object.assign(Object.assign({},t),{configAsset:e}))}catch(i){throw new Error(`Error creating database from asset: ${i.message}`)}}static async createFromConfig(e,t={}){try{return await this.create(Object.assign(Object.assign({},t),{config:e}))}catch(i){throw new Error(`Error creating database from config: ${i.message}`)}}}g.adapters=[];class h{static getMaxConnections(){return this.maxConnections}static setMaxConnections(e){if(e<=0)throw new Error("Maximum connections must be a positive number");const t=Object.keys(this.connections).length;if(t>e)throw new Error(`Cannot set maximum connections to ${e}. Current active connections (${t}) exceed the new limit. Please close some connections first.`);this.maxConnections=e}static setSchemaManager(e){this.schemaManager=e}static registerSchema(e,t){this.schemaConfigurations[e]=t}static registerSchemas(e){Object.entries(e).forEach(([t,i])=>{this.registerSchema(t,i)})}static getSchema(e){if(this.schemaConfigurations[e])return this.schemaConfigurations[e];if(this.schemaManager)return this.schemaManager.getSchema(e)}static getAvailableSchemas(){var e;const t=Object.keys(this.schemaConfigurations),i=((e=this.schemaManager)===null||e===void 0?void 0:e.getAllSchemaKeys())||[];return[...new Set([...t,...i])]}static registerRole(e){this.roleRegistry[e.roleName]=e}static registerRoles(e){e.forEach(t=>this.registerRole(t))}static getRegisteredRoles(){return Object.assign({},this.roleRegistry)}static getRoleDatabases(e){const t=this.roleRegistry[e];if(!t)throw new Error(`Role '${e}' is not registered.`);return[...t.requiredDatabases,...t.optionalDatabases||[]]}static getCurrentUserDatabases(){const e=new Set;e.add("core");for(const t of this.currentUserRoles){const i=this.roleRegistry[t];i&&(i.requiredDatabases.forEach(s=>e.add(s)),i.optionalDatabases&&i.optionalDatabases.forEach(s=>e.add(s)))}return Array.from(e)}static async initializeCoreConnection(){if(!this.connections.core)try{const e=this.getSchema("core");if(!e)throw new Error("Core database schema not found.");const t=await g.createOrOpen({config:e},!1);await t.execute("PRAGMA integrity_check"),this.connections.core=t}catch(e){throw new Error(`Error initializing core database: ${e.message}`)}}static async setCurrentUserRoles(e,t){for(const s of e)if(!this.roleRegistry[s])throw new Error(`Role '${s}' is not registered. Please register it first.`);const i=[...this.currentUserRoles];this.currentUserRoles=e,this.currentRole=t||e[0]||null,await this.initializeUserRoleConnections(),await this.cleanupUnusedConnections(i)}static getCurrentUserRoles(){return[...this.currentUserRoles]}static getCurrentRole(){return this.currentRole}static async initializeUserRoleConnections(){const e=this.getCurrentUserDatabases(),t=[],i=e.map(async s=>{if(!this.connections[s])try{const a=this.getSchema(s);if(!a)throw new Error(`Database key '${s}' not found in schema configurations.`);const n=await g.createOrOpen({config:a},!1);await n.execute("PRAGMA integrity_check"),this.connections[s]=n}catch(a){const n=a instanceof Error?a:new Error(String(a));this.currentUserRoles.some(r=>{const o=this.roleRegistry[r];return o&&o.requiredDatabases.includes(s)})&&t.push({key:s,error:n})}});if(await Promise.all(i),t.length>0){const s=t.map(a=>` - ${a.key}: ${a.error.message}`).join(`
6
6
  `);throw new Error(`Failed to initialize required databases for user roles:
7
- ${s}`)}}static async cleanupUnusedConnections(t){const e=new Set;e.add("core");for(const a of t){const r=this.roleRegistry[a];r&&(r.requiredDatabases.forEach(n=>e.add(n)),r.optionalDatabases&&r.optionalDatabases.forEach(n=>e.add(n)))}const i=new Set(this.getCurrentUserDatabases()),s=Array.from(e).filter(a=>!i.has(a));if(s.length>0){for(const a of s)if(this.connections[a])try{await this.connections[a].close(),delete this.connections[a]}catch(r){}}}static hasAccessToDatabase(t){return this.getSchema(t)!==void 0}static get(t){if(!this.hasAccessToDatabase(t))throw new Error(`Access denied: Database '${t}' is not accessible.`);const e=this.connections[t];if(!e)throw new Error(`Database '${t}' is not connected. Please ensure it's initialized.`);return e}static onDatabaseReconnect(t,e){this.eventListeners.has(t)||this.eventListeners.set(t,[]),this.eventListeners.get(t).push(e)}static offDatabaseReconnect(t,e){const i=this.eventListeners.get(t);if(i){const s=i.indexOf(e);s>-1&&i.splice(s,1)}}static notifyDatabaseReconnect(t,e){const i=this.eventListeners.get(t);i&&i.forEach(s=>{try{s(e)}catch(a){}})}static async closeAllConnections(){if(!this.isClosingConnections){this.isClosingConnections=!0;try{Object.keys(this.connections).forEach(e=>this.activeDatabases.add(e));const t=Object.entries(this.connections).map(async([e,i])=>{try{await i.close()}catch(s){}});await Promise.all(t),this.connections={}}finally{this.isClosingConnections=!1}}}static async reopenConnections(){await this.initializeCoreConnection(),this.currentUserRoles.length>0&&await this.initializeUserRoleConnections();const t=Array.from(this.activeDatabases);if(t.length>0)for(const e of t)if(this.connections[e])this.connections[e]&&this.notifyDatabaseReconnect(e,this.connections[e]);else{const i=this.getSchema(e);if(i)try{const s=await g.createOrOpen({config:i},!1);await s.connect(),this.connections[e]=s,this.notifyDatabaseReconnect(e,s)}catch(s){}}}static async ensureDatabaseConnection(t){if(this.activeDatabases.add(t),!this.hasAccessToDatabase(t))throw new Error(`Access denied: Database '${t}' is not accessible.`);if(this.connections[t])try{if(this.connections[t].isConnectionOpen())return this.connections[t];try{await this.connections[t].close().catch(()=>{})}catch(e){}delete this.connections[t]}catch(e){delete this.connections[t]}return await this.getLazyLoading(t)}static getConnections(){return Object.assign({},this.connections)}static async openAllExisting(t){const e=[];for(const i of t)try{const s=this.getSchema(i);if(!s)throw new Error(`Invalid database key: ${i}. Schema not found.`);const a=await g.createOrOpen({config:s},!1);await a.execute("PRAGMA integrity_check"),this.connections[i]=a}catch(s){const a=s instanceof Error?s:new Error(String(s));e.push({key:i,error:a})}if(e.length>0){const i=e.map(s=>` - ${s.key}: ${s.error.message}`).join(`
7
+ ${s}`)}}static async cleanupUnusedConnections(e){const t=new Set;t.add("core");for(const a of e){const n=this.roleRegistry[a];n&&(n.requiredDatabases.forEach(r=>t.add(r)),n.optionalDatabases&&n.optionalDatabases.forEach(r=>t.add(r)))}const i=new Set(this.getCurrentUserDatabases()),s=Array.from(t).filter(a=>!i.has(a));if(s.length>0){for(const a of s)if(this.connections[a])try{await this.connections[a].close(),delete this.connections[a]}catch(n){}}}static hasAccessToDatabase(e){return this.getSchema(e)!==void 0}static get(e){if(!this.hasAccessToDatabase(e))throw new Error(`Access denied: Database '${e}' is not accessible.`);const t=this.connections[e];if(!t)throw new Error(`Database '${e}' is not connected. Please ensure it's initialized.`);return t}static onDatabaseReconnect(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t)}static offDatabaseReconnect(e,t){const i=this.eventListeners.get(e);if(i){const s=i.indexOf(t);s>-1&&i.splice(s,1)}}static notifyDatabaseReconnect(e,t){const i=this.eventListeners.get(e);i&&i.forEach(s=>{try{s(t)}catch(a){}})}static async closeAllConnections(){if(!this.isClosingConnections){this.isClosingConnections=!0;try{Object.keys(this.connections).forEach(t=>this.activeDatabases.add(t));const e=Object.entries(this.connections).map(async([t,i])=>{try{await i.close()}catch(s){}});await Promise.all(e),this.connections={}}finally{this.isClosingConnections=!1}}}static async reopenConnections(){await this.initializeCoreConnection(),this.currentUserRoles.length>0&&await this.initializeUserRoleConnections();const e=Array.from(this.activeDatabases);if(e.length>0)for(const t of e)if(this.connections[t])this.connections[t]&&this.notifyDatabaseReconnect(t,this.connections[t]);else{const i=this.getSchema(t);if(i)try{const s=await g.createOrOpen({config:i},!1);await s.connect(),this.connections[t]=s,this.notifyDatabaseReconnect(t,s)}catch(s){}}}static async ensureDatabaseConnection(e){if(this.activeDatabases.add(e),!this.hasAccessToDatabase(e))throw new Error(`Access denied: Database '${e}' is not accessible.`);if(this.connections[e])try{if(this.connections[e].isConnectionOpen())return this.connections[e];try{await this.connections[e].close().catch(()=>{})}catch(t){}delete this.connections[e]}catch(t){delete this.connections[e]}return await this.getLazyLoading(e)}static getConnections(){return Object.assign({},this.connections)}static async openAllExisting(e){const t=[];for(const i of e)try{const s=this.getSchema(i);if(!s)throw new Error(`Invalid database key: ${i}. Schema not found.`);const a=await g.createOrOpen({config:s},!1);await a.execute("PRAGMA integrity_check"),this.connections[i]=a}catch(s){const a=s instanceof Error?s:new Error(String(s));t.push({key:i,error:a})}if(t.length>0){const i=t.map(s=>` - ${s.key}: ${s.error.message}`).join(`
8
8
  `);throw new Error(`Failed to open one or more databases:
9
- ${i}`)}return this.isInitialized=!0,!0}static async initLazySchema(t){const e=t.filter(n=>!this.getSchema(n));if(e.length>0)throw new Error(`Invalid database keys: ${e.join(", ")}. Schemas not found.`);const i=t.filter(n=>!this.connections[n]).length,s=Object.keys(this.connections).length;if(s+i>this.maxConnections)throw new Error(`Cannot initialize ${i} new connections. Would exceed maximum of ${this.maxConnections} connections. Current: ${s}`);const a=[],r=t.map(async n=>{if(!this.connections[n])try{const o=this.getSchema(n),l=await g.createOrOpen({config:o},!1);await l.execute("PRAGMA integrity_check"),this.connections[n]=l}catch(o){const l=o instanceof Error?o:new Error(String(o));a.push({key:n,error:l})}});if(await Promise.all(r),a.length>0){const n=a.map(o=>` - ${o.key}: ${o.error.message}`).join(`
9
+ ${i}`)}return this.isInitialized=!0,!0}static async initLazySchema(e){const t=e.filter(r=>!this.getSchema(r));if(t.length>0)throw new Error(`Invalid database keys: ${t.join(", ")}. Schemas not found.`);const i=e.filter(r=>!this.connections[r]).length,s=Object.keys(this.connections).length;if(s+i>this.maxConnections)throw new Error(`Cannot initialize ${i} new connections. Would exceed maximum of ${this.maxConnections} connections. Current: ${s}`);const a=[],n=e.map(async r=>{if(!this.connections[r])try{const o=this.getSchema(r),l=await g.createOrOpen({config:o},!1);await l.execute("PRAGMA integrity_check"),this.connections[r]=l}catch(o){const l=o instanceof Error?o:new Error(String(o));a.push({key:r,error:l})}});if(await Promise.all(n),a.length>0){const r=a.map(o=>` - ${o.key}: ${o.error.message}`).join(`
10
10
  `);throw new Error(`Failed to initialize one or more databases:
11
- ${n}`)}return Object.keys(this.connections).length>0&&(this.isInitialized=!0),!0}static async initializeAll(){if(this.isInitialized)return;const t=this.getAvailableSchemas(),e=[],i=t.map(async s=>{try{const a=this.getSchema(s),r=await g.createOrOpen({config:a},!1);this.connections[s]=r}catch(a){const r=a instanceof Error?a:new Error(String(a));e.push({key:s,error:r})}});if(await Promise.all(i),e.length>0){this.isInitialized=!1;const s=e.map(a=>` - ${a.key}: ${a.error.message}`).join(`
11
+ ${r}`)}return Object.keys(this.connections).length>0&&(this.isInitialized=!0),!0}static async initializeAll(){if(this.isInitialized)return;const e=this.getAvailableSchemas(),t=[],i=e.map(async s=>{try{const a=this.getSchema(s),n=await g.createOrOpen({config:a},!1);this.connections[s]=n}catch(a){const n=a instanceof Error?a:new Error(String(a));t.push({key:s,error:n})}});if(await Promise.all(i),t.length>0){this.isInitialized=!1;const s=t.map(a=>` - ${a.key}: ${a.error.message}`).join(`
12
12
  `);throw new Error(`Failed to initialize one or more databases:
13
- ${s}`)}this.isInitialized=!0}static async getLazyLoading(t){if(this.activeDatabases.add(t),!this.hasAccessToDatabase(t))throw new Error(`Access denied: Database '${t}' is not accessible.`);if(!this.connections[t]){const e=this.getSchema(t);if(!e)throw new Error(`Invalid database key: ${t}. Schema not found.`);if(Object.keys(this.connections).length>=this.maxConnections)throw new Error("Maximum number of database connections reached");const i=await g.createOrOpen({config:e},!1);await i.connect(),this.connections[t]=i}return this.isInitialized=!0,this.connections[t]}static async executeCrossSchemaTransaction(t,e){for(const s of t)if(!this.hasAccessToDatabase(s))throw new Error(`Access denied: Database '${s}' is not accessible.`);const i=t.reduce((s,a)=>(s[a]=this.get(a),s),{});try{await Promise.all(Object.values(i).map(s=>s.beginTransaction())),await e(i),await Promise.all(Object.values(i).map(s=>s.commitTransaction()))}catch(s){throw await Promise.all(Object.values(i).map(a=>a.rollbackTransaction())),s}}static async importDataToTable(t,e,i,s={}){if(!this.hasAccessToDatabase(t))throw new Error(`Access denied: Database '${t}' is not accessible.`);const a=this.get(t);try{return await a.importData(Object.assign({tableName:e,data:i},s))}catch(r){throw r}}static async importDataWithMapping(t,e,i,s,a={}){if(!this.hasAccessToDatabase(t))throw new Error(`Access denied: Database '${t}' is not accessible.`);const r=this.get(t);try{return await r.importDataWithMapping(e,i,s,a)}catch(n){throw n}}static async bulkImport(t){const e=Date.now(),i={totalDatabases:t.length,successDatabases:0,results:{},errors:{},executionTime:0};for(const s of t){const a=`${s.databaseKey}.${s.tableName}`;try{if(!this.hasAccessToDatabase(s.databaseKey))throw new Error(`Access denied: Database '${s.databaseKey}' is not accessible.`);const r=this.get(s.databaseKey);let n;s.columnMappings?n=await r.importDataWithMapping(s.tableName,s.data,s.columnMappings,s.options):n=await r.importData(Object.assign({tableName:s.tableName,data:s.data},s.options)),i.results[a]=n,i.successDatabases++}catch(r){const n=r instanceof Error?r:new Error(String(r));i.errors[a]=n}}return i.executionTime=Date.now()-e,i}static async importFromCSV(t,e,i,s={}){if(!this.hasAccessToDatabase(t))throw new Error(`Access denied: Database '${t}' is not accessible.`);const a=this.get(t);try{return await a.importFromCSV(e,i,s)}catch(r){throw r}}static getConnectionCount(){return Object.keys(this.connections).length}static listConnections(){return Object.keys(this.connections)}static async closeConnection(t){const e=this.connections[t];e&&(await e.disconnect(),delete this.connections[t])}static async closeAll(){await this.closeAllConnections(),this.currentUserRoles=[],this.currentRole=null,this.isInitialized=!1,this.activeDatabases.clear(),this.eventListeners.clear(),this.isClosingConnections=!1}static async logout(){const t=Object.keys(this.connections).filter(e=>e!=="core");for(const e of t)try{await this.connections[e].close(),delete this.connections[e]}catch(i){}this.currentUserRoles=[],this.currentRole=null}}h.maxConnections=10,h.connections={},h.isInitialized=!1,h.roleRegistry={},h.currentRole=null,h.currentUserRoles=[],h.activeDatabases=new Set,h.isClosingConnections=!1,h.schemaConfigurations={},h.schemaManager=null,h.eventListeners=new Map;class C{constructor(t,e){this.dao=null,this.isOpened=!1,this.isInitialized=!1,this.errorHandlers=new Map,this.eventListeners=new Map,this.primaryKeyFields=["id"],this.cache=new Map,this.schemaName=t,this.tableName=e||t,this.reconnectHandler=i=>{this.dao=i,this._emit("daoReconnected",{schemaName:this.schemaName})},h.onDatabaseReconnect(t,this.reconnectHandler),this.bindMethods()}bindMethods(){Object.getOwnPropertyNames(Object.getPrototypeOf(this)).forEach(t=>{typeof this[t]=="function"&&t!=="constructor"&&(this[t]=this[t].bind(this))})}setPrimaryKeyFields(t){return this.primaryKeyFields=t,this}async init(){try{if(this.isInitialized)return this;if(this.dao=await h.getLazyLoading(this.schemaName),!this.dao)throw new Error(`Failed to initialize DAO for schema: ${this.schemaName}`);return this.dao.isConnectionOpen()||await this.dao.connect(),this.isOpened=!0,this.isInitialized=!0,this._emit("initialized",{schemaName:this.schemaName}),this}catch(t){throw this._handleError("INIT_ERROR",t),t}}async create(t){await this._ensureInitialized(),await this.ensureValidConnection();try{this._validateData(t);const e=this.buildDataTable(t),i=await this.dao.insert(e);return this._emit("dataCreated",{operation:"create",data:i}),i}catch(e){throw this._handleError("CREATE_ERROR",e),e}}async update(t,e){await this._ensureInitialized();try{if(!t)throw new Error("ID is required for update");this._validateData(e);const i=Object.assign(Object.assign({},e),{[this.primaryKeyFields[0]]:t}),s=this.buildDataTable(i);await this.dao.update(s);const a=await this.findById(t);return this._emit("dataUpdated",{operation:"update",id:t,data:a}),a}catch(i){throw this._handleError("UPDATE_ERROR",i),i}}async delete(t){await this._ensureInitialized();try{if(!t)throw new Error("ID is required for delete");const e={name:this.tableName,cols:[],wheres:[{name:this.primaryKeyFields[0],value:t}]},i=(await this.dao.delete(e)).rowsAffected>0;return i&&this._emit("dataDeleted",{operation:"delete",id:t}),i}catch(e){throw this._handleError("DELETE_ERROR",e),e}}async findById(t){await this._ensureInitialized();try{if(!t)throw new Error("ID is required");const e={[this.primaryKeyFields[0]]:t},i=this.buildSelectTable(e),s=await this.dao.select(i),a=Object.keys(s).length>0?s:null;return this._emit("dataFetched",{operation:"findById",id:t}),a}catch(e){throw this._handleError("FIND_BY_ID_ERROR",e),e}}async findFirst(t={}){await this._ensureInitialized();try{const e=this.buildSelectTable(t),i=await this.dao.select(e),s=Object.keys(i).length>0?i:null;return this._emit("dataFetched",{operation:"findFirst"}),s}catch(e){throw this._handleError("FIND_FIRST_ERROR",e),e}}async findAll(t={},e={}){await this._ensureInitialized();try{const i=[...this.buildWhereFromObject(t),...e.where||[]],s={name:this.tableName,cols:e.columns?e.columns.map(r=>({name:r})):[],wheres:i,orderbys:e.orderBy,limitOffset:{limit:e.limit,offset:e.offset}},a=await this.dao.selectAll(s);return this._emit("dataFetched",{operation:"findAll",count:a.length}),a}catch(i){throw this._handleError("FIND_ALL_ERROR",i),i}}async count(t){await this._ensureInitialized();try{let e=[];Array.isArray(t)?e=t:t&&typeof t=="object"&&(e=this.buildWhereFromObject(t));const i={name:this.tableName,cols:[{name:"COUNT(*) as count"}],wheres:e};return(await this.dao.select(i)).count||0}catch(e){throw this._handleError("COUNT_ERROR",e),e}}async exists(t){return await this.findById(t)!==null}async truncate(){await this._ensureInitialized();try{await this.dao.execute(`DELETE FROM ${this.tableName}`),await this.dao.execute(`DELETE FROM sqlite_sequence WHERE name='${this.tableName}'`),this._emit("tableTruncated",{tableName:this.tableName})}catch(t){throw this._handleError("TRUNCATE_ERROR",t),t}}async bulkInsert(t){await this._ensureInitialized();try{if(!Array.isArray(t)||t.length===0)throw new Error("Items must be a non-empty array");const e=await this.dao.importData({tableName:this.tableName,data:t,batchSize:1e3,skipErrors:!1,validateData:!0});return this._emit("dataBulkCreated",{operation:"bulkInsert",count:e.successRows}),e}catch(e){throw this._handleError("BULK_INSERT_ERROR",e),e}}async bulkCreate(t){await this._ensureInitialized();try{if(!Array.isArray(t)||t.length===0)throw new Error("Data must be a non-empty array");const e=[];return await this.executeTransaction(async()=>{for(const i of t){this._validateData(i);const s=this.buildDataTable(i);await this.dao.insert(s),e.push(i)}}),this._emit("dataBulkCreated",{operation:"bulkCreate",count:e.length}),e}catch(e){throw this._handleError("BULK_CREATE_ERROR",e),e}}async executeTransaction(t){await this._ensureInitialized();try{await this.dao.beginTransaction();const e=await t();return await this.dao.commitTransaction(),this._emit("transactionCompleted",{operation:"transaction"}),e}catch(e){try{await this.dao.rollbackTransaction()}catch(i){this._handleError("ROLLBACK_ERROR",i)}throw this._handleError("TRANSACTION_ERROR",e),e}}async importFromCSV(t,e={}){await this._ensureInitialized();try{const i=await this.dao.importFromCSV(this.tableName,t,e);return this._emit("dataImported",{operation:"importFromCSV",result:i}),i}catch(i){throw this._handleError("IMPORT_CSV_ERROR",i),i}}async importDataWithMapping(t,e,i={}){await this._ensureInitialized();try{const s=await this.dao.importDataWithMapping(this.tableName,t,e,i);return this._emit("dataImported",{operation:"importWithMapping",result:s}),s}catch(s){throw this._handleError("IMPORT_MAPPING_ERROR",s),s}}buildSelectTable(t={},e={}){const i={name:this.tableName,cols:[],wheres:[],orderbys:e.orderBy||[],limitOffset:{}};return e.columns&&e.columns.length>0&&(i.cols=e.columns.map(s=>({name:s}))),t&&Object.keys(t).length>0&&(i.wheres=Object.entries(t).map(([s,a])=>({name:s,value:a,operator:"="}))),e.limit!==void 0&&(i.limitOffset.limit=e.limit),e.offset!==void 0&&(i.limitOffset.offset=e.offset),i}buildDataTable(t){return this.dao.convertJsonToQueryTable(this.tableName,t,this.primaryKeyFields)}buildWhereFromObject(t){return Object.entries(t).filter(([e,i])=>i!==void 0).map(([e,i])=>({name:e,value:i}))}on(t,e){return this.eventListeners.has(t)||this.eventListeners.set(t,[]),this.eventListeners.get(t).push(e),this}off(t,e){const i=this.eventListeners.get(t);if(i){const s=i.indexOf(e);s>-1&&i.splice(s,1)}return this}_emit(t,e){const i=this.eventListeners.get(t);i&&i.forEach(s=>{try{s(e)}catch(a){}})}setErrorHandler(t,e){return this.errorHandlers.set(t,e),this}_handleError(t,e){const i=this.errorHandlers.get(t);if(i)try{i(e)}catch(s){}this._emit("error",{errorType:t,error:e})}_validateData(t){if(!t||typeof t!="object")throw new Error("Data must be a valid object")}async _ensureInitialized(){this.isInitialized||await this.init()}async ensureValidConnection(){var t;try{!((t=this.dao)===null||t===void 0)&&t.isConnectionOpen()||(this.dao=await h.ensureDatabaseConnection(this.schemaName))}catch(e){this.dao=await h.ensureDatabaseConnection(this.schemaName)}}async getDatabaseInfo(){return await this._ensureInitialized(),await this.dao.getDatabaseInfo()}async getTableInfo(){return await this._ensureInitialized(),await this.dao.getTableInfo(this.tableName)}getStatus(){return{schemaName:this.schemaName,isOpened:this.isOpened,isInitialized:this.isInitialized,hasDao:!!this.dao}}async healthCheck(){try{await this._ensureInitialized();const t=await this.count();return{healthy:!0,schemaName:this.schemaName,recordCount:t,timestamp:new Date().toISOString()}}catch(t){return{healthy:!1,schemaName:this.schemaName,error:t.message,timestamp:new Date().toISOString()}}}async close(){try{return this.dao&&await this.dao.close(),this.isOpened=!1,this.isInitialized=!1,this.eventListeners.clear(),this.errorHandlers.clear(),this.cache.clear(),this._emit("closed",{schemaName:this.schemaName}),!0}catch(t){throw this._handleError("CLOSE_ERROR",t),t}}destroy(){h.offDatabaseReconnect(this.schemaName,this.reconnectHandler),this.eventListeners.clear(),this.errorHandlers.clear(),this.cache.clear()}async getAll(t={},e={}){return this.findAll(t,e)}async getById(t){return this.findById(t)}async getFirst(t={}){return this.findFirst(t)}}class E{constructor(t){this.tableName="",this.selectFields=["*"],this.joinClauses=[],this.whereConditions=[],this.groupByFields=[],this.havingConditions=[],this.orderByFields=[],this.limitValue=null,this.offsetValue=null,this.params=[],this.unionQueries=[],this.subQueries=[],this.cteQueries=new Map,this.dao=null,this.dao=t||null}static table(t,e){const i=new E(e);return i.tableName=t,i}static from(t,e){return E.table(t,e)}select(t){return this.selectFields=Array.isArray(t)?t:[t],this}selectRaw(t){return this.selectFields=[t],this}selectDistinct(t){const e=Array.isArray(t)?t.join(", "):t;return this.selectFields=[`DISTINCT ${e}`],this}join(t,e,i="INNER"){return this.joinClauses.push({type:i,table:t,condition:e}),this}innerJoin(t,e){return this.join(t,e,"INNER")}leftJoin(t,e){return this.join(t,e,"LEFT")}rightJoin(t,e){return this.join(t,e,"RIGHT")}fullOuterJoin(t,e){return this.join(t,e,"FULL OUTER")}where(t,e,i){if(typeof t=="object")return Object.entries(t).forEach(([r,n])=>{this.whereConditions.push({field:r,operator:"=",value:n})}),this;let s="=",a=e;return arguments.length===3&&(s=e,a=i),this.whereConditions.push({field:t,operator:s,value:a}),this}whereEquals(t,e){return this.where(t,"=",e)}whereNot(t,e){return this.where(t,"!=",e)}whereLike(t,e){return this.where(t,"LIKE",e)}whereNotLike(t,e){return this.where(t,"NOT LIKE",e)}whereIn(t,e){return this.whereConditions.push({field:t,operator:"IN",value:e}),this}whereNotIn(t,e){return this.whereConditions.push({field:t,operator:"NOT IN",value:e}),this}whereBetween(t,e,i){return this.whereConditions.push({field:t,operator:"BETWEEN",value:[e,i]}),this}whereNotBetween(t,e,i){return this.whereConditions.push({field:t,operator:"NOT BETWEEN",value:[e,i]}),this}whereNull(t){return this.whereConditions.push({field:t,operator:"IS NULL",value:null}),this}whereNotNull(t){return this.whereConditions.push({field:t,operator:"IS NOT NULL",value:null}),this}whereExists(t){return this.whereConditions.push({field:"",operator:"EXISTS",value:t}),this}whereNotExists(t){return this.whereConditions.push({field:"",operator:"NOT EXISTS",value:t}),this}orWhere(t,e,i){return this.where(t,e,i)}groupBy(t){return this.groupByFields=Array.isArray(t)?t:[t],this}having(t,e,i){let s="=",a=e;return arguments.length===3&&(s=e,a=i),this.havingConditions.push({field:t,operator:s,value:a}),this}havingCount(t,e,i){return this.having(`COUNT(${t})`,e,i)}orderBy(t,e="ASC"){return this.orderByFields.push(`${t} ${e}`),this}orderByDesc(t){return this.orderBy(t,"DESC")}orderByRaw(t){return this.orderByFields.push(t),this}latest(t="created_at"){return this.orderByDesc(t)}oldest(t="created_at"){return this.orderBy(t,"ASC")}limit(t){return this.limitValue=t,this}offset(t){return this.offsetValue=t,this}skip(t){return this.offset(t)}take(t){return this.limit(t)}firstRow(){return this.limit(1)}paginate(t,e){return this.limitValue=e,this.offsetValue=(t-1)*e,this}union(t){return this.unionQueries.push(t),this}unionAll(t){return this.union(t)}with(t,e){return this.cteQueries.set(t,e),this}whereSubQuery(t,e,i){return this.subQueries.push({query:i,alias:""}),this.whereConditions.push({field:t,operator:e,value:i}),this}count(t="*"){return this.selectFields=[`COUNT(${t}) as count`],this}sum(t){return this.selectFields=[`SUM(${t}) as sum`],this}avg(t){return this.selectFields=[`AVG(${t}) as avg`],this}max(t){return this.selectFields=[`MAX(${t}) as max`],this}min(t){return this.selectFields=[`MIN(${t}) as min`],this}toSQL(){let t="";const e=[];if(this.cteQueries.size>0){const i=[];this.cteQueries.forEach((s,a)=>{const{sql:r,params:n}=s.toSQL();i.push(`${a} AS (${r})`),e.push(...n)}),t+=`WITH ${i.join(", ")} `}if(t+=`SELECT ${this.selectFields.join(", ")} FROM ${this.tableName}`,this.joinClauses.length>0&&this.joinClauses.forEach(i=>{t+=` ${i.type} JOIN ${i.table} ON ${i.condition}`}),this.whereConditions.length>0){const i=[];this.whereConditions.forEach(s=>{const{clause:a,conditionParams:r}=this.buildCondition(s);i.push(a),e.push(...r)}),t+=` WHERE ${i.join(" AND ")}`}if(this.groupByFields.length>0&&(t+=` GROUP BY ${this.groupByFields.join(", ")}`),this.havingConditions.length>0){const i=[];this.havingConditions.forEach(s=>{const{clause:a,conditionParams:r}=this.buildCondition(s);i.push(a),e.push(...r)}),t+=` HAVING ${i.join(" AND ")}`}return this.orderByFields.length>0&&(t+=` ORDER BY ${this.orderByFields.join(", ")}`),this.limitValue!==null&&(t+=` LIMIT ${this.limitValue}`),this.offsetValue!==null&&(t+=` OFFSET ${this.offsetValue}`),this.unionQueries.length>0&&this.unionQueries.forEach(i=>{const{sql:s,params:a}=i.toSQL();t+=` UNION ${s}`,e.push(...a)}),{sql:t,params:e}}buildCondition(t){const{field:e,operator:i,value:s}=t,a=[];switch(i.toUpperCase()){case"IN":case"NOT IN":const r=s.map(()=>"?").join(", ");return a.push(...s),{clause:`${e} ${i} (${r})`,conditionParams:a};case"BETWEEN":case"NOT BETWEEN":return a.push(s[0],s[1]),{clause:`${e} ${i} ? AND ?`,conditionParams:a};case"IS NULL":case"IS NOT NULL":return{clause:`${e} ${i}`,conditionParams:[]};case"EXISTS":case"NOT EXISTS":const{sql:n,params:o}=s.toSQL();return a.push(...o),{clause:`${i} (${n})`,conditionParams:a};default:if(s instanceof E){const{sql:l,params:c}=s.toSQL();return a.push(...c),{clause:`${e} ${i} (${l})`,conditionParams:a}}return a.push(s),{clause:`${e} ${i} ?`,conditionParams:a}}}async get(){if(!this.dao)throw new Error("DAO instance required for query execution");const{sql:t,params:e}=this.toSQL();return(await this.dao.execute(t,e)).rows}async first(){this.limit(1);const t=await this.get();return t.length>0?t[0]:null}async pluck(t){return this.select(t),(await this.get()).map(e=>e[t])}async exists(){return this.select("1").limit(1),(await this.get()).length>0}async countResult(){this.count();const t=await this.first();return t?t.count:0}static insert(t,e){const i=Object.keys(e),s=Object.values(e),a=s.map(()=>"?").join(", ");return{sql:`INSERT INTO ${t} (${i.join(", ")}) VALUES (${a})`,params:s}}static insertMany(t,e){if(e.length===0)throw new Error("Data array cannot be empty");const i=Object.keys(e[0]),s=i.map(()=>"?").join(", "),a=e.map(()=>`(${s})`).join(", "),r=e.flatMap(n=>Object.values(n));return{sql:`INSERT INTO ${t} (${i.join(", ")}) VALUES ${a}`,params:r}}static update(t,e,i,s=[]){const a=Object.keys(e).map(n=>`${n} = ?`).join(", "),r=[...Object.values(e),...s];return{sql:`UPDATE ${t} SET ${a} WHERE ${i}`,params:r}}static delete(t,e,i=[]){return{sql:`DELETE FROM ${t} WHERE ${e}`,params:i}}static upsert(t,e,i){const s=Object.keys(e),a=Object.values(e),r=a.map(()=>"?").join(", "),n=s.filter(c=>!i.includes(c)),o=n.length>0?n.map(c=>`${c} = excluded.${c}`).join(", "):"";let l=`INSERT INTO ${t} (${s.join(", ")}) VALUES (${r})`;return n.length>0?l+=` ON CONFLICT(${i.join(", ")}) DO UPDATE SET ${o}`:l+=` ON CONFLICT(${i.join(", ")}) DO NOTHING`,{sql:l,params:a}}clone(){if(!this.dao)throw new Error("DAO instance required for cloning QueryBuilder");const t=new E(this.dao);return t.tableName=this.tableName,t.selectFields=[...this.selectFields],t.joinClauses=[...this.joinClauses],t.whereConditions=[...this.whereConditions],t.groupByFields=[...this.groupByFields],t.havingConditions=[...this.havingConditions],t.orderByFields=[...this.orderByFields],t.limitValue=this.limitValue,t.offsetValue=this.offsetValue,t.unionQueries=[...this.unionQueries],t.subQueries=[...this.subQueries],t.cteQueries=new Map(this.cteQueries),t}toRawSQL(){const{sql:t,params:e}=this.toSQL();let i=t;return e.forEach(s=>{typeof s=="string"?i=i.replace("?",`'${s.replace(/'/g,"''")}'`):s==null?i=i.replace("?","NULL"):i=i.replace("?",String(s))}),i}explain(){return this.selectFields=["EXPLAIN QUERY PLAN "+this.selectFields.join(", ")],this}}class R{constructor(t,e){this.migrations=new Map,this.migrationTable="_migrations",this.schemaVersion="1.0.0",this.dao=t,this.migrationTable=(e==null?void 0:e.migrationTable)||"_migrations",this.schemaVersion=(e==null?void 0:e.schemaVersion)||"1.0.0"}addMigration(t){this.validateMigration(t),this.migrations.set(t.version,t)}addMigrations(t){for(const e of t)this.addMigration(e)}loadMigrations(t){Object.values(t).forEach(e=>{this.addMigration(e)})}removeMigration(t){return this.migrations.delete(t)}getMigrations(){return Array.from(this.migrations.values()).sort((t,e)=>this.compareVersions(t.version,e.version))}getMigration(t){return this.migrations.get(t)}async initMigrationTable(){const t=`
13
+ ${s}`)}this.isInitialized=!0}static async getLazyLoading(e){if(this.activeDatabases.add(e),!this.hasAccessToDatabase(e))throw new Error(`Access denied: Database '${e}' is not accessible.`);if(!this.connections[e]){const t=this.getSchema(e);if(!t)throw new Error(`Invalid database key: ${e}. Schema not found.`);if(Object.keys(this.connections).length>=this.maxConnections)throw new Error("Maximum number of database connections reached");const i=await g.createOrOpen({config:t},!1);await i.connect(),this.connections[e]=i}return this.isInitialized=!0,this.connections[e]}static async executeCrossSchemaTransaction(e,t){for(const s of e)if(!this.hasAccessToDatabase(s))throw new Error(`Access denied: Database '${s}' is not accessible.`);const i=e.reduce((s,a)=>(s[a]=this.get(a),s),{});try{await Promise.all(Object.values(i).map(s=>s.beginTransaction())),await t(i),await Promise.all(Object.values(i).map(s=>s.commitTransaction()))}catch(s){throw await Promise.all(Object.values(i).map(a=>a.rollbackTransaction())),s}}static async importDataToTable(e,t,i,s={}){if(!this.hasAccessToDatabase(e))throw new Error(`Access denied: Database '${e}' is not accessible.`);const a=this.get(e);try{return await a.importData(Object.assign({tableName:t,data:i},s))}catch(n){throw n}}static async importDataWithMapping(e,t,i,s,a={}){if(!this.hasAccessToDatabase(e))throw new Error(`Access denied: Database '${e}' is not accessible.`);const n=this.get(e);try{return await n.importDataWithMapping(t,i,s,a)}catch(r){throw r}}static async bulkImport(e){const t=Date.now(),i={totalDatabases:e.length,successDatabases:0,results:{},errors:{},executionTime:0};for(const s of e){const a=`${s.databaseKey}.${s.tableName}`;try{if(!this.hasAccessToDatabase(s.databaseKey))throw new Error(`Access denied: Database '${s.databaseKey}' is not accessible.`);const n=this.get(s.databaseKey);let r;s.columnMappings?r=await n.importDataWithMapping(s.tableName,s.data,s.columnMappings,s.options):r=await n.importData(Object.assign({tableName:s.tableName,data:s.data},s.options)),i.results[a]=r,i.successDatabases++}catch(n){const r=n instanceof Error?n:new Error(String(n));i.errors[a]=r}}return i.executionTime=Date.now()-t,i}static async importFromCSV(e,t,i,s={}){if(!this.hasAccessToDatabase(e))throw new Error(`Access denied: Database '${e}' is not accessible.`);const a=this.get(e);try{return await a.importFromCSV(t,i,s)}catch(n){throw n}}static getConnectionCount(){return Object.keys(this.connections).length}static listConnections(){return Object.keys(this.connections)}static async closeConnection(e){const t=this.connections[e];t&&(await t.disconnect(),delete this.connections[e])}static async closeAll(){await this.closeAllConnections(),this.currentUserRoles=[],this.currentRole=null,this.isInitialized=!1,this.activeDatabases.clear(),this.eventListeners.clear(),this.isClosingConnections=!1}static async logout(){const e=Object.keys(this.connections).filter(t=>t!=="core");for(const t of e)try{await this.connections[t].close(),delete this.connections[t]}catch(i){}this.currentUserRoles=[],this.currentRole=null}}h.maxConnections=10,h.connections={},h.isInitialized=!1,h.roleRegistry={},h.currentRole=null,h.currentUserRoles=[],h.activeDatabases=new Set,h.isClosingConnections=!1,h.schemaConfigurations={},h.schemaManager=null,h.eventListeners=new Map;class C{constructor(e,t){this.dao=null,this.isOpened=!1,this.isInitialized=!1,this.errorHandlers=new Map,this.eventListeners=new Map,this.primaryKeyFields=["id"],this.cache=new Map,this.schemaName=e,this.tableName=t||e,this.reconnectHandler=i=>{this.dao=i,this._emit("daoReconnected",{schemaName:this.schemaName})},h.onDatabaseReconnect(e,this.reconnectHandler),this.bindMethods()}bindMethods(){Object.getOwnPropertyNames(Object.getPrototypeOf(this)).forEach(e=>{typeof this[e]=="function"&&e!=="constructor"&&(this[e]=this[e].bind(this))})}setPrimaryKeyFields(e){return this.primaryKeyFields=e,this}async init(){try{if(this.isInitialized)return this;if(this.dao=await h.getLazyLoading(this.schemaName),!this.dao)throw new Error(`Failed to initialize DAO for schema: ${this.schemaName}`);return this.dao.isConnectionOpen()||await this.dao.connect(),this.isOpened=!0,this.isInitialized=!0,this._emit("initialized",{schemaName:this.schemaName}),this}catch(e){throw this._handleError("INIT_ERROR",e),e}}async create(e){await this._ensureInitialized(),await this.ensureValidConnection();try{this._validateData(e);const t=this.buildDataTable(e),i=await this.dao.insert(t);if(i.rowsAffected===0)throw new Error("Insert operation failed - no rows affected");let s=null;const a=e[this.primaryKeyFields[0]];try{a!=null?s=await this.findById(a):i.lastInsertRowId&&(s=await this.findById(i.lastInsertRowId))}catch(n){console.warn("Warning: Could not retrieve created record:",n)}return s||(s=e),this._emit("dataCreated",{operation:"create",data:s}),s}catch(t){throw this._handleError("CREATE_ERROR",t),t}}async update(e,t){await this._ensureInitialized();try{if(!e)throw new Error("ID is required for update");this._validateData(t);const i=Object.assign(Object.assign({},t),{[this.primaryKeyFields[0]]:e}),s=this.buildDataTable(i);await this.dao.update(s);const a=await this.findById(e);return this._emit("dataUpdated",{operation:"update",id:e,data:a}),a}catch(i){throw this._handleError("UPDATE_ERROR",i),i}}async delete(e){await this._ensureInitialized();try{if(!e)throw new Error("ID is required for delete");const t={name:this.tableName,cols:[],wheres:[{name:this.primaryKeyFields[0],value:e}]},i=(await this.dao.delete(t)).rowsAffected>0;return i&&this._emit("dataDeleted",{operation:"delete",id:e}),i}catch(t){throw this._handleError("DELETE_ERROR",t),t}}async findById(e){await this._ensureInitialized();try{if(!e)throw new Error("ID is required");const t={[this.primaryKeyFields[0]]:e},i=this.buildSelectTable(t),s=await this.dao.select(i),a=Object.keys(s).length>0?s:null;return this._emit("dataFetched",{operation:"findById",id:e}),a}catch(t){throw this._handleError("FIND_BY_ID_ERROR",t),t}}async findFirst(e={}){await this._ensureInitialized();try{const t=this.buildSelectTable(e),i=await this.dao.select(t),s=Object.keys(i).length>0?i:null;return this._emit("dataFetched",{operation:"findFirst"}),s}catch(t){throw this._handleError("FIND_FIRST_ERROR",t),t}}async findAll(e={},t={}){await this._ensureInitialized();try{const i=[...this.buildWhereFromObject(e),...t.where||[]],s={name:this.tableName,cols:t.columns?t.columns.map(n=>({name:n})):[],wheres:i,orderbys:t.orderBy,limitOffset:{limit:t.limit,offset:t.offset}},a=await this.dao.selectAll(s);return this._emit("dataFetched",{operation:"findAll",count:a.length}),a}catch(i){throw this._handleError("FIND_ALL_ERROR",i),i}}async count(e){await this._ensureInitialized();try{let t=[];Array.isArray(e)?t=e:e&&typeof e=="object"&&(t=this.buildWhereFromObject(e));const i={name:this.tableName,cols:[{name:"COUNT(*) as count"}],wheres:t};return(await this.dao.select(i)).count||0}catch(t){throw this._handleError("COUNT_ERROR",t),t}}async exists(e){return await this.findById(e)!==null}async truncate(){await this._ensureInitialized();try{await this.dao.execute(`DELETE FROM ${this.tableName}`),await this.dao.execute(`DELETE FROM sqlite_sequence WHERE name='${this.tableName}'`),this._emit("tableTruncated",{tableName:this.tableName})}catch(e){throw this._handleError("TRUNCATE_ERROR",e),e}}async bulkInsert(e){await this._ensureInitialized();try{if(!Array.isArray(e)||e.length===0)throw new Error("Items must be a non-empty array");const t=await this.dao.importData({tableName:this.tableName,data:e,batchSize:1e3,skipErrors:!1,validateData:!0});return this._emit("dataBulkCreated",{operation:"bulkInsert",count:t.successRows}),t}catch(t){throw this._handleError("BULK_INSERT_ERROR",t),t}}async bulkCreate(e){await this._ensureInitialized();try{if(!Array.isArray(e)||e.length===0)throw new Error("Data must be a non-empty array");const t=[];return await this.executeTransaction(async()=>{for(const i of e){this._validateData(i);const s=this.buildDataTable(i);await this.dao.insert(s),t.push(i)}}),this._emit("dataBulkCreated",{operation:"bulkCreate",count:t.length}),t}catch(t){throw this._handleError("BULK_CREATE_ERROR",t),t}}async executeTransaction(e){await this._ensureInitialized();try{await this.dao.beginTransaction();const t=await e();return await this.dao.commitTransaction(),this._emit("transactionCompleted",{operation:"transaction"}),t}catch(t){try{await this.dao.rollbackTransaction()}catch(i){this._handleError("ROLLBACK_ERROR",i)}throw this._handleError("TRANSACTION_ERROR",t),t}}async importFromCSV(e,t={}){await this._ensureInitialized();try{const i=await this.dao.importFromCSV(this.tableName,e,t);return this._emit("dataImported",{operation:"importFromCSV",result:i}),i}catch(i){throw this._handleError("IMPORT_CSV_ERROR",i),i}}async importDataWithMapping(e,t,i={}){await this._ensureInitialized();try{const s=await this.dao.importDataWithMapping(this.tableName,e,t,i);return this._emit("dataImported",{operation:"importWithMapping",result:s}),s}catch(s){throw this._handleError("IMPORT_MAPPING_ERROR",s),s}}buildSelectTable(e={},t={}){const i={name:this.tableName,cols:[],wheres:[],orderbys:t.orderBy||[],limitOffset:{}};return t.columns&&t.columns.length>0&&(i.cols=t.columns.map(s=>({name:s}))),e&&Object.keys(e).length>0&&(i.wheres=Object.entries(e).map(([s,a])=>({name:s,value:a,operator:"="}))),t.limit!==void 0&&(i.limitOffset.limit=t.limit),t.offset!==void 0&&(i.limitOffset.offset=t.offset),i}buildDataTable(e){return this.dao.convertJsonToQueryTable(this.tableName,e,this.primaryKeyFields)}buildWhereFromObject(e){return Object.entries(e).filter(([t,i])=>i!==void 0).map(([t,i])=>({name:t,value:i}))}on(e,t){return this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t),this}off(e,t){const i=this.eventListeners.get(e);if(i){const s=i.indexOf(t);s>-1&&i.splice(s,1)}return this}_emit(e,t){const i=this.eventListeners.get(e);i&&i.forEach(s=>{try{s(t)}catch(a){}})}setErrorHandler(e,t){return this.errorHandlers.set(e,t),this}_handleError(e,t){const i=this.errorHandlers.get(e);if(i)try{i(t)}catch(s){}this._emit("error",{errorType:e,error:t})}_validateData(e){if(!e||typeof e!="object")throw new Error("Data must be a valid object")}async _ensureInitialized(){this.isInitialized||await this.init()}async ensureValidConnection(){var e;try{!((e=this.dao)===null||e===void 0)&&e.isConnectionOpen()||(this.dao=await h.ensureDatabaseConnection(this.schemaName))}catch(t){this.dao=await h.ensureDatabaseConnection(this.schemaName)}}async getDatabaseInfo(){return await this._ensureInitialized(),await this.dao.getDatabaseInfo()}async getTableInfo(){return await this._ensureInitialized(),await this.dao.getTableInfo(this.tableName)}getStatus(){return{schemaName:this.schemaName,isOpened:this.isOpened,isInitialized:this.isInitialized,hasDao:!!this.dao}}async healthCheck(){try{await this._ensureInitialized();const e=await this.count();return{healthy:!0,schemaName:this.schemaName,recordCount:e,timestamp:new Date().toISOString()}}catch(e){return{healthy:!1,schemaName:this.schemaName,error:e.message,timestamp:new Date().toISOString()}}}async close(){try{return this.dao&&await this.dao.close(),this.isOpened=!1,this.isInitialized=!1,this.eventListeners.clear(),this.errorHandlers.clear(),this.cache.clear(),this._emit("closed",{schemaName:this.schemaName}),!0}catch(e){throw this._handleError("CLOSE_ERROR",e),e}}destroy(){h.offDatabaseReconnect(this.schemaName,this.reconnectHandler),this.eventListeners.clear(),this.errorHandlers.clear(),this.cache.clear()}async getAll(e={},t={}){return this.findAll(e,t)}async getById(e){return this.findById(e)}async getFirst(e={}){return this.findFirst(e)}}class E{constructor(e){this.tableName="",this.selectFields=["*"],this.joinClauses=[],this.whereConditions=[],this.groupByFields=[],this.havingConditions=[],this.orderByFields=[],this.limitValue=null,this.offsetValue=null,this.params=[],this.unionQueries=[],this.subQueries=[],this.cteQueries=new Map,this.dao=null,this.dao=e||null}static table(e,t){const i=new E(t);return i.tableName=e,i}static from(e,t){return E.table(e,t)}select(e){return this.selectFields=Array.isArray(e)?e:[e],this}selectRaw(e){return this.selectFields=[e],this}selectDistinct(e){const t=Array.isArray(e)?e.join(", "):e;return this.selectFields=[`DISTINCT ${t}`],this}join(e,t,i="INNER"){return this.joinClauses.push({type:i,table:e,condition:t}),this}innerJoin(e,t){return this.join(e,t,"INNER")}leftJoin(e,t){return this.join(e,t,"LEFT")}rightJoin(e,t){return this.join(e,t,"RIGHT")}fullOuterJoin(e,t){return this.join(e,t,"FULL OUTER")}where(e,t,i){if(typeof e=="object")return Object.entries(e).forEach(([n,r])=>{this.whereConditions.push({field:n,operator:"=",value:r})}),this;let s="=",a=t;return arguments.length===3&&(s=t,a=i),this.whereConditions.push({field:e,operator:s,value:a}),this}whereEquals(e,t){return this.where(e,"=",t)}whereNot(e,t){return this.where(e,"!=",t)}whereLike(e,t){return this.where(e,"LIKE",t)}whereNotLike(e,t){return this.where(e,"NOT LIKE",t)}whereIn(e,t){return this.whereConditions.push({field:e,operator:"IN",value:t}),this}whereNotIn(e,t){return this.whereConditions.push({field:e,operator:"NOT IN",value:t}),this}whereBetween(e,t,i){return this.whereConditions.push({field:e,operator:"BETWEEN",value:[t,i]}),this}whereNotBetween(e,t,i){return this.whereConditions.push({field:e,operator:"NOT BETWEEN",value:[t,i]}),this}whereNull(e){return this.whereConditions.push({field:e,operator:"IS NULL",value:null}),this}whereNotNull(e){return this.whereConditions.push({field:e,operator:"IS NOT NULL",value:null}),this}whereExists(e){return this.whereConditions.push({field:"",operator:"EXISTS",value:e}),this}whereNotExists(e){return this.whereConditions.push({field:"",operator:"NOT EXISTS",value:e}),this}orWhere(e,t,i){return this.where(e,t,i)}groupBy(e){return this.groupByFields=Array.isArray(e)?e:[e],this}having(e,t,i){let s="=",a=t;return arguments.length===3&&(s=t,a=i),this.havingConditions.push({field:e,operator:s,value:a}),this}havingCount(e,t,i){return this.having(`COUNT(${e})`,t,i)}orderBy(e,t="ASC"){return this.orderByFields.push(`${e} ${t}`),this}orderByDesc(e){return this.orderBy(e,"DESC")}orderByRaw(e){return this.orderByFields.push(e),this}latest(e="created_at"){return this.orderByDesc(e)}oldest(e="created_at"){return this.orderBy(e,"ASC")}limit(e){return this.limitValue=e,this}offset(e){return this.offsetValue=e,this}skip(e){return this.offset(e)}take(e){return this.limit(e)}firstRow(){return this.limit(1)}paginate(e,t){return this.limitValue=t,this.offsetValue=(e-1)*t,this}union(e){return this.unionQueries.push(e),this}unionAll(e){return this.union(e)}with(e,t){return this.cteQueries.set(e,t),this}whereSubQuery(e,t,i){return this.subQueries.push({query:i,alias:""}),this.whereConditions.push({field:e,operator:t,value:i}),this}count(e="*"){return this.selectFields=[`COUNT(${e}) as count`],this}sum(e){return this.selectFields=[`SUM(${e}) as sum`],this}avg(e){return this.selectFields=[`AVG(${e}) as avg`],this}max(e){return this.selectFields=[`MAX(${e}) as max`],this}min(e){return this.selectFields=[`MIN(${e}) as min`],this}toSQL(){let e="";const t=[];if(this.cteQueries.size>0){const i=[];this.cteQueries.forEach((s,a)=>{const{sql:n,params:r}=s.toSQL();i.push(`${a} AS (${n})`),t.push(...r)}),e+=`WITH ${i.join(", ")} `}if(e+=`SELECT ${this.selectFields.join(", ")} FROM ${this.tableName}`,this.joinClauses.length>0&&this.joinClauses.forEach(i=>{e+=` ${i.type} JOIN ${i.table} ON ${i.condition}`}),this.whereConditions.length>0){const i=[];this.whereConditions.forEach(s=>{const{clause:a,conditionParams:n}=this.buildCondition(s);i.push(a),t.push(...n)}),e+=` WHERE ${i.join(" AND ")}`}if(this.groupByFields.length>0&&(e+=` GROUP BY ${this.groupByFields.join(", ")}`),this.havingConditions.length>0){const i=[];this.havingConditions.forEach(s=>{const{clause:a,conditionParams:n}=this.buildCondition(s);i.push(a),t.push(...n)}),e+=` HAVING ${i.join(" AND ")}`}return this.orderByFields.length>0&&(e+=` ORDER BY ${this.orderByFields.join(", ")}`),this.limitValue!==null&&(e+=` LIMIT ${this.limitValue}`),this.offsetValue!==null&&(e+=` OFFSET ${this.offsetValue}`),this.unionQueries.length>0&&this.unionQueries.forEach(i=>{const{sql:s,params:a}=i.toSQL();e+=` UNION ${s}`,t.push(...a)}),{sql:e,params:t}}buildCondition(e){const{field:t,operator:i,value:s}=e,a=[];switch(i.toUpperCase()){case"IN":case"NOT IN":const n=s.map(()=>"?").join(", ");return a.push(...s),{clause:`${t} ${i} (${n})`,conditionParams:a};case"BETWEEN":case"NOT BETWEEN":return a.push(s[0],s[1]),{clause:`${t} ${i} ? AND ?`,conditionParams:a};case"IS NULL":case"IS NOT NULL":return{clause:`${t} ${i}`,conditionParams:[]};case"EXISTS":case"NOT EXISTS":const{sql:r,params:o}=s.toSQL();return a.push(...o),{clause:`${i} (${r})`,conditionParams:a};default:if(s instanceof E){const{sql:l,params:c}=s.toSQL();return a.push(...c),{clause:`${t} ${i} (${l})`,conditionParams:a}}return a.push(s),{clause:`${t} ${i} ?`,conditionParams:a}}}async get(){if(!this.dao)throw new Error("DAO instance required for query execution");const{sql:e,params:t}=this.toSQL();return(await this.dao.execute(e,t)).rows}async first(){this.limit(1);const e=await this.get();return e.length>0?e[0]:null}async pluck(e){return this.select(e),(await this.get()).map(t=>t[e])}async exists(){return this.select("1").limit(1),(await this.get()).length>0}async countResult(){this.count();const e=await this.first();return e?e.count:0}static insert(e,t){const i=Object.keys(t),s=Object.values(t),a=s.map(()=>"?").join(", ");return{sql:`INSERT INTO ${e} (${i.join(", ")}) VALUES (${a})`,params:s}}static insertMany(e,t){if(t.length===0)throw new Error("Data array cannot be empty");const i=Object.keys(t[0]),s=i.map(()=>"?").join(", "),a=t.map(()=>`(${s})`).join(", "),n=t.flatMap(r=>Object.values(r));return{sql:`INSERT INTO ${e} (${i.join(", ")}) VALUES ${a}`,params:n}}static update(e,t,i,s=[]){const a=Object.keys(t).map(r=>`${r} = ?`).join(", "),n=[...Object.values(t),...s];return{sql:`UPDATE ${e} SET ${a} WHERE ${i}`,params:n}}static delete(e,t,i=[]){return{sql:`DELETE FROM ${e} WHERE ${t}`,params:i}}static upsert(e,t,i){const s=Object.keys(t),a=Object.values(t),n=a.map(()=>"?").join(", "),r=s.filter(c=>!i.includes(c)),o=r.length>0?r.map(c=>`${c} = excluded.${c}`).join(", "):"";let l=`INSERT INTO ${e} (${s.join(", ")}) VALUES (${n})`;return r.length>0?l+=` ON CONFLICT(${i.join(", ")}) DO UPDATE SET ${o}`:l+=` ON CONFLICT(${i.join(", ")}) DO NOTHING`,{sql:l,params:a}}clone(){if(!this.dao)throw new Error("DAO instance required for cloning QueryBuilder");const e=new E(this.dao);return e.tableName=this.tableName,e.selectFields=[...this.selectFields],e.joinClauses=[...this.joinClauses],e.whereConditions=[...this.whereConditions],e.groupByFields=[...this.groupByFields],e.havingConditions=[...this.havingConditions],e.orderByFields=[...this.orderByFields],e.limitValue=this.limitValue,e.offsetValue=this.offsetValue,e.unionQueries=[...this.unionQueries],e.subQueries=[...this.subQueries],e.cteQueries=new Map(this.cteQueries),e}toRawSQL(){const{sql:e,params:t}=this.toSQL();let i=e;return t.forEach(s=>{typeof s=="string"?i=i.replace("?",`'${s.replace(/'/g,"''")}'`):s==null?i=i.replace("?","NULL"):i=i.replace("?",String(s))}),i}explain(){return this.selectFields=["EXPLAIN QUERY PLAN "+this.selectFields.join(", ")],this}}class R{constructor(e,t){this.migrations=new Map,this.migrationTable="_migrations",this.schemaVersion="1.0.0",this.dao=e,this.migrationTable=(t==null?void 0:t.migrationTable)||"_migrations",this.schemaVersion=(t==null?void 0:t.schemaVersion)||"1.0.0"}addMigration(e){this.validateMigration(e),this.migrations.set(e.version,e)}addMigrations(e){for(const t of e)this.addMigration(t)}loadMigrations(e){Object.values(e).forEach(t=>{this.addMigration(t)})}removeMigration(e){return this.migrations.delete(e)}getMigrations(){return Array.from(this.migrations.values()).sort((e,t)=>this.compareVersions(e.version,t.version))}getMigration(e){return this.migrations.get(e)}async initMigrationTable(){const e=`
14
14
  CREATE TABLE IF NOT EXISTS ${this.migrationTable} (
15
15
  version TEXT PRIMARY KEY,
16
16
  description TEXT NOT NULL,
@@ -20,7 +20,7 @@ ${s}`)}this.isInitialized=!0}static async getLazyLoading(t){if(this.activeDataba
20
20
  checksum TEXT,
21
21
  schema_version TEXT DEFAULT '${this.schemaVersion}'
22
22
  )
23
- `;await this.dao.execute(t),await this.dao.execute(`
23
+ `;await this.dao.execute(e),await this.dao.execute(`
24
24
  CREATE INDEX IF NOT EXISTS idx_migrations_applied_at
25
25
  ON ${this.migrationTable} (applied_at)
26
26
  `),await this.dao.execute(`
@@ -30,17 +30,17 @@ ${s}`)}this.isInitialized=!0}static async getLazyLoading(t){if(this.activeDataba
30
30
  SELECT version, description, category, applied_at, execution_time_ms, checksum
31
31
  FROM ${this.migrationTable}
32
32
  ORDER BY applied_at ASC
33
- `)).rows}catch(t){return[]}}async getPendingMigrations(){const t=await this.getAppliedMigrations(),e=new Set(t.map(i=>i.version));return this.getMigrations().filter(i=>!e.has(i.version))}async getDetailedStatus(){await this.initMigrationTable();const t=await this.getAppliedMigrations(),e=new Map(t.map(i=>[i.version,i]));return this.getMigrations().map(i=>{const s=e.get(i.version),{dependenciesMet:a,missingDependencies:r}=this.checkDependencies(i);return{version:i.version,description:i.description,category:i.category,applied:!!s,applied_at:s==null?void 0:s.applied_at,execution_time_ms:s==null?void 0:s.execution_time_ms,dependencies_met:a,missing_dependencies:r}})}async createMigrationPlan(t,e="up"){const i=await this.getAppliedMigrations(),s=new Set(i.map(n=>n.version)),a=this.getMigrations(),r={toApply:[],toRollback:[],conflicts:[],estimatedTime:0};if(e==="up")for(const n of a){if(t&&this.compareVersions(n.version,t)>0)break;if(!s.has(n.version)){const{dependenciesMet:o,missingDependencies:l}=this.checkDependencies(n);o?r.toApply.push(n):r.conflicts.push(`Migration ${n.version} has unmet dependencies: ${l.join(", ")}`)}}else{const n=i.filter(o=>!t||this.compareVersions(o.version,t)>0).sort((o,l)=>this.compareVersions(l.version,o.version));for(const o of n){const l=this.migrations.get(o.version);l&&r.toRollback.push(l)}}return r.estimatedTime=(r.toApply.length+r.toRollback.length)*1e3,r}async migrate(t,e={}){var i,s;await this.initMigrationTable();const a=await this.createMigrationPlan(t,"up");if(a.conflicts.length>0)throw new Error(`Migration conflicts detected:
33
+ `)).rows}catch(e){return[]}}async getPendingMigrations(){const e=await this.getAppliedMigrations(),t=new Set(e.map(i=>i.version));return this.getMigrations().filter(i=>!t.has(i.version))}async getDetailedStatus(){await this.initMigrationTable();const e=await this.getAppliedMigrations(),t=new Map(e.map(i=>[i.version,i]));return this.getMigrations().map(i=>{const s=t.get(i.version),{dependenciesMet:a,missingDependencies:n}=this.checkDependencies(i);return{version:i.version,description:i.description,category:i.category,applied:!!s,applied_at:s==null?void 0:s.applied_at,execution_time_ms:s==null?void 0:s.execution_time_ms,dependencies_met:a,missing_dependencies:n}})}async createMigrationPlan(e,t="up"){const i=await this.getAppliedMigrations(),s=new Set(i.map(r=>r.version)),a=this.getMigrations(),n={toApply:[],toRollback:[],conflicts:[],estimatedTime:0};if(t==="up")for(const r of a){if(e&&this.compareVersions(r.version,e)>0)break;if(!s.has(r.version)){const{dependenciesMet:o,missingDependencies:l}=this.checkDependencies(r);o?n.toApply.push(r):n.conflicts.push(`Migration ${r.version} has unmet dependencies: ${l.join(", ")}`)}}else{const r=i.filter(o=>!e||this.compareVersions(o.version,e)>0).sort((o,l)=>this.compareVersions(l.version,o.version));for(const o of r){const l=this.migrations.get(o.version);l&&n.toRollback.push(l)}}return n.estimatedTime=(n.toApply.length+n.toRollback.length)*1e3,n}async migrate(e,t={}){var i,s;await this.initMigrationTable();const a=await this.createMigrationPlan(e,"up");if(a.conflicts.length>0)throw new Error(`Migration conflicts detected:
34
34
  ${a.conflicts.join(`
35
- `)}`);if(e.dryRun)return console.log("Dry run - would apply the following migrations:"),a.toApply.forEach(o=>console.log(` - ${o.version}: ${o.description}`)),[];const r=[],n=a.toApply.length;for(let o=0;o<a.toApply.length;o++){const l=a.toApply[o];try{(i=e.onProgress)===null||i===void 0||i.call(e,o+1,n,l);const c=await this.applyMigration(l,e);r.push(c)}catch(c){const f=c instanceof Error?c:new Error(String(c));if((s=e.onError)===null||s===void 0||s.call(e,f,l),e.stopOnError!==!1)throw new Error(`Migration ${l.version} failed: ${f.message}`)}}return r}async rollback(t,e={}){var i,s;await this.initMigrationTable();const a=await this.createMigrationPlan(t,"down");if(e.dryRun){console.log("Dry run - would rollback the following migrations:"),a.toRollback.forEach(n=>console.log(` - ${n.version}: ${n.description}`));return}const r=a.toRollback.length;for(let n=0;n<a.toRollback.length;n++){const o=a.toRollback[n];try{(i=e.onProgress)===null||i===void 0||i.call(e,n+1,r,o),await this.rollbackMigration(o,e)}catch(l){const c=l instanceof Error?l:new Error(String(l));if((s=e.onError)===null||s===void 0||s.call(e,c,o),e.stopOnError!==!1)throw new Error(`Rollback of migration ${o.version} failed: ${c.message}`)}}}async applyMigration(t,e){const i=Date.now(),s=e.timeout||3e4;await this.dao.beginTransaction();try{const a=t.up(this.dao);if(s>0){const o=new Promise((l,c)=>{setTimeout(()=>c(new Error(`Migration timeout after ${s}ms`)),s)});await Promise.race([a,o])}else await a;const r=Date.now()-i,n=e.validateChecksums?this.generateChecksum(t):void 0;return await this.dao.execute(`
35
+ `)}`);if(t.dryRun)return console.log("Dry run - would apply the following migrations:"),a.toApply.forEach(o=>console.log(` - ${o.version}: ${o.description}`)),[];const n=[],r=a.toApply.length;for(let o=0;o<a.toApply.length;o++){const l=a.toApply[o];try{(i=t.onProgress)===null||i===void 0||i.call(t,o+1,r,l);const c=await this.applyMigration(l,t);n.push(c)}catch(c){const f=c instanceof Error?c:new Error(String(c));if((s=t.onError)===null||s===void 0||s.call(t,f,l),t.stopOnError!==!1)throw new Error(`Migration ${l.version} failed: ${f.message}`)}}return n}async rollback(e,t={}){var i,s;await this.initMigrationTable();const a=await this.createMigrationPlan(e,"down");if(t.dryRun){console.log("Dry run - would rollback the following migrations:"),a.toRollback.forEach(r=>console.log(` - ${r.version}: ${r.description}`));return}const n=a.toRollback.length;for(let r=0;r<a.toRollback.length;r++){const o=a.toRollback[r];try{(i=t.onProgress)===null||i===void 0||i.call(t,r+1,n,o),await this.rollbackMigration(o,t)}catch(l){const c=l instanceof Error?l:new Error(String(l));if((s=t.onError)===null||s===void 0||s.call(t,c,o),t.stopOnError!==!1)throw new Error(`Rollback of migration ${o.version} failed: ${c.message}`)}}}async applyMigration(e,t){const i=Date.now(),s=t.timeout||3e4;await this.dao.beginTransaction();try{const a=e.up(this.dao);if(s>0){const o=new Promise((l,c)=>{setTimeout(()=>c(new Error(`Migration timeout after ${s}ms`)),s)});await Promise.race([a,o])}else await a;const n=Date.now()-i,r=t.validateChecksums?this.generateChecksum(e):void 0;return await this.dao.execute(`
36
36
  INSERT INTO ${this.migrationTable}
37
37
  (version, description, category, execution_time_ms, checksum)
38
38
  VALUES (?, ?, ?, ?, ?)
39
- `,[t.version,t.description,t.category||null,r,n||null]),await this.dao.commitTransaction(),{version:t.version,description:t.description,category:t.category,applied_at:new Date().toISOString(),execution_time_ms:r,checksum:n}}catch(a){throw await this.dao.rollbackTransaction(),a}}async rollbackMigration(t,e){const i=e.timeout||3e4;await this.dao.beginTransaction();try{const s=t.down(this.dao);if(i>0){const a=new Promise((r,n)=>{setTimeout(()=>n(new Error(`Rollback timeout after ${i}ms`)),i)});await Promise.race([s,a])}else await s;await this.dao.execute(`
39
+ `,[e.version,e.description,e.category||null,n,r||null]),await this.dao.commitTransaction(),{version:e.version,description:e.description,category:e.category,applied_at:new Date().toISOString(),execution_time_ms:n,checksum:r}}catch(a){throw await this.dao.rollbackTransaction(),a}}async rollbackMigration(e,t){const i=t.timeout||3e4;await this.dao.beginTransaction();try{const s=e.down(this.dao);if(i>0){const a=new Promise((n,r)=>{setTimeout(()=>r(new Error(`Rollback timeout after ${i}ms`)),i)});await Promise.race([s,a])}else await s;await this.dao.execute(`
40
40
  DELETE FROM ${this.migrationTable} WHERE version = ?
41
- `,[t.version]),await this.dao.commitTransaction()}catch(s){throw await this.dao.rollbackTransaction(),s}}async reset(t={}){if(!t.force)throw new Error("Reset requires explicit force option to prevent accidental data loss");await this.dao.beginTransaction();try{const e=(await this.getAppliedMigrations()).sort((i,s)=>this.compareVersions(s.version,i.version));for(const i of e){const s=this.migrations.get(i.version);s&&await s.down(this.dao)}await this.dao.execute(`DELETE FROM ${this.migrationTable}`),await this.dao.commitTransaction()}catch(e){throw await this.dao.rollbackTransaction(),e}}async validateIntegrity(){const t=[];try{const e=await this.getAppliedMigrations();for(const i of e){const s=this.migrations.get(i.version);if(!s){t.push(`Applied migration ${i.version} not found in registered migrations`);continue}const{dependenciesMet:a,missingDependencies:r}=this.checkDependencies(s);a||t.push(`Migration ${i.version} has unmet dependencies: ${r.join(", ")}`),i.checksum&&this.generateChecksum(s)!==i.checksum&&t.push(`Migration ${i.version} has changed since it was applied (checksum mismatch)`)}return{valid:t.length===0,issues:t}}catch(e){return{valid:!1,issues:[`Error validating migration integrity: ${e.message}`]}}}async getHistory(){const t=await this.getAppliedMigrations(),e=await this.getPendingMigrations(),i={};let s=0;for(const a of t)a.category&&(i[a.category]=(i[a.category]||0)+1),s+=a.execution_time_ms||0;return{totalMigrations:this.migrations.size,appliedMigrations:t.length,pendingMigrations:e.length,categories:i,totalExecutionTime:s,averageExecutionTime:t.length>0?s/t.length:0,recentMigrations:t.slice(-10)}}static createMigrationFromSchema(t,e,i,s){const a=s||`Schema update to version ${i}`;return{version:i,description:a,up:async r=>{for(const[n,o]of Object.entries(e.schemas))if(!t.schemas[n])throw o.cols,o.description,o.indexes,o.foreign_keys,new Error("Automatic schema migration generation not fully implemented. Please create migrations manually.")},down:async r=>{throw new Error("Automatic rollback generation not fully implemented. Please create rollback manually.")}}}validateMigration(t){if(!t.version||typeof t.version!="string")throw new Error("Migration version is required and must be a string");if(!t.description||typeof t.description!="string")throw new Error("Migration description is required and must be a string");if(typeof t.up!="function")throw new Error("Migration up function is required");if(typeof t.down!="function")throw new Error("Migration down function is required");if(this.migrations.has(t.version))throw new Error(`Migration with version ${t.version} already exists`)}checkDependencies(t){if(!t.dependencies||t.dependencies.length===0)return{dependenciesMet:!0,missingDependencies:[]};const e=t.dependencies.filter(i=>!this.migrations.has(i));return{dependenciesMet:e.length===0,missingDependencies:e}}compareVersions(t,e){const i=t.split(".").map(Number),s=e.split(".").map(Number);for(let a=0;a<Math.max(i.length,s.length);a++){const r=i[a]||0,n=s[a]||0;if(r<n)return-1;if(r>n)return 1}return 0}generateChecksum(t){const e=t.up.toString()+t.down.toString();let i=0;for(let s=0;s<e.length;s++){const a=e.charCodeAt(s);i=(i<<5)-i+a,i=i&i}return i.toString(16)}}class b{constructor(t){this.dao=t}parseCSV(t,e={}){const i=Object.assign({delimiter:",",quote:'"',escape:'"',hasHeader:!0,skipEmptyLines:!0,trimWhitespace:!0},e),s={data:[],headers:[],totalRows:0,parsedRows:0,skippedRows:0,errors:[]};if(!t||t.trim().length===0)return s.errors.push({row:0,error:"CSV data is empty"}),s;try{const a=this.splitCSVLines(t,i);if(s.totalRows=a.length,a.length===0)return s.errors.push({row:0,error:"No valid lines found in CSV data"}),s;let r=0;if(i.hasHeader&&a.length>0)try{s.headers=this.parseCSVRow(a[0],i),i.trimWhitespace&&(s.headers=s.headers.map(n=>n.trim())),r=1}catch(n){return s.errors.push({row:1,error:`Failed to parse header row: ${n.message}`,rawData:a[0]}),s}else{const n=this.parseCSVRow(a[0],i);s.headers=n.map((o,l)=>`column_${l+1}`)}for(let n=r;n<a.length;n++){const o=n+1,l=a[n];if(i.skipEmptyLines&&l.trim().length===0){s.skippedRows++;continue}try{const c=this.parseCSVRow(l,i),f={};s.headers.forEach((u,m)=>{let p=c[m]||null;i.trimWhitespace&&typeof p=="string"&&(p=p.trim()),p===""&&(p=null),f[u]=p}),s.data.push(f),s.parsedRows++}catch(c){s.errors.push({row:o,error:`Failed to parse row: ${c.message}`,rawData:l}),s.skippedRows++}}return s}catch(a){return s.errors.push({row:0,error:`CSV parsing failed: ${a.message}`}),s}}async importFromCSV(t,e,i={}){const s=this.parseCSV(e,i);if(s.errors.length>0&&s.data.length===0)throw new Error(`CSV parsing failed: ${s.errors.map(c=>c.error).join("; ")}`);let a=s.data;i.startFromRow&&i.startFromRow>0&&(a=a.slice(i.startFromRow)),i.maxRows&&i.maxRows>0&&(a=a.slice(0,i.maxRows)),i.columnMappings&&(a=this.applyColumnMappings(a,i.columnMappings));const r=[],n=[];for(let c=0;c<a.length;c++){const f=a[c];let u=Object.assign({},f);try{if(i.onRowParsed){const m=i.onRowParsed(u,c);if(m===null)continue;u=m}if(i.transform){for(const[m,p]of Object.entries(i.transform))if(u.hasOwnProperty(m))try{u[m]=p(u[m],u,c)}catch(y){if(n.push({row:c+1,error:`Transform error for field '${m}': ${y.message}`}),i.onRowError){if(!i.onRowError(y,u,c))throw y;continue}throw y}}if(i.validate){for(const[m,p]of Object.entries(i.validate))if(u.hasOwnProperty(m))try{const y=p(u[m],u,c);if(y!==!0){const S=typeof y=="string"?y:`Validation failed for field '${m}'`,T=new Error(S);if(i.onRowError){if(!i.onRowError(T,u,c))throw T;continue}throw T}}catch(y){throw n.push({row:c+1,error:`Validation error for field '${m}': ${y.message}`}),y}}u=this.autoConvertTypes(u,i),r.push(u)}catch(m){if(i.onRowError&&i.onRowError(m,u,c))continue;throw m}}const o=await this.dao.importData({tableName:t,data:r,batchSize:i.batchSize||1e3,onProgress:i.onProgress,onError:i.onError,skipErrors:i.skipErrors||!1,validateData:i.validateData!==!1,updateOnConflict:i.updateOnConflict||!1,conflictColumns:i.conflictColumns,includeAutoIncrementPK:i.includeAutoIncrementPK||!1}),l=[...s.errors.map(c=>({rowIndex:c.row-1,error:c.error,rowData:c.rawData?{_raw:c.rawData}:{}})),...n.map(c=>({rowIndex:c.row-1,error:c.error,rowData:{}})),...o.errors];return Object.assign(Object.assign({},o),{errors:l,parseResult:s})}async importFromFile(t,e,i={}){let s;try{if(typeof globalThis.Deno!="undefined"&&globalThis.Deno.readTextFile)s=await globalThis.Deno.readTextFile(e);else if(typeof require!="undefined")s=await require("fs").promises.readFile(e,i.encoding||"utf8");else if(typeof e=="object"&&"text"in e)s=await e.text();else throw new Error("File reading not supported in this environment")}catch(a){throw new Error(`Failed to read CSV file '${e}': ${a.message}`)}return await this.importFromCSV(t,s,i)}async exportToCSV(t,e={}){const i=Object.assign({delimiter:",",quote:'"',includeHeaders:!0,dateFormat:"YYYY-MM-DD HH:mm:ss",nullValue:""},e);let s=`SELECT ${e.columns?e.columns.join(", "):"*"} FROM ${t}`;const a=[];e.where&&(s+=` WHERE ${e.where}`),e.orderBy&&(s+=` ORDER BY ${e.orderBy}`),e.limit&&(s+=` LIMIT ${e.limit}`);const r=await this.dao.execute(s,a);if(r.rows.length===0)return i.includeHeaders&&e.columns?this.formatCSVRow(e.columns,i):"";const n=[];if(i.includeHeaders){const o=e.columns||Object.keys(r.rows[0]);n.push(this.formatCSVRow(o,i))}for(const o of r.rows){const l=Object.values(o).map(c=>c==null?i.nullValue:c instanceof Date?this.formatDate(c,i.dateFormat):String(c));n.push(this.formatCSVRow(l,i))}return n.join(`
42
- `)}splitCSVLines(t,e){const i=[];let s="",a=!1;for(let r=0;r<t.length;r++){const n=t[r],o=t[r+1];if(n===e.quote&&(a=!a,o===e.quote&&e.escape===e.quote)){s+=n+o,r++;continue}if(n===`
43
- `&&!a){if(e.skipEmptyLines&&s.trim().length===0){s="";continue}i.push(s),s="",a=!1}else if(n==="\r"&&o===`
44
- `&&!a){if(e.skipEmptyLines&&s.trim().length===0){s="",r++;continue}i.push(s),s="",r++,a=!1}else s+=n}return s.length>0&&(!e.skipEmptyLines||s.trim().length>0)&&i.push(s),i}parseCSVRow(t,e){const i=[];let s="",a=!1;for(let r=0;r<t.length;r++){const n=t[r],o=t[r+1];n===e.quote?a&&o===e.quote&&e.escape===e.quote?(s+=e.quote,r++):a=!a:n===e.delimiter&&!a?(i.push(s),s=""):s+=n}return i.push(s),i}formatCSVRow(t,e){return t.map(i=>{const s=String(i);return s.includes(e.delimiter)||s.includes(e.quote)||s.includes(`
45
- `)||s.includes("\r")?e.quote+s.replace(new RegExp(e.quote,"g"),e.quote+e.quote)+e.quote:s}).join(e.delimiter)}applyColumnMappings(t,e){return Array.isArray(e)?t.map(i=>{const s={};return e.forEach(a=>{if(i.hasOwnProperty(a.sourceColumn)){let r=i[a.sourceColumn];a.transform&&(r=a.transform(r)),s[a.targetColumn]=r}}),s}):t.map(i=>{const s={};return Object.entries(i).forEach(([a,r])=>{const n=e[a]||a;s[n]=r}),s})}autoConvertTypes(t,e){const i={};return Object.entries(t).forEach(([s,a])=>{i[s]=this.convertValue(a,e)}),i}convertValue(t,e){if(t==null||t==="")return null;const i=String(t).trim();if(e.booleanValues){const s=i.toLowerCase();if(e.booleanValues.true.some(a=>a.toLowerCase()===s))return!0;if(e.booleanValues.false.some(a=>a.toLowerCase()===s))return!1}else{const s=i.toLowerCase();if(["true","1","yes","on"].includes(s))return!0;if(["false","0","no","off"].includes(s))return!1}if(/^-?\d+$/.test(i)){const s=parseInt(i);if(!isNaN(s))return s}if(/^-?\d*\.?\d+$/.test(i)){const s=parseFloat(i);if(!isNaN(s))return s}if(e.dateFormats)for(const s of e.dateFormats){const a=this.parseDate(i,s);if(a)return a.toISOString()}else{const s=new Date(i);if(!isNaN(s.getTime())&&i.match(/\d{4}-\d{2}-\d{2}/))return s.toISOString()}return i}parseDate(t,e){try{const i=new Date(t);return isNaN(i.getTime())?null:i}catch(i){return null}}formatDate(t,e){const i=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),a=String(t.getDate()).padStart(2,"0"),r=String(t.getHours()).padStart(2,"0"),n=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0");return e.replace("YYYY",String(i)).replace("MM",s).replace("DD",a).replace("HH",r).replace("mm",n).replace("ss",o)}static parseCSVValue(t,e={}){if(t===""||t===null)return null;const i=Object.assign({autoConvert:!0,booleanValues:{true:["true","1","yes","on"],false:["false","0","no","off"]}},e);if(!i.autoConvert)return t;const s=String(t).trim().toLowerCase();if(i.booleanValues.true.includes(s))return!0;if(i.booleanValues.false.includes(s))return!1;if(/^-?\d+$/.test(t)){const r=parseInt(t);if(!isNaN(r))return r}if(/^-?\d*\.?\d+$/.test(t)){const r=parseFloat(t);if(!isNaN(r))return r}const a=new Date(t);return!isNaN(a.getTime())&&t.match(/\d{4}-\d{2}-\d{2}/)?a.toISOString():t}static validateCSVStructure(t,e={}){const i={isValid:!0,errors:[],rowCount:0,columnCount:0,headers:[]};try{const s=new b({}).parseCSV(t,e);i.rowCount=s.totalRows,i.headers=s.headers,i.columnCount=s.headers.length,s.errors.length>0&&(i.isValid=!1,i.errors=s.errors.map(r=>r.error)),s.data.length===0&&(i.isValid=!1,i.errors.push("No valid data rows found"));const a=s.data.filter(r=>Object.keys(r).length!==i.columnCount);a.length>0&&(i.isValid=!1,i.errors.push(`${a.length} rows have inconsistent column count`))}catch(s){i.isValid=!1,i.errors.push(`Validation failed: ${s.message}`)}return i}}class v{sanitizeSQL(t){return t.trim()}bindParameters(t,e){if(!e||e.length===0)return t;let i=0;return t.replace(/\?/g,()=>{if(i<e.length){const s=e[i++];return typeof s=="string"?`'${s.replace(/'/g,"''")}'`:s==null?"NULL":String(s)}return"?"})}}class w{constructor(){if(this.currentSchema=null,this.isInitialized=!1,this.initializationPromise=null,this.eventListeners=new Map,w.instance)throw new Error("UniversalSQLite is a singleton. Use UniversalSQLite.getInstance() instead.")}static getInstance(){return w.instance||(w.instance=new w),w.instance}static resetInstance(){w.instance&&w.instance.closeAll().catch(()=>{}),w.instance=null}async initialize(t,e={}){return this.isInitialized?this.initializationPromise||Promise.resolve():this.initializationPromise?this.initializationPromise:(this.initializationPromise=this._performInitialization(t,e),this.initializationPromise)}async _performInitialization(t,e){try{e.registerAdapters&&e.registerAdapters.forEach(i=>{g.registerAdapter(i)}),e.globalErrorHandler&&this.on("error",e.globalErrorHandler),h.registerSchemas(t),t.core&&e.autoConnectCore!==!1&&await h.initializeCoreConnection(),e.defaultRoles&&e.defaultRoles.length>0&&await h.setCurrentUserRoles(e.defaultRoles),this.isInitialized=!0,this._emit("initialized",{schemas:Object.keys(t)})}catch(i){throw this.isInitialized=!1,this.initializationPromise=null,this._emit("error",i,"initialization"),i}}async initializeFromSchema(t,e={}){const i={[t.database_name]:t};return this.initialize(i,Object.assign(Object.assign({},e),{autoConnectCore:e.autoConnect!==!1}))}async connect(t){this.ensureInitialized(),this.currentSchema=t;try{const e=await h.getLazyLoading(t);return this._emit("connected",{schemaName:t}),e}catch(e){throw this._emit("error",e,"connection"),e}}getDAO(t){this.ensureInitialized();const e=t||this.currentSchema;if(!e)throw new Error("No schema specified. Use connect() first or provide schemaName parameter.");try{return h.get(e)}catch(i){throw this._emit("error",i,"getDAO"),i}}getCurrentDAO(){if(!this.currentSchema)throw new Error("No current connection. Call connect() first.");return this.getDAO(this.currentSchema)}async ensureDatabaseConnection(t){this.ensureInitialized();try{return await h.ensureDatabaseConnection(t)}catch(e){throw this._emit("error",e,"ensureConnection"),e}}createService(t,e){const i=e||this.currentSchema;if(!i)throw new Error("No schema specified. Use connect() first or provide schemaName parameter.");const s=class extends C{constructor(){if(!i)throw new Error("No schema specified. Use connect() first or provide schemaName parameter.");super(i,t)}};return new s}createServices(t,e){const i={};return t.forEach(s=>{i[s]=this.createService(s,e)}),i}query(t,e){const i=this.getDAO(e);return t?E.table(t,i):new E(i)}table(t,e){return this.query(t,e)}async execute(t,e,i){try{const s=await this.getDAO(i).execute(t,e);return this._emit("queryExecuted",{sql:t,params:e,rowCount:s.rowsAffected}),s}catch(s){throw this._emit("error",s,"execute"),s}}async getRst(t,e,i){return await this.getDAO(i).getRst(t,e)}async getRsts(t,e,i){return await this.getDAO(i).getRsts(t,e)}async initializeSchema(t,e=!1){try{await(await g.createOrOpen({config:t},e)).initializeFromSchema(t),this._emit("schemaInitialized",{schemaName:t.database_name})}catch(i){throw this._emit("error",i,"schemaInitialization"),i}}async getSchemaVersion(t){return await this.getDAO(t).getSchemaVersion()}async getDatabaseInfo(t){return await this.getDAO(t).getDatabaseInfo()}async getTableInfo(t,e){return await this.getDAO(e).getTableInfo(t)}createMigrationManager(t){const e=this.getDAO(t);return new R(e)}async runMigrations(t,e,i){const s=this.createMigrationManager(e);t.forEach(a=>{s.addMigration(a)}),await s.migrate(i),this._emit("migrationsCompleted",{schemaName:e||this.currentSchema})}createCSVImporter(t){const e=this.getDAO(t);return new b(e)}async importData(t,e,i,s){try{const a=await h.importDataToTable(t,e,i,s);return this._emit("dataImported",{schemaName:t,tableName:e,recordCount:a.successRows}),a}catch(a){throw this._emit("error",a,"dataImport"),a}}async importDataWithMapping(t,e,i,s,a){try{const r=await h.importDataWithMapping(t,e,i,s,a);return this._emit("dataImported",{schemaName:t,tableName:e,recordCount:r.successRows}),r}catch(r){throw this._emit("error",r,"dataImportWithMapping"),r}}async importFromCSV(t,e,i,s){try{const a=await h.importFromCSV(t,e,i,s);return this._emit("csvImported",{schemaName:t,tableName:e,recordCount:a.successRows}),a}catch(a){throw this._emit("error",a,"csvImport"),a}}async exportToCSV(t,e,i){return await this.createCSVImporter(e).exportToCSV(t,i)}async setUserRoles(t,e){this.ensureInitialized();try{await h.setCurrentUserRoles(t,e),this._emit("userRolesSet",{roles:t,primaryRole:e})}catch(i){throw this._emit("error",i,"setUserRoles"),i}}getCurrentUserRoles(){return h.getCurrentUserRoles()}getCurrentRole(){return h.getCurrentRole()}hasAccessToDatabase(t){return h.hasAccessToDatabase(t)}async executeTransaction(t,e){try{await h.executeCrossSchemaTransaction(t,e),this._emit("transactionCompleted",{schemas:t})}catch(i){throw this._emit("error",i,"transaction"),i}}async executeTransactionOnCurrent(t){const e=this.getCurrentDAO();try{await e.beginTransaction();const i=await t(e);return await e.commitTransaction(),i}catch(i){throw await e.rollbackTransaction(),i}}getEnvironment(){return g.getEnvironmentInfo()}getConnectionStatus(){return{isInitialized:this.isInitialized,currentSchema:this.currentSchema,activeConnections:h.listConnections(),connectionCount:h.getConnectionCount(),userRoles:this.getCurrentUserRoles(),primaryRole:this.getCurrentRole()}}getAvailableSchemas(){return h.getAvailableSchemas()}async healthCheck(){const t=h.getConnections(),e={};for(const[i,s]of Object.entries(t))try{await s.execute("SELECT 1"),e[i]={healthy:!0}}catch(a){e[i]={healthy:!1,error:a.message}}return e}on(t,e){return this.eventListeners.has(t)||this.eventListeners.set(t,[]),this.eventListeners.get(t).push(e),this}off(t,e){const i=this.eventListeners.get(t);if(i){const s=i.indexOf(e);s>-1&&i.splice(s,1)}return this}_emit(t,...e){const i=this.eventListeners.get(t);i&&i.forEach(s=>{try{s(...e)}catch(a){console.error("Error in event handler:",a)}})}async closeConnection(t){try{await h.closeConnection(t),this.currentSchema===t&&(this.currentSchema=null),this._emit("connectionClosed",{schemaName:t})}catch(e){throw this._emit("error",e,"closeConnection"),e}}async closeAll(){try{await h.closeAll(),this.currentSchema=null,this.isInitialized=!1,this.initializationPromise=null,this.eventListeners.clear(),this._emit("allConnectionsClosed")}catch(t){throw this._emit("error",t,"closeAll"),t}}async logout(){try{await h.logout(),this.currentSchema=null,this._emit("userLoggedOut")}catch(t){throw this._emit("error",t,"logout"),t}}static registerAdapter(t){g.registerAdapter(t)}static registerRole(t){h.registerRole(t)}static registerRoles(t){h.registerRoles(t)}ensureInitialized(){if(!this.isInitialized)throw new Error("UniversalSQLite not initialized. Call initialize() first.")}}w.instance=null;const N=(d,t)=>g.createDAO(d,t),I=async(d,t)=>await g.createFromConfig(d,t),D=async(d,t)=>await g.openExisting(d,t),A=d=>new E(d),$=(d,t)=>new class extends C{constructor(){super(d,t)}},_=d=>new R(d),M=d=>new b(d),L=async d=>{const t=w.getInstance();return await t.initialize(d.schemas,{registerAdapters:d.adapters,defaultRoles:d.defaultRoles}),d.autoConnect&&await t.connect(d.autoConnect),t},j=async(d,t)=>{const e=w.getInstance();await e.initializeFromSchema(d,{registerAdapters:t!=null&&t.adapter?[t.adapter]:void 0,autoConnect:t==null?void 0:t.autoConnect});const i=(t==null?void 0:t.autoConnect)!==!1?await e.connect(d.database_name):e.getDAO(d.database_name);return{sqlite:e,dao:i}},F=w.getInstance();export{v as BaseAdapter,C as BaseService,b as CSVImporter,g as DatabaseFactory,h as DatabaseManager,R as MigrationManager,E as QueryBuilder,O as UniversalDAO,w as UniversalSQLite,$ as createBaseService,M as createCSVImporter,I as createDatabaseFromSchema,_ as createMigrationManager,A as createQueryBuilder,j as createSingleDatabase,N as createUniversalDAO,F as default,D as openExistingDatabase,L as setupUniversalSQLite};
41
+ `,[e.version]),await this.dao.commitTransaction()}catch(s){throw await this.dao.rollbackTransaction(),s}}async reset(e={}){if(!e.force)throw new Error("Reset requires explicit force option to prevent accidental data loss");await this.dao.beginTransaction();try{const t=(await this.getAppliedMigrations()).sort((i,s)=>this.compareVersions(s.version,i.version));for(const i of t){const s=this.migrations.get(i.version);s&&await s.down(this.dao)}await this.dao.execute(`DELETE FROM ${this.migrationTable}`),await this.dao.commitTransaction()}catch(t){throw await this.dao.rollbackTransaction(),t}}async validateIntegrity(){const e=[];try{const t=await this.getAppliedMigrations();for(const i of t){const s=this.migrations.get(i.version);if(!s){e.push(`Applied migration ${i.version} not found in registered migrations`);continue}const{dependenciesMet:a,missingDependencies:n}=this.checkDependencies(s);a||e.push(`Migration ${i.version} has unmet dependencies: ${n.join(", ")}`),i.checksum&&this.generateChecksum(s)!==i.checksum&&e.push(`Migration ${i.version} has changed since it was applied (checksum mismatch)`)}return{valid:e.length===0,issues:e}}catch(t){return{valid:!1,issues:[`Error validating migration integrity: ${t.message}`]}}}async getHistory(){const e=await this.getAppliedMigrations(),t=await this.getPendingMigrations(),i={};let s=0;for(const a of e)a.category&&(i[a.category]=(i[a.category]||0)+1),s+=a.execution_time_ms||0;return{totalMigrations:this.migrations.size,appliedMigrations:e.length,pendingMigrations:t.length,categories:i,totalExecutionTime:s,averageExecutionTime:e.length>0?s/e.length:0,recentMigrations:e.slice(-10)}}static createMigrationFromSchema(e,t,i,s){const a=s||`Schema update to version ${i}`;return{version:i,description:a,up:async n=>{for(const[r,o]of Object.entries(t.schemas))if(!e.schemas[r])throw o.cols,o.description,o.indexes,o.foreign_keys,new Error("Automatic schema migration generation not fully implemented. Please create migrations manually.")},down:async n=>{throw new Error("Automatic rollback generation not fully implemented. Please create rollback manually.")}}}validateMigration(e){if(!e.version||typeof e.version!="string")throw new Error("Migration version is required and must be a string");if(!e.description||typeof e.description!="string")throw new Error("Migration description is required and must be a string");if(typeof e.up!="function")throw new Error("Migration up function is required");if(typeof e.down!="function")throw new Error("Migration down function is required");if(this.migrations.has(e.version))throw new Error(`Migration with version ${e.version} already exists`)}checkDependencies(e){if(!e.dependencies||e.dependencies.length===0)return{dependenciesMet:!0,missingDependencies:[]};const t=e.dependencies.filter(i=>!this.migrations.has(i));return{dependenciesMet:t.length===0,missingDependencies:t}}compareVersions(e,t){const i=e.split(".").map(Number),s=t.split(".").map(Number);for(let a=0;a<Math.max(i.length,s.length);a++){const n=i[a]||0,r=s[a]||0;if(n<r)return-1;if(n>r)return 1}return 0}generateChecksum(e){const t=e.up.toString()+e.down.toString();let i=0;for(let s=0;s<t.length;s++){const a=t.charCodeAt(s);i=(i<<5)-i+a,i=i&i}return i.toString(16)}}class b{constructor(e){this.dao=e}parseCSV(e,t={}){const i=Object.assign({delimiter:",",quote:'"',escape:'"',hasHeader:!0,skipEmptyLines:!0,trimWhitespace:!0},t),s={data:[],headers:[],totalRows:0,parsedRows:0,skippedRows:0,errors:[]};if(!e||e.trim().length===0)return s.errors.push({row:0,error:"CSV data is empty"}),s;try{const a=this.splitCSVLines(e,i);if(s.totalRows=a.length,a.length===0)return s.errors.push({row:0,error:"No valid lines found in CSV data"}),s;let n=0;if(i.hasHeader&&a.length>0)try{s.headers=this.parseCSVRow(a[0],i),i.trimWhitespace&&(s.headers=s.headers.map(r=>r.trim())),n=1}catch(r){return s.errors.push({row:1,error:`Failed to parse header row: ${r.message}`,rawData:a[0]}),s}else{const r=this.parseCSVRow(a[0],i);s.headers=r.map((o,l)=>`column_${l+1}`)}for(let r=n;r<a.length;r++){const o=r+1,l=a[r];if(i.skipEmptyLines&&l.trim().length===0){s.skippedRows++;continue}try{const c=this.parseCSVRow(l,i),f={};s.headers.forEach((u,m)=>{let p=c[m]||null;i.trimWhitespace&&typeof p=="string"&&(p=p.trim()),p===""&&(p=null),f[u]=p}),s.data.push(f),s.parsedRows++}catch(c){s.errors.push({row:o,error:`Failed to parse row: ${c.message}`,rawData:l}),s.skippedRows++}}return s}catch(a){return s.errors.push({row:0,error:`CSV parsing failed: ${a.message}`}),s}}async importFromCSV(e,t,i={}){const s=this.parseCSV(t,i);if(s.errors.length>0&&s.data.length===0)throw new Error(`CSV parsing failed: ${s.errors.map(c=>c.error).join("; ")}`);let a=s.data;i.startFromRow&&i.startFromRow>0&&(a=a.slice(i.startFromRow)),i.maxRows&&i.maxRows>0&&(a=a.slice(0,i.maxRows)),i.columnMappings&&(a=this.applyColumnMappings(a,i.columnMappings));const n=[],r=[];for(let c=0;c<a.length;c++){const f=a[c];let u=Object.assign({},f);try{if(i.onRowParsed){const m=i.onRowParsed(u,c);if(m===null)continue;u=m}if(i.transform){for(const[m,p]of Object.entries(i.transform))if(u.hasOwnProperty(m))try{u[m]=p(u[m],u,c)}catch(y){if(r.push({row:c+1,error:`Transform error for field '${m}': ${y.message}`}),i.onRowError){if(!i.onRowError(y,u,c))throw y;continue}throw y}}if(i.validate){for(const[m,p]of Object.entries(i.validate))if(u.hasOwnProperty(m))try{const y=p(u[m],u,c);if(y!==!0){const S=typeof y=="string"?y:`Validation failed for field '${m}'`,T=new Error(S);if(i.onRowError){if(!i.onRowError(T,u,c))throw T;continue}throw T}}catch(y){throw r.push({row:c+1,error:`Validation error for field '${m}': ${y.message}`}),y}}u=this.autoConvertTypes(u,i),n.push(u)}catch(m){if(i.onRowError&&i.onRowError(m,u,c))continue;throw m}}const o=await this.dao.importData({tableName:e,data:n,batchSize:i.batchSize||1e3,onProgress:i.onProgress,onError:i.onError,skipErrors:i.skipErrors||!1,validateData:i.validateData!==!1,updateOnConflict:i.updateOnConflict||!1,conflictColumns:i.conflictColumns,includeAutoIncrementPK:i.includeAutoIncrementPK||!1}),l=[...s.errors.map(c=>({rowIndex:c.row-1,error:c.error,rowData:c.rawData?{_raw:c.rawData}:{}})),...r.map(c=>({rowIndex:c.row-1,error:c.error,rowData:{}})),...o.errors];return Object.assign(Object.assign({},o),{errors:l,parseResult:s})}async importFromFile(e,t,i={}){let s;try{if(typeof globalThis.Deno!="undefined"&&globalThis.Deno.readTextFile)s=await globalThis.Deno.readTextFile(t);else if(typeof require!="undefined")s=await require("fs").promises.readFile(t,i.encoding||"utf8");else if(typeof t=="object"&&"text"in t)s=await t.text();else throw new Error("File reading not supported in this environment")}catch(a){throw new Error(`Failed to read CSV file '${t}': ${a.message}`)}return await this.importFromCSV(e,s,i)}async exportToCSV(e,t={}){const i=Object.assign({delimiter:",",quote:'"',includeHeaders:!0,dateFormat:"YYYY-MM-DD HH:mm:ss",nullValue:""},t);let s=`SELECT ${t.columns?t.columns.join(", "):"*"} FROM ${e}`;const a=[];t.where&&(s+=` WHERE ${t.where}`),t.orderBy&&(s+=` ORDER BY ${t.orderBy}`),t.limit&&(s+=` LIMIT ${t.limit}`);const n=await this.dao.execute(s,a);if(n.rows.length===0)return i.includeHeaders&&t.columns?this.formatCSVRow(t.columns,i):"";const r=[];if(i.includeHeaders){const o=t.columns||Object.keys(n.rows[0]);r.push(this.formatCSVRow(o,i))}for(const o of n.rows){const l=Object.values(o).map(c=>c==null?i.nullValue:c instanceof Date?this.formatDate(c,i.dateFormat):String(c));r.push(this.formatCSVRow(l,i))}return r.join(`
42
+ `)}splitCSVLines(e,t){const i=[];let s="",a=!1;for(let n=0;n<e.length;n++){const r=e[n],o=e[n+1];if(r===t.quote&&(a=!a,o===t.quote&&t.escape===t.quote)){s+=r+o,n++;continue}if(r===`
43
+ `&&!a){if(t.skipEmptyLines&&s.trim().length===0){s="";continue}i.push(s),s="",a=!1}else if(r==="\r"&&o===`
44
+ `&&!a){if(t.skipEmptyLines&&s.trim().length===0){s="",n++;continue}i.push(s),s="",n++,a=!1}else s+=r}return s.length>0&&(!t.skipEmptyLines||s.trim().length>0)&&i.push(s),i}parseCSVRow(e,t){const i=[];let s="",a=!1;for(let n=0;n<e.length;n++){const r=e[n],o=e[n+1];r===t.quote?a&&o===t.quote&&t.escape===t.quote?(s+=t.quote,n++):a=!a:r===t.delimiter&&!a?(i.push(s),s=""):s+=r}return i.push(s),i}formatCSVRow(e,t){return e.map(i=>{const s=String(i);return s.includes(t.delimiter)||s.includes(t.quote)||s.includes(`
45
+ `)||s.includes("\r")?t.quote+s.replace(new RegExp(t.quote,"g"),t.quote+t.quote)+t.quote:s}).join(t.delimiter)}applyColumnMappings(e,t){return Array.isArray(t)?e.map(i=>{const s={};return t.forEach(a=>{if(i.hasOwnProperty(a.sourceColumn)){let n=i[a.sourceColumn];a.transform&&(n=a.transform(n)),s[a.targetColumn]=n}}),s}):e.map(i=>{const s={};return Object.entries(i).forEach(([a,n])=>{const r=t[a]||a;s[r]=n}),s})}autoConvertTypes(e,t){const i={};return Object.entries(e).forEach(([s,a])=>{i[s]=this.convertValue(a,t)}),i}convertValue(e,t){if(e==null||e==="")return null;const i=String(e).trim();if(t.booleanValues){const s=i.toLowerCase();if(t.booleanValues.true.some(a=>a.toLowerCase()===s))return!0;if(t.booleanValues.false.some(a=>a.toLowerCase()===s))return!1}else{const s=i.toLowerCase();if(["true","1","yes","on"].includes(s))return!0;if(["false","0","no","off"].includes(s))return!1}if(/^-?\d+$/.test(i)){const s=parseInt(i);if(!isNaN(s))return s}if(/^-?\d*\.?\d+$/.test(i)){const s=parseFloat(i);if(!isNaN(s))return s}if(t.dateFormats)for(const s of t.dateFormats){const a=this.parseDate(i,s);if(a)return a.toISOString()}else{const s=new Date(i);if(!isNaN(s.getTime())&&i.match(/\d{4}-\d{2}-\d{2}/))return s.toISOString()}return i}parseDate(e,t){try{const i=new Date(e);return isNaN(i.getTime())?null:i}catch(i){return null}}formatDate(e,t){const i=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),a=String(e.getDate()).padStart(2,"0"),n=String(e.getHours()).padStart(2,"0"),r=String(e.getMinutes()).padStart(2,"0"),o=String(e.getSeconds()).padStart(2,"0");return t.replace("YYYY",String(i)).replace("MM",s).replace("DD",a).replace("HH",n).replace("mm",r).replace("ss",o)}static parseCSVValue(e,t={}){if(e===""||e===null)return null;const i=Object.assign({autoConvert:!0,booleanValues:{true:["true","1","yes","on"],false:["false","0","no","off"]}},t);if(!i.autoConvert)return e;const s=String(e).trim().toLowerCase();if(i.booleanValues.true.includes(s))return!0;if(i.booleanValues.false.includes(s))return!1;if(/^-?\d+$/.test(e)){const n=parseInt(e);if(!isNaN(n))return n}if(/^-?\d*\.?\d+$/.test(e)){const n=parseFloat(e);if(!isNaN(n))return n}const a=new Date(e);return!isNaN(a.getTime())&&e.match(/\d{4}-\d{2}-\d{2}/)?a.toISOString():e}static validateCSVStructure(e,t={}){const i={isValid:!0,errors:[],rowCount:0,columnCount:0,headers:[]};try{const s=new b({}).parseCSV(e,t);i.rowCount=s.totalRows,i.headers=s.headers,i.columnCount=s.headers.length,s.errors.length>0&&(i.isValid=!1,i.errors=s.errors.map(n=>n.error)),s.data.length===0&&(i.isValid=!1,i.errors.push("No valid data rows found"));const a=s.data.filter(n=>Object.keys(n).length!==i.columnCount);a.length>0&&(i.isValid=!1,i.errors.push(`${a.length} rows have inconsistent column count`))}catch(s){i.isValid=!1,i.errors.push(`Validation failed: ${s.message}`)}return i}}class v{sanitizeSQL(e){return e.trim()}bindParameters(e,t){if(!t||t.length===0)return e;let i=0;return e.replace(/\?/g,()=>{if(i<t.length){const s=t[i++];return typeof s=="string"?`'${s.replace(/'/g,"''")}'`:s==null?"NULL":String(s)}return"?"})}}class w{constructor(){if(this.currentSchema=null,this.isInitialized=!1,this.initializationPromise=null,this.eventListeners=new Map,w.instance)throw new Error("UniversalSQLite is a singleton. Use UniversalSQLite.getInstance() instead.")}static getInstance(){return w.instance||(w.instance=new w),w.instance}static resetInstance(){w.instance&&w.instance.closeAll().catch(()=>{}),w.instance=null}async initialize(e,t={}){return this.isInitialized?this.initializationPromise||Promise.resolve():this.initializationPromise?this.initializationPromise:(this.initializationPromise=this._performInitialization(e,t),this.initializationPromise)}async _performInitialization(e,t){try{t.registerAdapters&&t.registerAdapters.forEach(i=>{g.registerAdapter(i)}),t.globalErrorHandler&&this.on("error",t.globalErrorHandler),h.registerSchemas(e),e.core&&t.autoConnectCore!==!1&&await h.initializeCoreConnection(),t.defaultRoles&&t.defaultRoles.length>0&&await h.setCurrentUserRoles(t.defaultRoles),this.isInitialized=!0,this._emit("initialized",{schemas:Object.keys(e)})}catch(i){throw this.isInitialized=!1,this.initializationPromise=null,this._emit("error",i,"initialization"),i}}async initializeFromSchema(e,t={}){const i={[e.database_name]:e};return this.initialize(i,Object.assign(Object.assign({},t),{autoConnectCore:t.autoConnect!==!1}))}async connect(e){this.ensureInitialized(),this.currentSchema=e;try{const t=await h.getLazyLoading(e);return this._emit("connected",{schemaName:e}),t}catch(t){throw this._emit("error",t,"connection"),t}}getDAO(e){this.ensureInitialized();const t=e||this.currentSchema;if(!t)throw new Error("No schema specified. Use connect() first or provide schemaName parameter.");try{return h.get(t)}catch(i){throw this._emit("error",i,"getDAO"),i}}getCurrentDAO(){if(!this.currentSchema)throw new Error("No current connection. Call connect() first.");return this.getDAO(this.currentSchema)}async ensureDatabaseConnection(e){this.ensureInitialized();try{return await h.ensureDatabaseConnection(e)}catch(t){throw this._emit("error",t,"ensureConnection"),t}}createService(e,t){const i=t||this.currentSchema;if(!i)throw new Error("No schema specified. Use connect() first or provide schemaName parameter.");const s=class extends C{constructor(){if(!i)throw new Error("No schema specified. Use connect() first or provide schemaName parameter.");super(i,e)}};return new s}createServices(e,t){const i={};return e.forEach(s=>{i[s]=this.createService(s,t)}),i}query(e,t){const i=this.getDAO(t);return e?E.table(e,i):new E(i)}table(e,t){return this.query(e,t)}async execute(e,t,i){try{const s=await this.getDAO(i).execute(e,t);return this._emit("queryExecuted",{sql:e,params:t,rowCount:s.rowsAffected}),s}catch(s){throw this._emit("error",s,"execute"),s}}async getRst(e,t,i){return await this.getDAO(i).getRst(e,t)}async getRsts(e,t,i){return await this.getDAO(i).getRsts(e,t)}async initializeSchema(e,t=!1){try{await(await g.createOrOpen({config:e},t)).initializeFromSchema(e),this._emit("schemaInitialized",{schemaName:e.database_name})}catch(i){throw this._emit("error",i,"schemaInitialization"),i}}async getSchemaVersion(e){return await this.getDAO(e).getSchemaVersion()}async getDatabaseInfo(e){return await this.getDAO(e).getDatabaseInfo()}async getTableInfo(e,t){return await this.getDAO(t).getTableInfo(e)}createMigrationManager(e){const t=this.getDAO(e);return new R(t)}async runMigrations(e,t,i){const s=this.createMigrationManager(t);e.forEach(a=>{s.addMigration(a)}),await s.migrate(i),this._emit("migrationsCompleted",{schemaName:t||this.currentSchema})}createCSVImporter(e){const t=this.getDAO(e);return new b(t)}async importData(e,t,i,s){try{const a=await h.importDataToTable(e,t,i,s);return this._emit("dataImported",{schemaName:e,tableName:t,recordCount:a.successRows}),a}catch(a){throw this._emit("error",a,"dataImport"),a}}async importDataWithMapping(e,t,i,s,a){try{const n=await h.importDataWithMapping(e,t,i,s,a);return this._emit("dataImported",{schemaName:e,tableName:t,recordCount:n.successRows}),n}catch(n){throw this._emit("error",n,"dataImportWithMapping"),n}}async importFromCSV(e,t,i,s){try{const a=await h.importFromCSV(e,t,i,s);return this._emit("csvImported",{schemaName:e,tableName:t,recordCount:a.successRows}),a}catch(a){throw this._emit("error",a,"csvImport"),a}}async exportToCSV(e,t,i){return await this.createCSVImporter(t).exportToCSV(e,i)}async setUserRoles(e,t){this.ensureInitialized();try{await h.setCurrentUserRoles(e,t),this._emit("userRolesSet",{roles:e,primaryRole:t})}catch(i){throw this._emit("error",i,"setUserRoles"),i}}getCurrentUserRoles(){return h.getCurrentUserRoles()}getCurrentRole(){return h.getCurrentRole()}hasAccessToDatabase(e){return h.hasAccessToDatabase(e)}async executeTransaction(e,t){try{await h.executeCrossSchemaTransaction(e,t),this._emit("transactionCompleted",{schemas:e})}catch(i){throw this._emit("error",i,"transaction"),i}}async executeTransactionOnCurrent(e){const t=this.getCurrentDAO();try{await t.beginTransaction();const i=await e(t);return await t.commitTransaction(),i}catch(i){throw await t.rollbackTransaction(),i}}getEnvironment(){return g.getEnvironmentInfo()}getConnectionStatus(){return{isInitialized:this.isInitialized,currentSchema:this.currentSchema,activeConnections:h.listConnections(),connectionCount:h.getConnectionCount(),userRoles:this.getCurrentUserRoles(),primaryRole:this.getCurrentRole()}}getAvailableSchemas(){return h.getAvailableSchemas()}async healthCheck(){const e=h.getConnections(),t={};for(const[i,s]of Object.entries(e))try{await s.execute("SELECT 1"),t[i]={healthy:!0}}catch(a){t[i]={healthy:!1,error:a.message}}return t}on(e,t){return this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t),this}off(e,t){const i=this.eventListeners.get(e);if(i){const s=i.indexOf(t);s>-1&&i.splice(s,1)}return this}_emit(e,...t){const i=this.eventListeners.get(e);i&&i.forEach(s=>{try{s(...t)}catch(a){console.error("Error in event handler:",a)}})}async closeConnection(e){try{await h.closeConnection(e),this.currentSchema===e&&(this.currentSchema=null),this._emit("connectionClosed",{schemaName:e})}catch(t){throw this._emit("error",t,"closeConnection"),t}}async closeAll(){try{await h.closeAll(),this.currentSchema=null,this.isInitialized=!1,this.initializationPromise=null,this.eventListeners.clear(),this._emit("allConnectionsClosed")}catch(e){throw this._emit("error",e,"closeAll"),e}}async logout(){try{await h.logout(),this.currentSchema=null,this._emit("userLoggedOut")}catch(e){throw this._emit("error",e,"logout"),e}}static registerAdapter(e){g.registerAdapter(e)}static registerRole(e){h.registerRole(e)}static registerRoles(e){h.registerRoles(e)}ensureInitialized(){if(!this.isInitialized)throw new Error("UniversalSQLite not initialized. Call initialize() first.")}}w.instance=null;const I=(d,e)=>g.createDAO(d,e),N=async(d,e)=>await g.createFromConfig(d,e),D=async(d,e)=>await g.openExisting(d,e),A=d=>new E(d),$=(d,e)=>new class extends C{constructor(){super(d,e)}},_=d=>new R(d),M=d=>new b(d),L=async d=>{const e=w.getInstance();return await e.initialize(d.schemas,{registerAdapters:d.adapters,defaultRoles:d.defaultRoles}),d.autoConnect&&await e.connect(d.autoConnect),e},j=async(d,e)=>{const t=w.getInstance();await t.initializeFromSchema(d,{registerAdapters:e!=null&&e.adapter?[e.adapter]:void 0,autoConnect:e==null?void 0:e.autoConnect});const i=(e==null?void 0:e.autoConnect)!==!1?await t.connect(d.database_name):t.getDAO(d.database_name);return{sqlite:t,dao:i}},F=w.getInstance();export{v as BaseAdapter,C as BaseService,b as CSVImporter,g as DatabaseFactory,h as DatabaseManager,R as MigrationManager,E as QueryBuilder,O as UniversalDAO,w as UniversalSQLite,$ as createBaseService,M as createCSVImporter,N as createDatabaseFromSchema,_ as createMigrationManager,A as createQueryBuilder,j as createSingleDatabase,I as createUniversalDAO,F as default,D as openExistingDatabase,L as setupUniversalSQLite};
46
46
  //# sourceMappingURL=index.mjs.map