@dqcai/sqlite 2.0.0 → 2.0.2
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/README.md +1612 -361
- package/lib/core/base-service.d.ts +1 -14
- package/lib/core/base-service.d.ts.map +1 -1
- package/lib/core/database-manager.d.ts.map +1 -1
- package/lib/index.js +1 -1
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +2 -2
- package/lib/index.mjs.map +1 -1
- package/lib/index.umd.js +1 -1
- package/lib/index.umd.js.map +1 -1
- package/lib/types.d.ts +16 -0
- package/lib/types.d.ts.map +1 -1
- package/package.json +2 -3
package/lib/index.mjs
CHANGED
|
@@ -10,7 +10,7 @@ ${i}`)}return this.isInitialized=!0,!0}static async initLazySchema(t){const e=t.
|
|
|
10
10
|
`);throw new Error(`Failed to initialize one or more databases:
|
|
11
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(`
|
|
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);let s=null;return i.lastInsertRowId?s=await this.findById(i.lastInsertRowId):t[this.primaryKeyFields[0]]?s=await this.findById(t[this.primaryKeyFields[0]]):s=t,this._emit("dataCreated",{operation:"create",data:s}),s}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(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=`
|
|
14
14
|
CREATE TABLE IF NOT EXISTS ${this.migrationTable} (
|
|
15
15
|
version TEXT PRIMARY KEY,
|
|
16
16
|
description TEXT NOT NULL,
|
|
@@ -42,5 +42,5 @@ ${a.conflicts.join(`
|
|
|
42
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
43
|
`&&!a){if(e.skipEmptyLines&&s.trim().length===0){s="";continue}i.push(s),s="",a=!1}else if(n==="\r"&&o===`
|
|
44
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 I=(d,t)=>g.createDAO(d,t),N=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,N as createDatabaseFromSchema,_ as createMigrationManager,A as createQueryBuilder,j as createSingleDatabase,I as createUniversalDAO,F as default,D as openExistingDatabase,L as setupUniversalSQLite};
|
|
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};
|
|
46
46
|
//# sourceMappingURL=index.mjs.map
|