@dqcai/sqlite 3.0.1 → 3.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/lib/index.js +1 -1
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +1 -1
- package/lib/index.mjs.map +1 -1
- package/lib/index.umd.js +1 -1
- package/lib/index.umd.js.map +1 -1
- package/lib/logger/logger-config.d.ts.map +1 -1
- package/package.json +1 -1
package/lib/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const R=(...h)=>h.map(e=>typeof e=="object"?JSON.stringify(e,null,2):String(e)).join(" ");class L{constructor(e){this.transports=new Map,this.transportFactory=null,this.config=e,this.sessionId=e.sessionId||this.generateSessionId()}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}getSessionId(){return this.sessionId}renewSession(){return this.sessionId=this.generateSessionId(),this.sessionId}setTransportFactory(e){this.transportFactory=e}addTransport(e){this.transports.set(e.name,e)}removeTransport(e){return this.transports.delete(e)}getTransport(e){return this.transports.get(e)}listTransports(){return Array.from(this.transports.keys())}setModuleConfig(e,t){this.config.modules[e]=t}getModuleConfig(e){return this.config.modules[e]}setGlobalEnabled(e){this.config.enabled=e}isGlobalEnabled(){return this.config.enabled}setDefaultLevel(e){this.config.defaultLevel=e}getConfig(){return JSON.parse(JSON.stringify(this.config))}setMetadata(e){this.config.metadata=Object.assign(Object.assign({},this.config.metadata),e)}shouldLog(e,t){if(!this.config.enabled)return!1;const a=this.config.modules[e];return a?a.enabled&&a.levels.includes(t):this.isLevelEnabled(t,this.config.defaultLevel)}isLevelEnabled(e,t){const a=["trace","debug","info","warn","error"],s=a.indexOf(e),r=a.indexOf(t);return s===-1||r===-1?!1:s>=r}getTransportsForModule(e){const t=this.config.modules[e];return((t==null?void 0:t.transports)||["console"]).map(a=>this.transports.get(a)).filter(a=>a!==void 0)}async sendToTransports(e,t){if(t.length===0)return;const a=t.map(async s=>{try{await s.log(e)}catch(r){console.error(`[UniversalLogger] Transport ${s.name} failed:`,r)}});await Promise.allSettled(a)}async log(e,t,a,s){if(!this.shouldLog(e,t))return;const r={timestamp:new Date().toISOString(),level:t,module:e,message:a,data:s,metadata:this.config.metadata,sessionId:this.sessionId},i=this.getTransportsForModule(e);await this.sendToTransports(r,i)}async trace(e,...t){const a=R(...t);await this.log(e,"trace",a)}async debug(e,...t){const a=R(...t);await this.log(e,"debug",a)}async info(e,...t){const a=R(...t);await this.log(e,"info",a)}async warn(e,...t){const a=R(...t);await this.log(e,"warn",a)}async error(e,...t){const a=R(...t);await this.log(e,"error",a)}async flush(){const e=Array.from(this.transports.values()).filter(t=>typeof t.flush=="function").map(t=>t.flush());await Promise.allSettled(e)}async cleanup(){const e=Array.from(this.transports.values()).filter(t=>typeof t.cleanup=="function").map(t=>t.cleanup());await Promise.allSettled(e)}createModuleLogger(e){return new M(e,this)}}class M{constructor(e,t){this.module=e,this.logger=t}async flush(){await this.logger.flush()}async trace(...e){const t=R(...e);await this.logger.trace(this.module,t)}async debug(...e){const t=R(...e);await this.logger.debug(this.module,t)}async info(...e){const t=R(...e);await this.logger.info(this.module,t)}async warn(...e){const t=R(...e);await this.logger.warn(this.module,t)}async error(...e){const t=R(...e);await this.logger.error(this.module,t)}getModuleName(){return this.module}}class ${constructor(e={}){this.name="console",this.config=Object.assign({colorize:!0,timestamp:!0,prefix:""},e)}log(e){const t=[];this.config.timestamp&&t.push(`[${e.timestamp}]`),this.config.prefix&&t.push(`[${this.config.prefix}]`),t.push(`[${e.module}]`,`[${e.level.toUpperCase()}]`,e.message);const a=t.join(" "),s=e.data?[e.data]:[];this.config.colorize?this.logWithColor(e.level,a,s):this.logWithoutColor(e.level,a,s)}logWithColor(e,t,a){const s={trace:"#999999",debug:"#0066cc",info:"#00cc66",warn:"#ff9900",error:"#cc0000"}[e];console.log(`%c${t}`,`color: ${s}`,...a)}logWithoutColor(e,t,a){switch(e){case"error":console.error(t,...a);break;case"warn":console.warn(t,...a);break;case"info":console.info(t,...a);break;default:console.log(t,...a)}}}class T{constructor(){this.config={enabled:!0,defaultLevel:"info",modules:{}}}setEnabled(e){return this.config.enabled=e,this}setDefaultLevel(e){return this.config.defaultLevel=e,this}setSessionId(e){return this.config.sessionId=e,this}setMetadata(e){return this.config.metadata=e,this}addModule(e,t=!0,a=["info","warn","error"],s=["console"]){return this.config.modules[e]={enabled:t,levels:a,transports:s},this}build(){return JSON.parse(JSON.stringify(this.config))}}class k{static createDevelopmentConfig(){return new T().setEnabled(!0).setDefaultLevel("debug").addModule("DatabaseManager",!0,["debug","info","warn","error"],["console"]).addModule("ApiClient",!0,["info","warn","error"],["console"]).addModule("Cache",!0,["debug","info","warn","error"],["console"]).build()}static createProductionConfig(){return new T().setEnabled(!0).setDefaultLevel("warn").addModule("DatabaseManager",!0,["error"],["console"]).addModule("ApiClient",!0,["warn","error"],["console"]).addModule("Cache",!1,[],[]).build()}static createCustomConfig(e=!1){return e?k.createDevelopmentConfig():k.createProductionConfig()}}const _=h=>{const e=h||k.createDevelopmentConfig(),t=new L(e);return t.addTransport(new $),t};var b;(function(h){h.DATABASE_MANAGER="DatabaseManager",h.DATABASE_FACTORY="DatabaseFactory",h.UNIVERSAL_DAO="UniversalDAO",h.BASE_SERVICE="BaseService",h.SERVICE_MANAGER="ServiceManager",h.QUERY_BUILDER="QueryBuilder",h.BASE_ADAPTER="BaseAdapter",h.UNIVERSAL_SQLITE="UniversalSQLite",h.TRANSACTION="Transaction",h.CONNECTION="Connection"})(b||(b={}));class u{static createDefaultConfig(){return new T().setEnabled(!1).setDefaultLevel("trace").addModule(b.UNIVERSAL_SQLITE,!0,["warn","error"],["console"]).addModule(b.DATABASE_MANAGER,!0,["debug","info","warn","error"],["console"]).addModule(b.DATABASE_FACTORY,!0,["debug","info","warn","error"],["console"]).addModule(b.UNIVERSAL_DAO,!1,["warn","error"],["console"]).addModule(b.BASE_SERVICE,!1,["trace","debug","info","warn","error"],["console"]).addModule(b.SERVICE_MANAGER,!1,["info","warn","error"],["console"]).addModule(b.QUERY_BUILDER,!1,["debug","info","warn","error"],["console"]).addModule(b.BASE_ADAPTER,!1,["debug","info","warn","error"],["console"]).build()}static initialize(e){const t=e||u.createDefaultConfig();return u.currentConfig=t,t.enabled&&(t.defaultLevel==="trace"||t.defaultLevel==="debug")&&console.debug("SQLiteLoggerConfig.initialize()",JSON.stringify(t,null,2)),u.instance=_(t),u.instance}static getInstance(){return u.currentConfig&&u.currentConfig.enabled&&(u.currentConfig.defaultLevel==="trace"||u.currentConfig.defaultLevel==="debug")&&console.debug("SQLiteLoggerConfig.getInstance()",JSON.stringify(u.currentConfig,null,2)),u.instance?u.instance:u.initialize()}static updateConfiguration(e){e&&e.enabled&&(e.defaultLevel==="trace"||e.defaultLevel==="debug")&&console.debug("SQLiteLoggerConfig.updateConfiguration()",JSON.stringify(e,null,2)),u.currentConfig=e,u.instance=_(e),e&&e.enabled&&(e.defaultLevel==="trace"||e.defaultLevel==="debug"||e.defaultLevel==="info")&&console.log("SQLiteLoggerConfig.updateConfiguration()",JSON.stringify(u.instance,null,2))}static setEnabled(e){u.currentConfig&&(u.currentConfig.enabled=e,u.updateConfiguration(u.currentConfig))}static enableModule(e,t,a){u.currentConfig&&u.currentConfig.modules&&(u.currentConfig.modules[e]={enabled:!0,levels:t||["debug","info","warn","error"],appenders:a||["console"]},u.updateConfiguration(u.currentConfig))}static disableModule(e){u.currentConfig&&u.currentConfig.modules&&(u.currentConfig.modules[e]={enabled:!1},u.updateConfiguration(u.currentConfig))}static createDebugConfig(){return new T().setEnabled(!0).setDefaultLevel("trace").addModule(b.UNIVERSAL_SQLITE,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.DATABASE_MANAGER,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.DATABASE_FACTORY,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.UNIVERSAL_DAO,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.BASE_SERVICE,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.SERVICE_MANAGER,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.QUERY_BUILDER,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.BASE_ADAPTER,!0,["trace","debug","info","warn","error"],["console"]).build()}static createProductionConfig(){return new T().setEnabled(!0).setDefaultLevel("warn").addModule(b.UNIVERSAL_SQLITE,!0,["error"],["console"]).addModule(b.DATABASE_MANAGER,!0,["warn","error"],["console"]).addModule(b.DATABASE_FACTORY,!0,["warn","error"],["console"]).addModule(b.UNIVERSAL_DAO,!0,["error"],["console"]).addModule(b.BASE_SERVICE,!0,["error"],["console"]).addModule(b.SERVICE_MANAGER,!0,["error"],["console"]).addModule(b.QUERY_BUILDER,!0,["error"],["console"]).addModule(b.BASE_ADAPTER,!0,["warn","error"],["console"]).build()}static reset(){return u.initialize()}}u.instance=null,u.currentConfig=null;const z=u.getInstance(),w=h=>{const e=u.getInstance();return{trace:(t,...a)=>e.trace(h,t,...a),debug:(t,...a)=>e.debug(h,t,...a),info:(t,...a)=>e.info(h,t,...a),warn:(t,...a)=>e.warn(h,t,...a),error:(t,...a)=>e.error(h,t,...a)}};class F{constructor(e,t,a){var s,r;this.adapter=e,this.dbPath=t,this.options=a,this.connection=null,this.isConnected=!1,this.inTransaction=!1,this.typeMappingConfig=null,this.createIfNotExists=!1,this.forceRecreate=!1,this.logger=w(b.UNIVERSAL_DAO),this.createIfNotExists=(s=a==null?void 0:a.createIfNotExists)!==null&&s!==void 0?s:!1,this.forceRecreate=(r=a==null?void 0:a.forceRecreate)!==null&&r!==void 0?r:!1,this.logger.trace("UniversalDAO constructor initialized",{dbPath:this.dbPath,createIfNotExists:this.createIfNotExists,forceRecreate:this.forceRecreate})}async connect(){if(this.logger.trace("Attempting to connect to database",{dbPath:this.dbPath}),this.isConnected){this.logger.debug("Already connected to database, skipping connection");return}try{this.connection=await this.adapter.connect(this.dbPath),this.isConnected=!0,this.logger.info("Successfully connected to database",{dbPath:this.dbPath})}catch(e){throw this.logger.error("Failed to connect to database",{dbPath:this.dbPath,error:e instanceof Error?e.message:String(e)}),e}}async disconnect(){if(this.logger.trace("Attempting to disconnect from database"),this.connection&&this.isConnected)try{await this.connection.close(),this.connection=null,this.isConnected=!1,this.logger.info("Successfully disconnected from database")}catch(e){throw this.logger.error("Error during database disconnection",{error:e instanceof Error?e.message:String(e)}),e}else this.logger.debug("Database was not connected, nothing to disconnect")}async close(){this.logger.trace("Closing database connection"),await this.disconnect()}setTypeMappingConfig(e){this.logger.trace("Setting type mapping configuration",{config:e}),this.typeMappingConfig=e,this.logger.debug("Type mapping configuration updated")}convertToSQLiteType(e){if(this.logger.trace("Converting generic type to SQLite type",{genericType:e}),!this.typeMappingConfig||!this.typeMappingConfig.sqlite){const a=this.getDefaultSQLiteType(e);return this.logger.debug("Using default type mapping",{genericType:e,sqliteType:a}),a}const t=this.typeMappingConfig.sqlite[e.toLowerCase()]||"TEXT";return this.logger.debug("Using custom type mapping",{genericType:e,sqliteType:t}),t}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){this.logger.trace("Processing column definition",{columnName:e.name,originalType:e.type});const t=Object.assign({},e);t.type=this.convertToSQLiteType(e.type);const a=[];if(e.constraints){this.logger.trace("Processing column constraints",{columnName:e.name,constraints:e.constraints});const s=e.constraints.toUpperCase().split(" ");s.includes("PRIMARY")&&(a.push("PRIMARY KEY"),t.primary_key=!0),(s.includes("AUTO_INCREMENT")||s.includes("AUTOINCREMENT"))&&(t.primary_key&&a.push("AUTOINCREMENT"),t.auto_increment=!0),s.includes("NOT")&&s.includes("NULL")&&(a.push("NOT NULL"),t.nullable=!1),s.includes("UNIQUE")&&(t.primary_key||a.push("UNIQUE"),t.unique=!0);const r=s.indexOf("DEFAULT");if(r!==-1&&s.length>r+1){const i=s[r+1];a.push(`DEFAULT ${i}`),t.default=i}}return t.option_key=a.join(" ").trim(),this.logger.debug("Column definition processed",{columnName:e.name,finalType:t.type,options:t.option_key}),t}async initializeFromSchema(e){var t,a;this.logger.info("Initializing database schema",{schemaVersion:e.version,tableCount:Object.keys(e.schemas).length}),this.ensureConnected();let s=!1;try{const r=await this.execute("SELECT version FROM _schema_info ORDER BY applied_at DESC LIMIT 1");s=r.rows.length>0,s&&this.logger.debug("Existing schema detected",{currentVersion:(t=r.rows[0])===null||t===void 0?void 0:t.version})}catch(r){this.logger.debug("No existing schema found or schema info table missing"),s=!1}if(s&&!this.createIfNotExists&&!this.forceRecreate){this.logger.info("Schema exists and no recreation options set, using existing schema"),e.type_mapping&&this.setTypeMappingConfig(e.type_mapping);return}s&&this.forceRecreate&&(this.logger.warn("Force recreate option enabled, dropping all existing tables"),await this.dropAllTables()),e.type_mapping&&this.setTypeMappingConfig(e.type_mapping);try{this.logger.debug("Enabling foreign key constraints"),await this.execute("PRAGMA foreign_keys = ON")}catch(r){this.logger.warn("Failed to enable foreign key constraints",{error:r instanceof Error?r.message:String(r)})}await this.beginTransaction();try{this.logger.info("Creating tables from schema");for(const[r,i]of Object.entries(e.schemas)){this.logger.debug("Creating table",{tableName:r,columnCount:i.cols.length});const o={name:r,cols:i.cols.map(l=>this.processColumnDefinition(l)),description:i.description,indexes:i.indexes,foreign_keys:i.foreign_keys};await this.createTableWithForeignKeys(o)}this.logger.info("Creating indexes for tables");for(const[r,i]of Object.entries(e.schemas))!((a=i.indexes)===null||a===void 0)&&a.length&&(this.logger.debug("Creating indexes for table",{tableName:r,indexCount:i.indexes.length}),await this.createIndexesForTable(r,i.indexes));await this.setSchemaVersion(e.version),await this.commitTransaction(),this.logger.info("Schema initialization completed successfully",{version:e.version})}catch(r){throw this.logger.error("Schema initialization failed, rolling back transaction",{error:r instanceof Error?r.message:String(r)}),await this.rollbackTransaction(),r}}async dropAllTables(){this.logger.info("Dropping all existing tables");const e=await this.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");this.logger.debug("Found tables to drop",{tableCount:e.rows.length}),await this.beginTransaction();try{for(const t of e.rows)this.logger.trace("Dropping table",{tableName:t.name}),await this.execute(`DROP TABLE IF EXISTS ${t.name}`);await this.commitTransaction(),this.logger.info("All tables dropped successfully")}catch(t){throw this.logger.error("Failed to drop tables, rolling back",{error:t instanceof Error?t.message:String(t)}),await this.rollbackTransaction(),t}}async createTableWithForeignKeys(e){this.logger.trace("Creating table with foreign keys",{tableName:e.name});const t=e.cols.map(i=>`${i.name} ${i.type} ${i.option_key||""}`.trim()),a=[];if(e.foreign_keys){this.logger.debug("Processing foreign keys",{tableName:e.name,fkCount:e.foreign_keys.length});for(const i of e.foreign_keys){let o=`FOREIGN KEY (${i.column}) REFERENCES ${i.references.table}(${i.references.column})`;i.on_delete&&(o+=` ON DELETE ${i.on_delete}`),i.on_update&&(o+=` ON UPDATE ${i.on_update}`),a.push(o)}}const s=[...t,...a],r=`CREATE TABLE IF NOT EXISTS ${e.name} (${s.join(", ")})`;try{await this.execute(r),this.logger.debug("Table created successfully",{tableName:e.name})}catch(i){throw this.logger.error("Failed to create table",{tableName:e.name,sql:r,error:i instanceof Error?i.message:String(i)}),i}}async createIndexesForTable(e,t){this.logger.trace("Creating indexes for table",{tableName:e,indexCount:t.length});for(const a of t){const s=a.columns.join(", "),r=a.unique||!1,i=`CREATE ${r?"UNIQUE":""} INDEX IF NOT EXISTS ${a.name} ON ${e} (${s})`;try{await this.execute(i),this.logger.debug("Index created successfully",{indexName:a.name,tableName:e,columns:a.columns,unique:r})}catch(o){throw this.logger.error("Failed to create index",{indexName:a.name,tableName:e,sql:i,error:o instanceof Error?o.message:String(o)}),o}}}async beginTransaction(){if(this.logger.trace("Beginning transaction"),this.inTransaction){const e=new Error("Transaction already in progress");throw this.logger.error("Cannot begin transaction",{error:e.message}),e}try{await this.execute("BEGIN TRANSACTION"),this.inTransaction=!0,this.logger.debug("Transaction started successfully")}catch(e){throw this.logger.error("Failed to begin transaction",{error:e instanceof Error?e.message:String(e)}),e}}async commitTransaction(){if(this.logger.trace("Committing transaction"),!this.inTransaction){const e=new Error("No transaction in progress");throw this.logger.error("Cannot commit transaction",{error:e.message}),e}try{await this.execute("COMMIT"),this.inTransaction=!1,this.logger.debug("Transaction committed successfully")}catch(e){throw this.logger.error("Failed to commit transaction",{error:e instanceof Error?e.message:String(e)}),e}}async rollbackTransaction(){if(this.logger.trace("Rolling back transaction"),!this.inTransaction){const e=new Error("No transaction in progress");throw this.logger.error("Cannot rollback transaction",{error:e.message}),e}try{await this.execute("ROLLBACK"),this.inTransaction=!1,this.logger.debug("Transaction rolled back successfully")}catch(e){throw this.logger.error("Failed to rollback transaction",{error:e instanceof Error?e.message:String(e)}),e}}async getSchemaVersion(){this.logger.trace("Getting schema version");try{const e=(await this.getRst("SELECT version FROM _schema_info ORDER BY applied_at DESC LIMIT 1")).version||"0";return this.logger.debug("Schema version retrieved",{version:e}),e}catch(e){return this.logger.debug("No schema version found, returning default",{defaultVersion:"0"}),"0"}}async setSchemaVersion(e){this.logger.trace("Setting schema version",{version:e});try{await this.execute(`CREATE TABLE IF NOT EXISTS _schema_info (
|
|
1
|
+
const R=(...h)=>h.map(e=>typeof e=="object"?JSON.stringify(e,null,2):String(e)).join(" ");class M{constructor(e){this.transports=new Map,this.transportFactory=null,this.config=e,this.sessionId=e.sessionId||this.generateSessionId()}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}getSessionId(){return this.sessionId}renewSession(){return this.sessionId=this.generateSessionId(),this.sessionId}setTransportFactory(e){this.transportFactory=e}addTransport(e){this.transports.set(e.name,e)}removeTransport(e){return this.transports.delete(e)}getTransport(e){return this.transports.get(e)}listTransports(){return Array.from(this.transports.keys())}setModuleConfig(e,t){this.config.modules[e]=t}getModuleConfig(e){return this.config.modules[e]}setGlobalEnabled(e){this.config.enabled=e}isGlobalEnabled(){return this.config.enabled}setDefaultLevel(e){this.config.defaultLevel=e}getConfig(){return JSON.parse(JSON.stringify(this.config))}setMetadata(e){this.config.metadata=Object.assign(Object.assign({},this.config.metadata),e)}shouldLog(e,t){if(!this.config.enabled)return!1;const a=this.config.modules[e];return a?a.enabled&&a.levels.includes(t):this.isLevelEnabled(t,this.config.defaultLevel)}isLevelEnabled(e,t){const a=["trace","debug","info","warn","error"],s=a.indexOf(e),r=a.indexOf(t);return s===-1||r===-1?!1:s>=r}getTransportsForModule(e){const t=this.config.modules[e];return((t==null?void 0:t.transports)||["console"]).map(a=>this.transports.get(a)).filter(a=>a!==void 0)}async sendToTransports(e,t){if(t.length===0)return;const a=t.map(async s=>{try{await s.log(e)}catch(r){console.error(`[UniversalLogger] Transport ${s.name} failed:`,r)}});await Promise.allSettled(a)}async log(e,t,a,s){if(!this.shouldLog(e,t))return;const r={timestamp:new Date().toISOString(),level:t,module:e,message:a,data:s,metadata:this.config.metadata,sessionId:this.sessionId},i=this.getTransportsForModule(e);await this.sendToTransports(r,i)}async trace(e,...t){const a=R(...t);await this.log(e,"trace",a)}async debug(e,...t){const a=R(...t);await this.log(e,"debug",a)}async info(e,...t){const a=R(...t);await this.log(e,"info",a)}async warn(e,...t){const a=R(...t);await this.log(e,"warn",a)}async error(e,...t){const a=R(...t);await this.log(e,"error",a)}async flush(){const e=Array.from(this.transports.values()).filter(t=>typeof t.flush=="function").map(t=>t.flush());await Promise.allSettled(e)}async cleanup(){const e=Array.from(this.transports.values()).filter(t=>typeof t.cleanup=="function").map(t=>t.cleanup());await Promise.allSettled(e)}createModuleLogger(e){return new L(e,this)}}class L{constructor(e,t){this.module=e,this.logger=t}async flush(){await this.logger.flush()}async trace(...e){const t=R(...e);await this.logger.trace(this.module,t)}async debug(...e){const t=R(...e);await this.logger.debug(this.module,t)}async info(...e){const t=R(...e);await this.logger.info(this.module,t)}async warn(...e){const t=R(...e);await this.logger.warn(this.module,t)}async error(...e){const t=R(...e);await this.logger.error(this.module,t)}getModuleName(){return this.module}}class ${constructor(e={}){this.name="console",this.config=Object.assign({colorize:!0,timestamp:!0,prefix:""},e)}log(e){const t=[];this.config.timestamp&&t.push(`[${e.timestamp}]`),this.config.prefix&&t.push(`[${this.config.prefix}]`),t.push(`[${e.module}]`,`[${e.level.toUpperCase()}]`,e.message);const a=t.join(" "),s=e.data?[e.data]:[];this.config.colorize?this.logWithColor(e.level,a,s):this.logWithoutColor(e.level,a,s)}logWithColor(e,t,a){const s={trace:"#999999",debug:"#0066cc",info:"#00cc66",warn:"#ff9900",error:"#cc0000"}[e];console.log(`%c${t}`,`color: ${s}`,...a)}logWithoutColor(e,t,a){switch(e){case"error":console.error(t,...a);break;case"warn":console.warn(t,...a);break;case"info":console.info(t,...a);break;default:console.log(t,...a)}}}class T{constructor(){this.config={enabled:!0,defaultLevel:"info",modules:{}}}setEnabled(e){return this.config.enabled=e,this}setDefaultLevel(e){return this.config.defaultLevel=e,this}setSessionId(e){return this.config.sessionId=e,this}setMetadata(e){return this.config.metadata=e,this}addModule(e,t=!0,a=["info","warn","error"],s=["console"]){return this.config.modules[e]={enabled:t,levels:a,transports:s},this}build(){return JSON.parse(JSON.stringify(this.config))}}class k{static createDevelopmentConfig(){return new T().setEnabled(!0).setDefaultLevel("debug").addModule("DatabaseManager",!0,["debug","info","warn","error"],["console"]).addModule("ApiClient",!0,["info","warn","error"],["console"]).addModule("Cache",!0,["debug","info","warn","error"],["console"]).build()}static createProductionConfig(){return new T().setEnabled(!0).setDefaultLevel("warn").addModule("DatabaseManager",!0,["error"],["console"]).addModule("ApiClient",!0,["warn","error"],["console"]).addModule("Cache",!1,[],[]).build()}static createCustomConfig(e=!1){return e?k.createDevelopmentConfig():k.createProductionConfig()}}const _=h=>{const e=h||k.createDevelopmentConfig(),t=new M(e);return t.addTransport(new $),t};var b;(function(h){h.DATABASE_MANAGER="DatabaseManager",h.DATABASE_FACTORY="DatabaseFactory",h.UNIVERSAL_DAO="UniversalDAO",h.BASE_SERVICE="BaseService",h.SERVICE_MANAGER="ServiceManager",h.QUERY_BUILDER="QueryBuilder",h.BASE_ADAPTER="BaseAdapter",h.UNIVERSAL_SQLITE="UniversalSQLite",h.TRANSACTION="Transaction",h.CONNECTION="Connection"})(b||(b={}));class u{static createDefaultConfig(){return new T().setEnabled(!0).setDefaultLevel("warn").addModule(b.UNIVERSAL_SQLITE,!0,["warn","error"],["console"]).addModule(b.DATABASE_MANAGER,!0,["debug","info","warn","error"],["console"]).addModule(b.DATABASE_FACTORY,!0,["debug","info","warn","error"],["console"]).addModule(b.UNIVERSAL_DAO,!0,["warn","error"],["console"]).addModule(b.BASE_SERVICE,!0,["warn","error"],["console"]).addModule(b.SERVICE_MANAGER,!0,["warn","error"],["console"]).addModule(b.QUERY_BUILDER,!0,["warn","error"],["console"]).addModule(b.BASE_ADAPTER,!0,["warn","error"],["console"]).build()}static initialize(e){const t=e||u.createDefaultConfig();return u.currentConfig=t,t.enabled&&console.debug("SQLiteLoggerConfig.initialize()",JSON.stringify(t,null,2)),u.instance=_(t),u.instance}static getInstance(){return u.currentConfig&&u.currentConfig.enabled&&(u.currentConfig.defaultLevel==="trace"||u.currentConfig.defaultLevel==="debug")&&console.debug("SQLiteLoggerConfig.getInstance()",JSON.stringify(u.currentConfig,null,2)),u.instance?u.instance:u.initialize()}static updateConfiguration(e){e&&e.enabled&&(e.defaultLevel==="trace"||e.defaultLevel==="debug")&&console.debug("SQLiteLoggerConfig.updateConfiguration()",JSON.stringify(e,null,2)),u.currentConfig=e,u.instance=_(e),e&&e.enabled&&(e.defaultLevel==="trace"||e.defaultLevel==="debug"||e.defaultLevel==="info")&&console.log("SQLiteLoggerConfig.updateConfiguration()",JSON.stringify(u.instance,null,2))}static setEnabled(e){u.currentConfig&&(u.currentConfig.enabled=e,u.updateConfiguration(u.currentConfig))}static enableModule(e,t,a){u.currentConfig&&u.currentConfig.modules&&(u.currentConfig.modules[e]={enabled:!0,levels:t||["debug","info","warn","error"],appenders:a||["console"]},u.updateConfiguration(u.currentConfig))}static disableModule(e){u.currentConfig&&u.currentConfig.modules&&(u.currentConfig.modules[e]={enabled:!1},u.updateConfiguration(u.currentConfig))}static createDebugConfig(){return new T().setEnabled(!0).setDefaultLevel("trace").addModule(b.UNIVERSAL_SQLITE,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.DATABASE_MANAGER,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.DATABASE_FACTORY,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.UNIVERSAL_DAO,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.BASE_SERVICE,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.SERVICE_MANAGER,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.QUERY_BUILDER,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.BASE_ADAPTER,!0,["trace","debug","info","warn","error"],["console"]).build()}static createProductionConfig(){return new T().setEnabled(!0).setDefaultLevel("warn").addModule(b.UNIVERSAL_SQLITE,!0,["error"],["console"]).addModule(b.DATABASE_MANAGER,!0,["warn","error"],["console"]).addModule(b.DATABASE_FACTORY,!0,["warn","error"],["console"]).addModule(b.UNIVERSAL_DAO,!0,["error"],["console"]).addModule(b.BASE_SERVICE,!0,["error"],["console"]).addModule(b.SERVICE_MANAGER,!0,["error"],["console"]).addModule(b.QUERY_BUILDER,!0,["error"],["console"]).addModule(b.BASE_ADAPTER,!0,["warn","error"],["console"]).build()}static reset(){return u.initialize()}}u.instance=null,u.currentConfig=null;const z=u.getInstance(),w=h=>{const e=u.getInstance();return{trace:(t,...a)=>e.trace(h,t,...a),debug:(t,...a)=>e.debug(h,t,...a),info:(t,...a)=>e.info(h,t,...a),warn:(t,...a)=>e.warn(h,t,...a),error:(t,...a)=>e.error(h,t,...a)}};class F{constructor(e,t,a){var s,r;this.adapter=e,this.dbPath=t,this.options=a,this.connection=null,this.isConnected=!1,this.inTransaction=!1,this.typeMappingConfig=null,this.createIfNotExists=!1,this.forceRecreate=!1,this.logger=w(b.UNIVERSAL_DAO),this.createIfNotExists=(s=a==null?void 0:a.createIfNotExists)!==null&&s!==void 0?s:!1,this.forceRecreate=(r=a==null?void 0:a.forceRecreate)!==null&&r!==void 0?r:!1,this.logger.trace("UniversalDAO constructor initialized",{dbPath:this.dbPath,createIfNotExists:this.createIfNotExists,forceRecreate:this.forceRecreate})}async connect(){if(this.logger.trace("Attempting to connect to database",{dbPath:this.dbPath}),this.isConnected){this.logger.debug("Already connected to database, skipping connection");return}try{this.connection=await this.adapter.connect(this.dbPath),this.isConnected=!0,this.logger.info("Successfully connected to database",{dbPath:this.dbPath})}catch(e){throw this.logger.error("Failed to connect to database",{dbPath:this.dbPath,error:e instanceof Error?e.message:String(e)}),e}}async disconnect(){if(this.logger.trace("Attempting to disconnect from database"),this.connection&&this.isConnected)try{await this.connection.close(),this.connection=null,this.isConnected=!1,this.logger.info("Successfully disconnected from database")}catch(e){throw this.logger.error("Error during database disconnection",{error:e instanceof Error?e.message:String(e)}),e}else this.logger.debug("Database was not connected, nothing to disconnect")}async close(){this.logger.trace("Closing database connection"),await this.disconnect()}setTypeMappingConfig(e){this.logger.trace("Setting type mapping configuration",{config:e}),this.typeMappingConfig=e,this.logger.debug("Type mapping configuration updated")}convertToSQLiteType(e){if(this.logger.trace("Converting generic type to SQLite type",{genericType:e}),!this.typeMappingConfig||!this.typeMappingConfig.sqlite){const a=this.getDefaultSQLiteType(e);return this.logger.debug("Using default type mapping",{genericType:e,sqliteType:a}),a}const t=this.typeMappingConfig.sqlite[e.toLowerCase()]||"TEXT";return this.logger.debug("Using custom type mapping",{genericType:e,sqliteType:t}),t}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){this.logger.trace("Processing column definition",{columnName:e.name,originalType:e.type});const t=Object.assign({},e);t.type=this.convertToSQLiteType(e.type);const a=[];if(e.constraints){this.logger.trace("Processing column constraints",{columnName:e.name,constraints:e.constraints});const s=e.constraints.toUpperCase().split(" ");s.includes("PRIMARY")&&(a.push("PRIMARY KEY"),t.primary_key=!0),(s.includes("AUTO_INCREMENT")||s.includes("AUTOINCREMENT"))&&(t.primary_key&&a.push("AUTOINCREMENT"),t.auto_increment=!0),s.includes("NOT")&&s.includes("NULL")&&(a.push("NOT NULL"),t.nullable=!1),s.includes("UNIQUE")&&(t.primary_key||a.push("UNIQUE"),t.unique=!0);const r=s.indexOf("DEFAULT");if(r!==-1&&s.length>r+1){const i=s[r+1];a.push(`DEFAULT ${i}`),t.default=i}}return t.option_key=a.join(" ").trim(),this.logger.debug("Column definition processed",{columnName:e.name,finalType:t.type,options:t.option_key}),t}async initializeFromSchema(e){var t,a;this.logger.info("Initializing database schema",{schemaVersion:e.version,tableCount:Object.keys(e.schemas).length}),this.ensureConnected();let s=!1;try{const r=await this.execute("SELECT version FROM _schema_info ORDER BY applied_at DESC LIMIT 1");s=r.rows.length>0,s&&this.logger.debug("Existing schema detected",{currentVersion:(t=r.rows[0])===null||t===void 0?void 0:t.version})}catch(r){this.logger.debug("No existing schema found or schema info table missing"),s=!1}if(s&&!this.createIfNotExists&&!this.forceRecreate){this.logger.info("Schema exists and no recreation options set, using existing schema"),e.type_mapping&&this.setTypeMappingConfig(e.type_mapping);return}s&&this.forceRecreate&&(this.logger.warn("Force recreate option enabled, dropping all existing tables"),await this.dropAllTables()),e.type_mapping&&this.setTypeMappingConfig(e.type_mapping);try{this.logger.debug("Enabling foreign key constraints"),await this.execute("PRAGMA foreign_keys = ON")}catch(r){this.logger.warn("Failed to enable foreign key constraints",{error:r instanceof Error?r.message:String(r)})}await this.beginTransaction();try{this.logger.info("Creating tables from schema");for(const[r,i]of Object.entries(e.schemas)){this.logger.debug("Creating table",{tableName:r,columnCount:i.cols.length});const o={name:r,cols:i.cols.map(l=>this.processColumnDefinition(l)),description:i.description,indexes:i.indexes,foreign_keys:i.foreign_keys};await this.createTableWithForeignKeys(o)}this.logger.info("Creating indexes for tables");for(const[r,i]of Object.entries(e.schemas))!((a=i.indexes)===null||a===void 0)&&a.length&&(this.logger.debug("Creating indexes for table",{tableName:r,indexCount:i.indexes.length}),await this.createIndexesForTable(r,i.indexes));await this.setSchemaVersion(e.version),await this.commitTransaction(),this.logger.info("Schema initialization completed successfully",{version:e.version})}catch(r){throw this.logger.error("Schema initialization failed, rolling back transaction",{error:r instanceof Error?r.message:String(r)}),await this.rollbackTransaction(),r}}async dropAllTables(){this.logger.info("Dropping all existing tables");const e=await this.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");this.logger.debug("Found tables to drop",{tableCount:e.rows.length}),await this.beginTransaction();try{for(const t of e.rows)this.logger.trace("Dropping table",{tableName:t.name}),await this.execute(`DROP TABLE IF EXISTS ${t.name}`);await this.commitTransaction(),this.logger.info("All tables dropped successfully")}catch(t){throw this.logger.error("Failed to drop tables, rolling back",{error:t instanceof Error?t.message:String(t)}),await this.rollbackTransaction(),t}}async createTableWithForeignKeys(e){this.logger.trace("Creating table with foreign keys",{tableName:e.name});const t=e.cols.map(i=>`${i.name} ${i.type} ${i.option_key||""}`.trim()),a=[];if(e.foreign_keys){this.logger.debug("Processing foreign keys",{tableName:e.name,fkCount:e.foreign_keys.length});for(const i of e.foreign_keys){let o=`FOREIGN KEY (${i.column}) REFERENCES ${i.references.table}(${i.references.column})`;i.on_delete&&(o+=` ON DELETE ${i.on_delete}`),i.on_update&&(o+=` ON UPDATE ${i.on_update}`),a.push(o)}}const s=[...t,...a],r=`CREATE TABLE IF NOT EXISTS ${e.name} (${s.join(", ")})`;try{await this.execute(r),this.logger.debug("Table created successfully",{tableName:e.name})}catch(i){throw this.logger.error("Failed to create table",{tableName:e.name,sql:r,error:i instanceof Error?i.message:String(i)}),i}}async createIndexesForTable(e,t){this.logger.trace("Creating indexes for table",{tableName:e,indexCount:t.length});for(const a of t){const s=a.columns.join(", "),r=a.unique||!1,i=`CREATE ${r?"UNIQUE":""} INDEX IF NOT EXISTS ${a.name} ON ${e} (${s})`;try{await this.execute(i),this.logger.debug("Index created successfully",{indexName:a.name,tableName:e,columns:a.columns,unique:r})}catch(o){throw this.logger.error("Failed to create index",{indexName:a.name,tableName:e,sql:i,error:o instanceof Error?o.message:String(o)}),o}}}async beginTransaction(){if(this.logger.trace("Beginning transaction"),this.inTransaction){const e=new Error("Transaction already in progress");throw this.logger.error("Cannot begin transaction",{error:e.message}),e}try{await this.execute("BEGIN TRANSACTION"),this.inTransaction=!0,this.logger.debug("Transaction started successfully")}catch(e){throw this.logger.error("Failed to begin transaction",{error:e instanceof Error?e.message:String(e)}),e}}async commitTransaction(){if(this.logger.trace("Committing transaction"),!this.inTransaction){const e=new Error("No transaction in progress");throw this.logger.error("Cannot commit transaction",{error:e.message}),e}try{await this.execute("COMMIT"),this.inTransaction=!1,this.logger.debug("Transaction committed successfully")}catch(e){throw this.logger.error("Failed to commit transaction",{error:e instanceof Error?e.message:String(e)}),e}}async rollbackTransaction(){if(this.logger.trace("Rolling back transaction"),!this.inTransaction){const e=new Error("No transaction in progress");throw this.logger.error("Cannot rollback transaction",{error:e.message}),e}try{await this.execute("ROLLBACK"),this.inTransaction=!1,this.logger.debug("Transaction rolled back successfully")}catch(e){throw this.logger.error("Failed to rollback transaction",{error:e instanceof Error?e.message:String(e)}),e}}async getSchemaVersion(){this.logger.trace("Getting schema version");try{const e=(await this.getRst("SELECT version FROM _schema_info ORDER BY applied_at DESC LIMIT 1")).version||"0";return this.logger.debug("Schema version retrieved",{version:e}),e}catch(e){return this.logger.debug("No schema version found, returning default",{defaultVersion:"0"}),"0"}}async setSchemaVersion(e){this.logger.trace("Setting schema version",{version:e});try{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
4
|
)`),await this.execute("INSERT INTO _schema_info (version) VALUES (?)",[e]),this.logger.info("Schema version set successfully",{version:e})}catch(t){throw this.logger.error("Failed to set schema version",{version:e,error:t instanceof Error?t.message:String(t)}),t}}async insert(e){this.logger.trace("Performing insert operation",{tableName:e.name});const t=e.cols.filter(o=>o.value!==void 0&&o.value!==null);if(t.length===0){const o=new Error("No valid columns to insert");throw this.logger.error("Insert operation failed",{tableName:e.name,error:o.message}),o}const a=t.map(o=>o.name).join(", "),s=t.map(()=>"?").join(", "),r=t.map(o=>typeof o.value=="object"?JSON.stringify(o.value):o.value),i=`INSERT INTO ${e.name} (${a}) VALUES (${s})`;this.logger.debug("Executing insert query",{tableName:e.name,columnCount:t.length,sql:i});try{const o=await this.execute(i,r);return this.logger.info("Insert operation completed successfully",{tableName:e.name,rowsAffected:o.rowsAffected,lastInsertRowid:o.lastInsertRowId}),o}catch(o){throw this.logger.error("Insert operation failed",{tableName:e.name,sql:i,error:o instanceof Error?o.message:String(o)}),o}}async update(e){var t;this.logger.trace("Performing update operation",{tableName:e.name});const a=e.cols.filter(l=>{var m;return l.value!==void 0&&!(!((m=e.wheres)===null||m===void 0)&&m.some(f=>f.name===l.name))});if(a.length===0){const l=new Error("No columns to update");throw this.logger.error("Update operation failed",{tableName:e.name,error:l.message}),l}const s=a.map(l=>`${l.name} = ?`).join(", "),r=a.map(l=>typeof l.value=="object"?JSON.stringify(l.value):l.value);let i=`UPDATE ${e.name} SET ${s}`;const o=this.buildWhereClause(e.wheres);if(!o.sql){const l=new Error("WHERE clause is required for UPDATE operation");throw this.logger.error("Update operation failed",{tableName:e.name,error:l.message}),l}i+=o.sql,r.push(...o.params),this.logger.debug("Executing update query",{tableName:e.name,updateColumnCount:a.length,whereConditions:((t=e.wheres)===null||t===void 0?void 0:t.length)||0,sql:i});try{const l=await this.execute(i,r);return this.logger.info("Update operation completed successfully",{tableName:e.name,rowsAffected:l.rowsAffected}),l}catch(l){throw this.logger.error("Update operation failed",{tableName:e.name,sql:i,error:l instanceof Error?l.message:String(l)}),l}}async delete(e){var t;this.logger.trace("Performing delete operation",{tableName:e.name});let a=`DELETE FROM ${e.name}`;const s=this.buildWhereClause(e.wheres);if(!s.sql){const r=new Error("WHERE clause is required for DELETE operation");throw this.logger.error("Delete operation failed",{tableName:e.name,error:r.message}),r}a+=s.sql,this.logger.debug("Executing delete query",{tableName:e.name,whereConditions:((t=e.wheres)===null||t===void 0?void 0:t.length)||0,sql:a});try{const r=await this.execute(a,s.params);return this.logger.info("Delete operation completed successfully",{tableName:e.name,rowsAffected:r.rowsAffected}),r}catch(r){throw this.logger.error("Delete operation failed",{tableName:e.name,sql:a,error:r instanceof Error?r.message:String(r)}),r}}async select(e){this.logger.trace("Performing select single operation",{tableName:e.name});const{sql:t,params:a}=this.buildSelectQuery(e," LIMIT 1");this.logger.debug("Executing select single query",{tableName:e.name,sql:t});try{const s=await this.execute(t,a),r=s.rows[0]||{};return this.logger.debug("Select single operation completed",{tableName:e.name,hasResult:!!s.rows[0]}),r}catch(s){throw this.logger.error("Select single operation failed",{tableName:e.name,sql:t,error:s instanceof Error?s.message:String(s)}),s}}async selectAll(e){this.logger.trace("Performing select all operation",{tableName:e.name});const{sql:t,params:a}=this.buildSelectQuery(e);this.logger.debug("Executing select all query",{tableName:e.name,sql:t});try{const s=await this.execute(t,a);return this.logger.debug("Select all operation completed",{tableName:e.name,rowCount:s.rows.length}),s.rows}catch(s){throw this.logger.error("Select all operation failed",{tableName:e.name,sql:t,error:s instanceof Error?s.message:String(s)}),s}}buildSelectQuery(e,t=""){var a;let s=`SELECT ${e.cols.length>0?e.cols.map(i=>i.name).join(", "):"*"} FROM ${e.name}`;const r=this.buildWhereClause(e.wheres);if(s+=r.sql,!((a=e.orderbys)===null||a===void 0)&&a.length){const i=e.orderbys.map(o=>`${o.name} ${o.direction||"ASC"}`).join(", ");s+=` ORDER BY ${i}`}return e.limitOffset&&(e.limitOffset.limit&&(s+=` LIMIT ${e.limitOffset.limit}`),e.limitOffset.offset&&(s+=` OFFSET ${e.limitOffset.offset}`)),s+=t,{sql:s,params:r.params}}buildWhereClause(e,t="WHERE"){if(!e||e.length===0)return{sql:"",params:[]};const a=[],s=[];for(const r of e){const i=r.operator||"=";a.push(`${r.name} ${i} ?`),s.push(r.value)}return{sql:` ${t} ${a.join(" AND ")}`,params:s}}convertJsonToQueryTable(e,t,a=["id"]){var s,r;this.logger.trace("Converting JSON to QueryTable",{tableName:e,fieldCount:Object.keys(t).length,idFields:a});const i={name:e,cols:[],wheres:[]};for(const[o,l]of Object.entries(t))i.cols.push({name:o,value:l}),a.includes(o)&&l!==void 0&&((s=i.wheres)===null||s===void 0||s.push({name:o,value:l}));return this.logger.debug("JSON converted to QueryTable",{tableName:e,columnCount:i.cols.length,whereCount:((r=i.wheres)===null||r===void 0?void 0:r.length)||0}),i}async importData(e){this.logger.info("Starting data import operation",{tableName:e.tableName,totalRows:e.data.length,batchSize:e.batchSize||1e3,validateData:e.validateData,updateOnConflict:e.updateOnConflict,skipErrors:e.skipErrors});const t=Date.now(),a={totalRows:e.data.length,successRows:0,errorRows:0,errors:[],executionTime:0};if(!this.isConnected){const m=new Error("Database is not connected");throw this.logger.error("Import failed - database not connected"),m}if(!e.data||e.data.length===0)return this.logger.warn("No data provided for import, returning empty result"),a.executionTime=Date.now()-t,a;const s=await this.getTableInfo(e.tableName);if(s.length===0){const m=new Error(`Table '${e.tableName}' does not exist`);throw this.logger.error("Import failed - table does not exist",{tableName:e.tableName}),m}this.logger.debug("Table info retrieved for import",{tableName:e.tableName,columnCount:s.length});const r=new Map(s.map(m=>[m.name.toLowerCase(),m])),i=e.batchSize||1e3;let o=0;const l=!e.includeAutoIncrementPK;try{await this.beginTransaction();for(let m=0;m<e.data.length;m+=i){const f=e.data.slice(m,m+i);this.logger.debug("Processing import batch",{batchNumber:Math.floor(m/i)+1,batchSize:f.length,totalBatches:Math.ceil(e.data.length/i)});for(let y=0;y<f.length;y++){const N=m+y,I=f[y];try{const C=e.validateData?this.validateAndTransformRow(I,r,e.tableName,l):this.transformRowData(I,r,l);e.updateOnConflict&&e.conflictColumns?await this.insertOrUpdate(e.tableName,C,e.conflictColumns):await this.insertRow(e.tableName,C),a.successRows++}catch(C){a.errorRows++;const x={rowIndex:N,error:C instanceof Error?C.message:String(C),rowData:I};if(a.errors.push(x),this.logger.warn("Row import failed",{rowIndex:N,tableName:e.tableName,error:C instanceof Error?C.message:String(C)}),e.onError&&e.onError(C instanceof Error?C:new Error(String(C)),N,I),!e.skipErrors)throw this.logger.error("Import operation stopped due to error and skipErrors=false"),C}o++,e.onProgress&&o%100===0&&e.onProgress(o,e.data.length)}}await this.commitTransaction(),this.logger.info("Data import completed successfully",{tableName:e.tableName,totalRows:a.totalRows,successRows:a.successRows,errorRows:a.errorRows,executionTime:Date.now()-t})}catch(m){throw this.logger.error("Import operation failed, rolling back transaction",{tableName:e.tableName,processedCount:o,error:m instanceof Error?m.message:String(m)}),await this.rollbackTransaction(),m}return e.onProgress&&e.onProgress(o,e.data.length),a.executionTime=Date.now()-t,a}async importDataWithMapping(e,t,a,s={}){this.logger.info("Starting data import with column mapping",{tableName:e,dataRows:t.length,mappingCount:a.length});const r=t.map((i,o)=>{this.logger.trace("Transforming row with column mappings",{rowIndex:o});const l={};return a.forEach(m=>{if(i.hasOwnProperty(m.sourceColumn)){let f=i[m.sourceColumn];if(m.transform)try{f=m.transform(f)}catch(y){this.logger.warn("Column transformation failed",{rowIndex:o,sourceColumn:m.sourceColumn,targetColumn:m.targetColumn,error:y instanceof Error?y.message:String(y)})}l[m.targetColumn]=f}}),l});return this.logger.debug("Data transformation completed",{originalRowCount:t.length,transformedRowCount:r.length}),await this.importData(Object.assign({tableName:e,data:r},s))}async importFromCSV(e,t,a={}){this.logger.info("Starting CSV import",{tableName:e,csvLength:t.length,delimiter:a.delimiter||",",hasHeader:a.hasHeader!==!1});const s=a.delimiter||",",r=a.hasHeader!==!1,i=t.split(`
|