@dreamtree-org/korm-js 1.0.53 → 1.0.55

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.
Files changed (44) hide show
  1. package/BaseHelperUtility.js +1 -1
  2. package/ControllerWrapper.js +1 -1
  3. package/Emitter.js +1 -1
  4. package/KormError.js +1 -0
  5. package/README.md +463 -254
  6. package/RequestValidator.js +1 -1
  7. package/ai-skills/korm-js.md +265 -0
  8. package/bin/korm-mcp.js +2 -0
  9. package/build.js +1 -1
  10. package/cli.js +2 -0
  11. package/clients/BaseSyncTable.js +1 -0
  12. package/clients/mysql/BaseUtility.js +1 -1
  13. package/clients/mysql/CurdTable.js +1 -1
  14. package/clients/mysql/DataTypeMap.js +1 -1
  15. package/clients/mysql/HookService.js +1 -1
  16. package/clients/mysql/QueryBuilder.js +1 -1
  17. package/clients/mysql/QueryService.js +1 -1
  18. package/clients/mysql/SyncTable.js +1 -1
  19. package/clients/pg/BaseUtility.js +1 -1
  20. package/clients/pg/CurdTable.js +1 -1
  21. package/clients/pg/DataTypeMap.js +1 -1
  22. package/clients/pg/HookService.js +1 -1
  23. package/clients/pg/QueryBuilder.js +1 -1
  24. package/clients/pg/QueryService.js +1 -1
  25. package/clients/pg/SyncTable.js +1 -1
  26. package/clients/sqlite/BaseUtility.js +1 -1
  27. package/clients/sqlite/CurdTable.js +1 -1
  28. package/clients/sqlite/HookService.js +1 -1
  29. package/clients/sqlite/QueryBuilder.js +1 -1
  30. package/clients/sqlite/QueryService.js +1 -1
  31. package/clients/sqlite/SyncTable.js +1 -1
  32. package/columnSchema.js +1 -0
  33. package/helpers/files.js +1 -1
  34. package/index.d.ts +213 -0
  35. package/index.js +1 -1
  36. package/jest.config.js +1 -1
  37. package/package.json +13 -4
  38. package/requestSchema.js +1 -0
  39. package/schemaDescribe.js +1 -0
  40. package/src/mcp/errors.js +1 -0
  41. package/src/mcp/schemaIntrospect.js +1 -0
  42. package/src/mcp/server.js +1 -0
  43. package/src/mcp/toolGenerator.js +1 -0
  44. package/TableSchemaSync.js +0 -1
@@ -1 +1 @@
1
- const QueryService=require("./QueryService"),HookService=require("./HookService");class CurdTable{constructor(e,r,t=null){if(this.db=e,this.utils=r,this.controllerWrapper=t,this.hookService=new HookService(e,r,t),this.queryService=new QueryService(e,r,t),!this.queryService)throw new Error("CurdTable requires queryService (execute*Query / getQuery).")}async processRequest(e,r=null,t=null){const o=this.controllerWrapper;let s=this.utils.getModel(this.controllerWrapper,r);const c=e?.action||"list";let u=null;const a={model:s,action:c,request:e,ctx:t,controller:o};switch(this.hookService?.executeValidatorHook&&await this.hookService.executeValidatorHook({...a}),this.hookService?.executeBeforeHook&&(e.beforeActionData=await this.hookService.executeBeforeHook({...a})),c){case"count":u=await this.queryService.executeCountQuery(s,e);break;case"sum":u=await this.queryService.executeSumQuery(s,e);break;case"list":u=await this.hookService.executeHasSoftDeleteHook(s)?await this.queryService.getSoftDeleteQuery(s,e):await this.queryService.getQuery(s,e);break;case"show":u=await this.queryService.executeShowQuery(s,e);break;case"create":u=await this.queryService.executeCreateQuery(s,e);break;case"update":{const r=await this.queryService.executeUpdateQuery(s,e);if(!r)throw new Error(`Record not found or not updated: ${s.table} returned ${r}`);u={message:"Record updated successfully",data:r,success:!0};break}case"replace":if(u=await this.queryService.executeReplaceQuery(s,e),!u)throw new Error(`Record not found or not replaced: ${r} returned ${u}`);u={message:"Record replaced successfully",data:u,success:!0};break;case"upsert":if(u=await this.queryService.executeUpsertQuery(s,e),!u)throw new Error(`Record not found or not upserted: ${r} returned ${u}`);u={message:"Record upserted successfully",data:u,success:!0};break;case"sync":if(u=await this.queryService.executeSyncQuery(s,e),!u)throw new Error(`Record not found or not synced: ${r} returned ${u}`);u={message:"Record synced successfully",data:u,success:!0};break;case"delete":{let t=null;if(t=await this.hookService.executeHasSoftDeleteHook(s)?await this.queryService.executeSoftDeleteQuery(s,e):await this.queryService.executeDeleteQuery(s,e),!t)throw new Error(`Record not found or not deleted: ${r} returned ${t}`);u={message:"Record deleted successfully",data:t,success:!0};break}default:if(!this.hookService?.executeCustomAction)throw new Error(`Unknown action "${c}" and no custom action hook provided.`);u=await this.hookService.executeCustomAction({...a})}if(this.hookService?.executeAfterHook&&(u=await this.hookService.executeAfterHook({...a,data:u})),e?.other_requests&&"object"==typeof e.other_requests){const r={},o=Object.entries(e.other_requests);for(const[e,s]of o)Array.isArray(s)?r[e]=await Promise.all(s.map(r=>this.processRequest(r,e,t))):r[e]=await this.processRequest(s,e,t);u.other_responses=r}return u}}module.exports=CurdTable;
1
+ const QueryService=require("./QueryService"),HookService=require("./HookService"),KormError=require("../../KormError");class CurdTable{constructor(e,r,t=null){if(this.db=e,this.utils=r,this.controllerWrapper=t,this.hookService=new HookService(e,r,t),this.queryService=new QueryService(e,r,t),!this.queryService)throw new KormError("CurdTable requires queryService (execute*Query / getQuery).",{code:KormError.CODES.INTERNAL})}async processRequest(e,r=null,t=null){const o=this.controllerWrapper,s=this.utils.getModel(this.controllerWrapper,r),c=e?.action||"list";let i=null;const a={model:s,action:c,request:e,ctx:t,controller:o};if(this.hookService?.executeValidatorHook&&await this.hookService.executeValidatorHook({...a}),e?.dryRun)return this.buildDryRunResult(s,e,c);switch(this.hookService?.executeBeforeHook&&(e.beforeActionData=await this.hookService.executeBeforeHook({...a})),c){case"count":i=await this.queryService.executeCountQuery(s,e);break;case"sum":i=await this.queryService.executeSumQuery(s,e);break;case"list":i=await this.hookService.executeHasSoftDeleteHook(s)?await this.queryService.getSoftDeleteQuery(s,e):await this.queryService.getQuery(s,e);break;case"show":i=await this.queryService.executeShowQuery(s,e);break;case"create":i=await this.queryService.executeCreateQuery(s,e);break;case"update":{const r=await this.queryService.executeUpdateQuery(s,e);if(!r)throw KormError.noMatchingRow({action:c,model:s.name});i={message:"Record updated successfully",data:r,success:!0};break}case"replace":if(i=await this.queryService.executeReplaceQuery(s,e),!i)throw KormError.noMatchingRow({action:c,model:s.name});i={message:"Record replaced successfully",data:i,success:!0};break;case"upsert":if(i=await this.queryService.executeUpsertQuery(s,e),!i)throw KormError.noMatchingRow({action:c,model:s.name});i={message:"Record upserted successfully",data:i,success:!0};break;case"sync":if(i=await this.queryService.executeSyncQuery(s,e),!i)throw KormError.noMatchingRow({action:c,model:s.name});i={message:"Record synced successfully",data:i,success:!0};break;case"delete":{let r=null;if(r=await this.hookService.executeHasSoftDeleteHook(s)?await this.queryService.executeSoftDeleteQuery(s,e):await this.queryService.executeDeleteQuery(s,e),!r)throw KormError.noMatchingRow({action:c,model:s.name});i={message:"Record deleted successfully",data:r,success:!0};break}default:if(!this.hookService?.executeCustomAction)throw KormError.unknownAction({action:c,model:s?.name});i=await this.hookService.executeCustomAction({...a})}if(this.hookService?.executeAfterHook&&(i=await this.hookService.executeAfterHook({...a,data:i})),e?.other_requests&&"object"==typeof e.other_requests){const r={},o=Object.entries(e.other_requests);for(const[e,s]of o)Array.isArray(s)?r[e]=await Promise.all(s.map(r=>this.processRequest(r,e,t))):r[e]=await this.processRequest(s,e,t);i.other_responses=r}return i}async buildDryRunResult(e,r,t){if(!["list","show","count","sum","create","update","replace","upsert","sync","delete"].includes(t))throw KormError.unknownAction({action:t,model:e?.name});let o=t,s=r;const c=await this.hookService.executeHasSoftDeleteHook(e);return c&&"delete"===t?o="softDelete":c&&"list"===t&&(s={...r,where:{...r.where||{},deleted_at:null}}),this.queryService.buildDryRun(e,s,o)}}module.exports=CurdTable;
@@ -1 +1 @@
1
- const DataTypeMap=[{type:"number",maxSize:2,dbType:"smallint"},{type:"number",maxSize:4,dbType:"integer"},{type:"number",maxSize:8,dbType:"bigint"},{type:"number",maxSize:4,dbType:"real"},{type:"number",maxSize:8,dbType:"double precision"},{type:"number",maxSize:null,dbType:"numeric"},{type:"number",maxSize:null,dbType:"decimal"},{type:"number",maxSize:null,dbType:"money"},{type:"number",maxSize:4,dbType:"serial"},{type:"number",maxSize:2,dbType:"smallserial"},{type:"number",maxSize:8,dbType:"bigserial"},{type:"string",maxSize:255,dbType:"character varying"},{type:"string",maxSize:255,dbType:"varchar"},{type:"string",maxSize:1,dbType:"character"},{type:"string",maxSize:1,dbType:"char"},{type:"string",maxSize:null,dbType:"text"},{type:"string",maxSize:255,dbType:"citext"},{type:"string",maxSize:255,dbType:"uuid"},{type:"string",maxSize:255,dbType:"bpchar"},{type:"string",maxSize:63,dbType:"name"},{type:"string",maxSize:null,dbType:"xml"},{type:"string",maxSize:null,dbType:"inet"},{type:"string",maxSize:null,dbType:"macaddr"},{type:"string",maxSize:null,dbType:"macaddr8"},{type:"string",maxSize:null,dbType:"bit"},{type:"string",maxSize:null,dbType:"varbit"},{type:"string",maxSize:null,dbType:"tsvector"},{type:"string",maxSize:null,dbType:"tsquery"},{type:"string",maxSize:null,dbType:"jsonpath"},{type:"boolean",maxSize:null,dbType:"boolean"},{type:"date",maxSize:null,dbType:"date"},{type:"date",maxSize:null,dbType:"timestamp"},{type:"date",maxSize:null,dbType:"timestamp without time zone"},{type:"date",maxSize:null,dbType:"timestamp with time zone"},{type:"date",maxSize:null,dbType:"timestamptz"},{type:"date",maxSize:null,dbType:"time"},{type:"date",maxSize:null,dbType:"time without time zone"},{type:"date",maxSize:null,dbType:"time with time zone"},{type:"date",maxSize:null,dbType:"timetz"},{type:"date",maxSize:null,dbType:"interval"},{type:"json",maxSize:null,dbType:"json"},{type:"json",maxSize:null,dbType:"jsonb"},{type:"buffer",maxSize:null,dbType:"bytea"},{type:"string",maxSize:null,dbType:"point"},{type:"string",maxSize:null,dbType:"line"},{type:"string",maxSize:null,dbType:"lseg"},{type:"string",maxSize:null,dbType:"box"},{type:"string",maxSize:null,dbType:"path"},{type:"string",maxSize:null,dbType:"polygon"},{type:"string",maxSize:null,dbType:"circle"},{type:"string",maxSize:null,dbType:"cidr"},{type:"string",maxSize:null,dbType:"cid"},{type:"string",maxSize:null,dbType:"oid"},{type:"string",maxSize:null,dbType:"xid"},{type:"string",maxSize:null,dbType:"tid"},{type:"string",maxSize:null,dbType:"regproc"},{type:"string",maxSize:null,dbType:"regprocedure"},{type:"string",maxSize:null,dbType:"regoper"},{type:"string",maxSize:null,dbType:"regoperator"},{type:"string",maxSize:null,dbType:"regclass"},{type:"string",maxSize:null,dbType:"regtype"},{type:"string",maxSize:null,dbType:"regrole"},{type:"string",maxSize:null,dbType:"regnamespace"},{type:"string",maxSize:null,dbType:"regconfig"},{type:"string",maxSize:null,dbType:"regdictionary"},{type:"string",maxSize:null,dbType:"regcollation"},{type:"string",maxSize:null,dbType:"regtypearray"},{type:"string",maxSize:null,dbType:"pg_lsn"},{type:"string",maxSize:null,dbType:"txid_snapshot"},{type:"string",maxSize:null,dbType:"uuid[]"},{type:"string",maxSize:null,dbType:"int4range"},{type:"string",maxSize:null,dbType:"int8range"},{type:"string",maxSize:null,dbType:"numrange"},{type:"string",maxSize:null,dbType:"tsrange"},{type:"string",maxSize:null,dbType:"tstzrange"},{type:"string",maxSize:null,dbType:"daterange"},{type:"string",maxSize:null,dbType:"USER-DEFINED"}];function getDbType(e,t,p){let i=null;return p&&(i=DataTypeMap.find(i=>i.type===e&&i.maxSize===t&&i.dbType.toLowerCase()===p.toLowerCase())),i||(i=DataTypeMap.find(p=>p.type===e&&p.maxSize===t)||null),i||(i=DataTypeMap.find(t=>t.dbType.toLowerCase()===e.toLowerCase())||null),i||(i=DataTypeMap.find(t=>t.type===e&&null===t.maxSize)||null),i?i.dbType:null}function getSchemaType(e){return DataTypeMap.find(t=>t.dbType===e)?.type}function getDefaultTypeSize(e){return DataTypeMap.find(t=>t.dbType===e)?.maxSize}module.exports={DataTypeMap:DataTypeMap,getDbType:getDbType,getSchemaType:getSchemaType,getDefaultTypeSize:getDefaultTypeSize};
1
+ const DataTypeMap=[{type:"number",maxSize:2,dbType:"smallint"},{type:"number",maxSize:4,dbType:"integer"},{type:"number",maxSize:8,dbType:"bigint"},{type:"number",maxSize:4,dbType:"real"},{type:"number",maxSize:8,dbType:"double precision"},{type:"number",maxSize:null,dbType:"numeric"},{type:"number",maxSize:null,dbType:"decimal"},{type:"number",maxSize:null,dbType:"money"},{type:"number",maxSize:4,dbType:"serial"},{type:"number",maxSize:2,dbType:"smallserial"},{type:"number",maxSize:8,dbType:"bigserial"},{type:"string",maxSize:255,dbType:"character varying"},{type:"string",maxSize:255,dbType:"varchar"},{type:"string",maxSize:1,dbType:"character"},{type:"string",maxSize:1,dbType:"char"},{type:"string",maxSize:null,dbType:"text"},{type:"string",maxSize:255,dbType:"citext"},{type:"string",maxSize:255,dbType:"uuid"},{type:"string",maxSize:255,dbType:"bpchar"},{type:"string",maxSize:63,dbType:"name"},{type:"string",maxSize:null,dbType:"xml"},{type:"string",maxSize:null,dbType:"inet"},{type:"string",maxSize:null,dbType:"macaddr"},{type:"string",maxSize:null,dbType:"macaddr8"},{type:"string",maxSize:null,dbType:"bit"},{type:"string",maxSize:null,dbType:"varbit"},{type:"string",maxSize:null,dbType:"tsvector"},{type:"string",maxSize:null,dbType:"tsquery"},{type:"string",maxSize:null,dbType:"jsonpath"},{type:"boolean",maxSize:null,dbType:"boolean"},{type:"date",maxSize:null,dbType:"date"},{type:"date",maxSize:null,dbType:"timestamp"},{type:"date",maxSize:null,dbType:"timestamp without time zone"},{type:"date",maxSize:null,dbType:"timestamp with time zone"},{type:"date",maxSize:null,dbType:"timestamptz"},{type:"date",maxSize:null,dbType:"time"},{type:"date",maxSize:null,dbType:"time without time zone"},{type:"date",maxSize:null,dbType:"time with time zone"},{type:"date",maxSize:null,dbType:"timetz"},{type:"date",maxSize:null,dbType:"interval"},{type:"json",maxSize:null,dbType:"json"},{type:"json",maxSize:null,dbType:"jsonb"},{type:"buffer",maxSize:null,dbType:"bytea"},{type:"string",maxSize:null,dbType:"point"},{type:"string",maxSize:null,dbType:"line"},{type:"string",maxSize:null,dbType:"lseg"},{type:"string",maxSize:null,dbType:"box"},{type:"string",maxSize:null,dbType:"path"},{type:"string",maxSize:null,dbType:"polygon"},{type:"string",maxSize:null,dbType:"circle"},{type:"string",maxSize:null,dbType:"cidr"},{type:"string",maxSize:null,dbType:"cid"},{type:"string",maxSize:null,dbType:"oid"},{type:"string",maxSize:null,dbType:"xid"},{type:"string",maxSize:null,dbType:"tid"},{type:"string",maxSize:null,dbType:"regproc"},{type:"string",maxSize:null,dbType:"regprocedure"},{type:"string",maxSize:null,dbType:"regoper"},{type:"string",maxSize:null,dbType:"regoperator"},{type:"string",maxSize:null,dbType:"regclass"},{type:"string",maxSize:null,dbType:"regtype"},{type:"string",maxSize:null,dbType:"regrole"},{type:"string",maxSize:null,dbType:"regnamespace"},{type:"string",maxSize:null,dbType:"regconfig"},{type:"string",maxSize:null,dbType:"regdictionary"},{type:"string",maxSize:null,dbType:"regcollation"},{type:"string",maxSize:null,dbType:"regtypearray"},{type:"string",maxSize:null,dbType:"pg_lsn"},{type:"string",maxSize:null,dbType:"txid_snapshot"},{type:"string",maxSize:null,dbType:"uuid[]"},{type:"string",maxSize:null,dbType:"int4range"},{type:"string",maxSize:null,dbType:"int8range"},{type:"string",maxSize:null,dbType:"numrange"},{type:"string",maxSize:null,dbType:"tsrange"},{type:"string",maxSize:null,dbType:"tstzrange"},{type:"string",maxSize:null,dbType:"daterange"},{type:"string",maxSize:null,dbType:"USER-DEFINED"}];function _normaliseMaxSize(e){if(null==e||""===e)return null;const t=Number(e);return Number.isNaN(t)?null:t}function getDbType(e,t,p){const i=_normaliseMaxSize(t);let n=null;return p&&(n=DataTypeMap.find(t=>t.type===e&&t.maxSize===i&&t.dbType.toLowerCase()===p.toLowerCase())),n||(n=DataTypeMap.find(t=>t.type===e&&t.maxSize===i)||null),n||(n=DataTypeMap.find(t=>t.dbType.toLowerCase()===e.toLowerCase())||null),n||(n=DataTypeMap.find(t=>t.type===e&&null===t.maxSize)||null),n?n.dbType:null}function getSchemaType(e){return DataTypeMap.find(t=>t.dbType===e)?.type}function getDefaultTypeSize(e){return DataTypeMap.find(t=>t.dbType===e)?.maxSize}module.exports={DataTypeMap:DataTypeMap,getDbType:getDbType,getSchemaType:getSchemaType,getDefaultTypeSize:getDefaultTypeSize};
@@ -1 +1 @@
1
- const path=require("path"),logger=require("../../Logger");class HookService{constructor(e,t,o=null){this.db=e,this.utils=t,this.controllerWrapper=o,this.controllerWrapper.hookService=this,this.appRoot=o&&o.resolverPath?o.resolverPath:process.cwd()}loadModelClass(e){try{const t=path.join(this.appRoot,"models",`${e}.model.js`);delete require.cache[require.resolve(t)];return require(t)}catch(e){return void logger.debug("loadModelClass error",{err:e})}}getModelInstance(e){let t="string"==typeof e?e:e.modelName;const o=this.loadModelClass(t);if(o)return"function"==typeof o?new o:o}resolveModelHook(e,t,o){const r=e.modelName,s=this.loadModelClass(r);if(!s)return;const l=this.getModelInstance(e);let i;if("validate"===t)i="validate";else if("on"===t)i=`on${o.charAt(0).toUpperCase()+o.slice(1)}`;else if("before"===t)i=`before${o.charAt(0).toUpperCase()+o.slice(1)}`;else if("after"===t)i=`after${o.charAt(0).toUpperCase()+o.slice(1)}`;else{if("custom"!==t)return;i=`on${o.charAt(0).toUpperCase()+o.slice(1)}Action`}return"function"==typeof l[i]?l[i].bind(l):"function"==typeof s[i]?s[i].bind(s):void 0}async executeValidatorHook({model:e,action:t,request:o,ctx:r,controller:s}){const l=this.resolveModelHook(e,"validate",t);if(l)return await l({model:e,action:t,request:o,context:r,db:this.db,utils:this.utils,controller:s})}async executeBeforeHook({model:e,action:t,request:o,ctx:r,controller:s}){const l=this.resolveModelHook(e,"before",t);if(l)return await l({model:e,action:t,request:o,context:r,db:this.db,utils:this.utils,controller:s})}async executeAfterHook({model:e,action:t,data:o,request:r,ctx:s,controller:l}){const i=this.resolveModelHook(e,"after",t);return i?await i({model:e,action:t,data:o,request:r,context:s,db:this.db,utils:this.utils,controller:l}):o}async executeCustomAction({model:e,action:t,request:o,ctx:r,controller:s}){const l=this.resolveModelHook(e,"custom",t);if(l)return await l({model:e,action:t,request:o,context:r,db:this.db,utils:this.utils,controller:s});throw new Error(`No custom action hook found for ${e.modelName}.${t}`)}async executeHasSoftDeleteHook(e){const t=this.getModelInstance(e);if(!t)return!1;return t.hasOwnProperty("hasSoftDelete")&&!0===t.hasSoftDelete}}module.exports=HookService;
1
+ const path=require("path"),KormError=require("../../KormError"),logger=require("../../Logger");class HookService{constructor(e,t,o=null){this.db=e,this.utils=t,this.controllerWrapper=o,this.controllerWrapper.hookService=this,this.appRoot=o&&o.resolverPath?o.resolverPath:process.cwd()}loadModelClass(e){try{const t=path.join(this.appRoot,"models",`${e}.model.js`);delete require.cache[require.resolve(t)];return require(t)}catch(e){return void logger.debug("loadModelClass error",{err:e})}}getModelInstance(e){const t="string"==typeof e?e:e.modelName,o=this.loadModelClass(t);if(o)return"function"==typeof o?new o:o}resolveModelHook(e,t,o){const r=e.modelName,s=this.loadModelClass(r);if(!s)return;const l=this.getModelInstance(e);let i;if("validate"===t)i="validate";else if("on"===t)i=`on${o.charAt(0).toUpperCase()+o.slice(1)}`;else if("before"===t)i=`before${o.charAt(0).toUpperCase()+o.slice(1)}`;else if("after"===t)i=`after${o.charAt(0).toUpperCase()+o.slice(1)}`;else{if("custom"!==t)return;i=`on${o.charAt(0).toUpperCase()+o.slice(1)}Action`}return"function"==typeof l[i]?l[i].bind(l):"function"==typeof s[i]?s[i].bind(s):void 0}async executeValidatorHook({model:e,action:t,request:o,ctx:r,controller:s}){const l=this.resolveModelHook(e,"validate",t);if(l)return await l({model:e,action:t,request:o,context:r,db:this.db,utils:this.utils,controller:s})}async executeBeforeHook({model:e,action:t,request:o,ctx:r,controller:s}){const l=this.resolveModelHook(e,"before",t);if(l)return await l({model:e,action:t,request:o,context:r,db:this.db,utils:this.utils,controller:s})}async executeAfterHook({model:e,action:t,data:o,request:r,ctx:s,controller:l}){const i=this.resolveModelHook(e,"after",t);return i?await i({model:e,action:t,data:o,request:r,context:s,db:this.db,utils:this.utils,controller:l}):o}async executeCustomAction({model:e,action:t,request:o,ctx:r,controller:s}){const l=this.resolveModelHook(e,"custom",t);if(l)return await l({model:e,action:t,request:o,context:r,db:this.db,utils:this.utils,controller:s});throw KormError.unknownAction({action:t,model:e.modelName||e.name,hasCustomHook:!0})}async executeHasSoftDeleteHook(e){const t=this.getModelInstance(e);if(!t)return!1;return t.hasOwnProperty("hasSoftDelete")&&!0===t.hasSoftDelete}}module.exports=HookService;
@@ -1 +1 @@
1
- const HelperUtility=require("./HelperUtility"),logger=require("../../Logger");class QueryBuilder{constructor(e,t,r=null){this.db=e,this.utils=t,this.controllerWrapper=r,this.helperUtility=new HelperUtility}getHookService(){return this.controllerWrapper.hookService}getQueryBuilder(e,t=null){let r=this.db(e.table);return t&&(r=t),r._getMyModel=()=>e,r}parseValue(e){return this.helperUtility.parseValue(e)}parseWhereValue(e){return this.helperUtility.parseWhereValue(e)}parseWhereColumn(e){return this.helperUtility.parseWhereColumn(e)}_applyOrWhereCondition(e,t,r,o){if(null!==o)if(Array.isArray(o))e.orWhereIn(t,o);else switch(r){case"between":e.orWhereBetween(t,o);break;case"notBetween":e.orWhereNotBetween(t,o);break;case"in":e.orWhereIn(t,o);break;case"notIn":e.orWhereNotIn(t,o);break;case"like":e.orWhere(t,"like",o);break;default:e.orWhere(t,r,o)}else e.orWhereNull(t)}_applyAndWhereCondition(e,t,r,o){if(null!==o)if(Array.isArray(o))e.whereIn(t,o);else switch(r){case"between":e.whereBetween(t,o);break;case"notBetween":e.whereNotBetween(t,o);break;case"in":e.whereIn(t,o);break;case"notIn":e.whereNotIn(t,o);break;case"like":e.where(t,"like",o);break;default:e.where(t,r,o)}else e.whereNull(t)}buildWithTree(e,t=null){return this.helperUtility.dotWalkTree(e,{resolver:({current:e,part:r,source:o})=>t?t({current:e,part:r,source:o}):{}})}_getWithWhereForRelation(e,t){if(!e||"object"!=typeof e)return{direct:{},nested:{}};const r=`${t}.`,o={},i={};for(const[t,s]of Object.entries(e))if(t.startsWith(r)){const e=t.slice(r.length);e.includes(".")?i[e]=s:o[e]=s}return{direct:o,nested:i}}_applyWithWhereConditions(e,t){for(const[r,o]of Object.entries(t)){const{joinType:t="AND",column:i}=this.parseWhereColumn(r),{operator:s,value:n}=this.parseWhereValue(o);"AND"===t?this._applyAndWhereCondition(e,i,s,n):this._applyOrWhereCondition(e,i,s,n)}}async fetchRelatedRows(e,t,r={}){if(e.through){let o=await this.db(e.through).whereIn(e.throughLocalKey,t),i=this.db(e.table).whereIn(e.foreignKey,o.map(t=>t[e.throughForeignKey]));return Object.keys(r).length>0&&this._applyWithWhereConditions(i,r),i}{let o=this.db(e.table).whereIn(e.foreignKey,t);return Object.keys(r).length>0&&this._applyWithWhereConditions(o,r),o}}async fetchAndAttachRelated(e){const{parentRows:t,relName:r,model:o,withTree:i,relation:s,withWhere:n={}}=e;if(!s){const e=this.getHookService().getModelInstance(o),s=`get${r.charAt(0).toUpperCase()+r.slice(1)}Relation`;if("function"==typeof e[s]){const{direct:l,nested:a}=this._getWithWhereForRelation(n,r),h={rows:t,relName:r,model:o,withTree:i,controller:this.controllerWrapper,relation:o.hasRelations[r],qb:this,db:this.db,withWhere:l,nestedWithWhere:a};await e[s](h)}else logger.warn(`Method ${s} not found in model ${o.name}`);return t}let l=t.map(e=>e[s.localKey]);const a="one"===s?.type;let h=[];const{direct:c,nested:p}=this._getWithWhereForRelation(n,r);let u={...c};try{const e=this.utils.getModel(this.controllerWrapper,r);if(this.controllerWrapper?.hookService){await this.controllerWrapper.hookService.executeHasSoftDeleteHook(e)&&(u={...u,deleted_at:null})}}catch(e){}h=await this.fetchRelatedRows(s,l,u);let y=new Map;for(const e of h){let t=e[s.foreignKey];y.has(t)||y.set(t,[]),y.get(t).push(e)}for(const e of t){let t=e[s.localKey];a&&1==y.get(t)?.length?e[r]=y.get(t)[0]:e[r]=y.get(t)||[]}let d=Object.keys(i);for(const e of d){let o=i[e],s=t.filter(e=>a?e[r]:e[r].length>0).map(e=>e[r]).reduce((e,t)=>e.concat(t),[]),n=this.utils.getModel(this.controllerWrapper,r);await this.fetchAndAttachRelated({parentRows:s,relName:e,model:n,withTree:o,relation:n.hasRelations[e],withWhere:p})}return t}filterWhere(e,t=""){return t?Object.keys(e).filter(e=>e.includes(t)).reduce((r,o)=>(r[o.replace(t,"")]=e[o],r),{}):Object.keys(e).filter(e=>!e.includes(".")).reduce((t,r)=>(t[r]=e[r],t),{})}async getQuery(e,t){try{const{where:r={},with:o,withWhere:i,select:s,orderBy:n={column:"id",direction:"asc"},limit:l=10,offset:a=0,page:h,groupBy:c,having:p,distinct:u,join:y,leftJoin:d,rightJoin:f,innerJoin:g,count:W=!1}=t;let w=this.getQueryBuilder(e);s&&(Array.isArray(s)||"string"==typeof s)?w.select(s):w.select("*"),u&&(Array.isArray(u)||"string"==typeof u?w.distinct(u):w.distinct()),y&&this._applyJoins(w,y,"join"),d&&this._applyJoins(w,d,"leftJoin"),f&&this._applyJoins(w,f,"rightJoin"),g&&this._applyJoins(w,g,"innerJoin"),this._applyWhereClause(w,r,o),c&&(Array.isArray(c),w.groupBy(c)),p&&this._applyHavingClause(w,p),n&&this._applyOrderBy(w,n);let b=!1,m=l,_=a,A=1,j=0;h&&l>0&&(A=Math.max(1,parseInt(h)),_=(A-1)*l),l>0&&(w.limit(m),_>0&&w.offset(_));const k=[],C=w.toSQL();k.push(C.sql);const J=await w;if(o&&o.length>0){const t=this.buildWithTree(o);for(const r of Object.keys(t))await this.fetchAndAttachRelated({parentRows:J,relName:r,model:e,withTree:t[r],relation:e.hasRelations[r],withWhere:i||{}})}let B=null;if(l>0)try{let t=this.getQueryBuilder(e);r&&Object.keys(r).length>0&&this._applyWhereClause(t,r),y&&this._applyJoins(t,y,"join"),d&&this._applyJoins(t,d,"leftJoin"),f&&this._applyJoins(t,f,"rightJoin"),g&&this._applyJoins(t,g,"innerJoin");const o=t.count("* as cnt");k.push(o.toSQL().sql);B=(await o.first()).cnt}catch(e){logger.warn("Failed to get total count:",e.message),B=J.length}l>0&&null!==B&&(j=Math.ceil(B/l),b=A<j);const N=b?A+1:null,O=A>1?A-1:null;return{data:J,totalCount:B,...this.controllerWrapper.debug?{sqlDebug:k}:{},...l>0?{pagination:{page:A,limit:m,offset:_,totalPages:j,hasNext:b,hasPrev:A>1,nextPage:N,prevPage:O}}:{}}}catch(t){throw logger.error("QueryService.getQuery error:",t),new Error(`Failed to execute query: ${t.message} on model ${e.name}`)}}getSumQuery(e,t){const{where:r={},join:o,leftJoin:i,rightJoin:s,innerJoin:n}=t,l=t.data||t,a=l.sumColumn,h=l.sumFormula;if(!a&&!h)throw new Error("Sum action requires either data.sumColumn or data.sumFormula");const c=e=>'"'+String(e).replace(/["\\]/g,"")+'"';let p;if(a){const e=String(a).trim().replace(/[^a-zA-Z0-9_]/g,"");if(!e)throw new Error("data.sumColumn must be a valid column name");p="SUM("+c(e)+")"}else{const e=String(h).trim();if(!/\{[a-zA-Z0-9_]+\}/.test(e))throw new Error("data.sumFormula must contain at least one {columnName}");let t=0;for(const r of e)if("("===r)t++;else if(")"===r&&(t--,t<0))break;if(0!==t)throw new Error("data.sumFormula has unbalanced or misordered parentheses ( and )");const r=e.replace(/\{[a-zA-Z0-9_]+\}/g,"@");if(!/^[\s0-9.+*\/\-()@]+$/.test(r))throw new Error("data.sumFormula may only use BODMAS: numbers, + - * /, parentheses, and {columnName}");p="SUM("+e.replace(/\{([a-zA-Z0-9_]+)\}/g,(e,t)=>c(t))+")"}let u=this.getQueryBuilder(e);return o&&this._applyJoins(u,o,"join"),i&&this._applyJoins(u,i,"leftJoin"),s&&this._applyJoins(u,s,"rightJoin"),n&&this._applyJoins(u,n,"innerJoin"),this._applyWhereClause(u,r,[]),u.select(this.db.raw(p+" as sum")),u}_applyWhereWithArray(e,t,r){for(const o of t)this._applyWhereClause(e,o,r)}_applyWhereClause(e,t,r=[]){if(Array.isArray(t))this._applyWhereWithArray(e,t,r);else{if(t&&Object.keys(t).length>0){let r=this.helperUtility.getDotWalkQuery(t);logger.debug({filteredWhere:r}),r=this.helperUtility.objectFilter(r,(e,t)=>!e.startsWith("!")&&("__exists__"!==e&&("object"!=typeof t||null===t)));for(const[t,o]of Object.entries(r)){const{joinType:r="AND",column:i}=this.parseWhereColumn(t),{operator:s,value:n}=this.parseWhereValue(o);"AND"===r?this._applyAndWhereCondition(e,i,s,n):this._applyOrWhereCondition(e,i,s,n)}}this._applyNestedWhere(e,t,r)}}_getNestedWhereConditions(e,t){if(!e||"object"!=typeof e)return{};const r=`${t}.`,o={};for(const[i,s]of Object.entries(e))if(i.startsWith(r)){o[i.slice(r.length)]=s}else i===t&&!0===s&&(o.__exists__=!0);return o}_getTopLevelRelationsFromWhere(e){if(!e||"object"!=typeof e)return[];const t=new Set;for(const r of Object.keys(e))if(r.includes(".")){const e=r.split(".")[0];t.add(e)}else r.startsWith("!")&&t.add(r);return[...t]}_applyNestedWhere(e,t,r){let o=this,i=e._getMyModel();const s=this._getTopLevelRelationsFromWhere(t);if(0!==s.length)for(let r of s){let s=r.startsWith("!"),n=s?r.slice(1):r,l=this._getNestedWhereConditions(t,r);if(0===Object.keys(l).length)continue;let a,h=i.hasRelations?.[n];if(!h){logger.warn(`Relation ${n} not found in model ${i.modelName}`);continue}try{a=this.utils.getModel(this.controllerWrapper,h.table||n)}catch(e){try{a=this.utils.getModel(this.controllerWrapper,n)}catch(e){logger.warn(`Model for relation ${n} (table: ${h.table}) not found`);continue}}e[s?"whereNotExists":"whereExists"](function(){let e=o.getQueryBuilder(a,this.select("*").from(h.table));e.whereRaw(`"${h.table}"."${h.foreignKey}" = "${i.table}"."${h.localKey}"`);if(!(!0===l.__exists__&&1===Object.keys(l).length)){const t={...l};delete t.__exists__,o._applyWhereClause(e,t,[])}})}}_applyJoins(e,t,r){const o=Array.isArray(t)?t:[t];for(const t of o)"string"==typeof t?e[r](t):"object"==typeof t&&(t.table&&t.on?e[r](t.table,t.on):t.table&&t.first&&t.operator&&t.second&&e[r](t.table,t.first,t.operator,t.second))}_applyWithWhere(e,t){try{if(Array.isArray(t))for(const r of t)"string"==typeof r?e.withWhere(r):"object"==typeof r&&e.withWhere(r.column,r.operator,r.value);else if("object"==typeof t)for(const[r,o]of Object.entries(t))e.withWhere(r,o)}catch(e){logger.warn("Failed to apply withWhere:",e.message)}}_applyHavingClause(e,t){for(const[r,o]of Object.entries(t))"object"==typeof o&&o.operator?e.having(r,o.operator,o.value):e.having(r,o)}_applyOrderBy(e,t){if(Array.isArray(t))for(const r of t)"string"==typeof r?e.orderBy(r):"object"==typeof r&&e.orderBy(r.column,r.direction||"asc");else"string"==typeof t?e.orderBy(t):"object"==typeof t&&e.orderBy(t.column,t.direction||"asc")}}module.exports=QueryBuilder;
1
+ const HelperUtility=require("./HelperUtility"),logger=require("../../Logger");class QueryBuilder{constructor(e,t,r=null){this.db=e,this.utils=t,this.controllerWrapper=r,this.helperUtility=new HelperUtility}getHookService(){return this.controllerWrapper.hookService}getQueryBuilder(e,t=null){let r=this.db(e.table);return t&&(r=t),r._getMyModel=()=>e,r}parseValue(e){return this.helperUtility.parseValue(e)}parseWhereValue(e){return this.helperUtility.parseWhereValue(e)}parseWhereColumn(e){return this.helperUtility.parseWhereColumn(e)}_applyOrWhereCondition(e,t,r,o){if(null!==o)if(Array.isArray(o))e.orWhereIn(t,o);else switch(r){case"between":e.orWhereBetween(t,o);break;case"notBetween":e.orWhereNotBetween(t,o);break;case"in":e.orWhereIn(t,o);break;case"notIn":e.orWhereNotIn(t,o);break;case"like":e.orWhere(t,"like",o);break;default:e.orWhere(t,r,o)}else e.orWhereNull(t)}_applyAndWhereCondition(e,t,r,o){if(null!==o)if(Array.isArray(o))e.whereIn(t,o);else switch(r){case"between":e.whereBetween(t,o);break;case"notBetween":e.whereNotBetween(t,o);break;case"in":e.whereIn(t,o);break;case"notIn":e.whereNotIn(t,o);break;case"like":e.where(t,"like",o);break;default:e.where(t,r,o)}else e.whereNull(t)}buildWithTree(e,t=null){return this.helperUtility.dotWalkTree(e,{resolver:({current:e,part:r,source:o})=>t?t({current:e,part:r,source:o}):{}})}_getWithWhereForRelation(e,t){if(!e||"object"!=typeof e)return{direct:{},nested:{}};const r=`${t}.`,o={},i={};for(const[t,n]of Object.entries(e))if(t.startsWith(r)){const e=t.slice(r.length);e.includes(".")?i[e]=n:o[e]=n}return{direct:o,nested:i}}_applyWithWhereConditions(e,t){for(const[r,o]of Object.entries(t)){const{joinType:t="AND",column:i}=this.parseWhereColumn(r),{operator:n,value:s}=this.parseWhereValue(o);"AND"===t?this._applyAndWhereCondition(e,i,n,s):this._applyOrWhereCondition(e,i,n,s)}}async fetchRelatedRows(e,t,r={}){if(e.through){const o=await this.db(e.through).whereIn(e.throughLocalKey,t),i=this.db(e.table).whereIn(e.foreignKey,o.map(t=>t[e.throughForeignKey]));return Object.keys(r).length>0&&this._applyWithWhereConditions(i,r),i}{const o=this.db(e.table).whereIn(e.foreignKey,t);return Object.keys(r).length>0&&this._applyWithWhereConditions(o,r),o}}async fetchAndAttachRelated(e){const{parentRows:t,relName:r,model:o,withTree:i,relation:n,withWhere:s={}}=e;if(!n){const e=this.getHookService().getModelInstance(o),n=`get${r.charAt(0).toUpperCase()+r.slice(1)}Relation`;if("function"==typeof e[n]){const{direct:l,nested:a}=this._getWithWhereForRelation(s,r),h={rows:t,relName:r,model:o,withTree:i,controller:this.controllerWrapper,relation:o.hasRelations[r],qb:this,db:this.db,withWhere:l,nestedWithWhere:a};await e[n](h)}else logger.warn(`Method ${n} not found in model ${o.name}`);return t}const l=t.map(e=>e[n.localKey]),a="one"===n?.type;let h=[];const{direct:c,nested:p}=this._getWithWhereForRelation(s,r);let u={...c};try{const e=this.utils.getModel(this.controllerWrapper,r);if(this.controllerWrapper?.hookService){await this.controllerWrapper.hookService.executeHasSoftDeleteHook(e)&&(u={...u,deleted_at:null})}}catch(e){}h=await this.fetchRelatedRows(n,l,u);const y=new Map;for(const e of h){const t=e[n.foreignKey];y.has(t)||y.set(t,[]),y.get(t).push(e)}for(const e of t){const t=e[n.localKey];a&&1==y.get(t)?.length?e[r]=y.get(t)[0]:e[r]=y.get(t)||[]}const d=Object.keys(i);for(const e of d){const o=i[e],n=t.filter(e=>a?e[r]:e[r].length>0).map(e=>e[r]).reduce((e,t)=>e.concat(t),[]),s=this.utils.getModel(this.controllerWrapper,r);await this.fetchAndAttachRelated({parentRows:n,relName:e,model:s,withTree:o,relation:s.hasRelations[e],withWhere:p})}return t}filterWhere(e,t=""){return t?Object.keys(e).filter(e=>e.includes(t)).reduce((r,o)=>(r[o.replace(t,"")]=e[o],r),{}):Object.keys(e).filter(e=>!e.includes(".")).reduce((t,r)=>(t[r]=e[r],t),{})}buildSelectQuery(e,t){const{where:r={},with:o,select:i,orderBy:n={column:"id",direction:"asc"},limit:s=10,offset:l=0,page:a,groupBy:h,having:c,distinct:p,join:u,leftJoin:y,rightJoin:d,innerJoin:f}=t,g=this.getQueryBuilder(e);i&&(Array.isArray(i)||"string"==typeof i)?g.select(i):g.select("*"),p&&(Array.isArray(p)||"string"==typeof p?g.distinct(p):g.distinct()),u&&this._applyJoins(g,u,"join"),y&&this._applyJoins(g,y,"leftJoin"),d&&this._applyJoins(g,d,"rightJoin"),f&&this._applyJoins(g,f,"innerJoin"),this._applyWhereClause(g,r,o),h&&g.groupBy(h),c&&this._applyHavingClause(g,c),n&&this._applyOrderBy(g,n);let W=l;return a&&s>0&&(W=(Math.max(1,parseInt(a))-1)*s),s>0&&(g.limit(s),W>0&&g.offset(W)),g}async getQuery(e,t){try{const{where:r={},with:o,withWhere:i,limit:n=10,offset:s=0,page:l,join:a,leftJoin:h,rightJoin:c,innerJoin:p}=t,u=this.buildSelectQuery(e,t);let y=!1;const d=n;let f=s,g=1,W=0;l&&n>0&&(g=Math.max(1,parseInt(l)),f=(g-1)*n);const w=[],b=u.toSQL();w.push(b.sql);const m=await u;if(o&&o.length>0){const t=this.buildWithTree(o);for(const r of Object.keys(t))await this.fetchAndAttachRelated({parentRows:m,relName:r,model:e,withTree:t[r],relation:e.hasRelations[r],withWhere:i||{}})}let _=null;if(n>0)try{const t=this.getQueryBuilder(e);r&&Object.keys(r).length>0&&this._applyWhereClause(t,r),a&&this._applyJoins(t,a,"join"),h&&this._applyJoins(t,h,"leftJoin"),c&&this._applyJoins(t,c,"rightJoin"),p&&this._applyJoins(t,p,"innerJoin");const o=t.count("* as cnt");w.push(o.toSQL().sql);_=(await o.first()).cnt}catch(e){logger.warn("Failed to get total count:",e.message),_=m.length}n>0&&null!==_&&(W=Math.ceil(_/n),y=g<W);const A=y?g+1:null,j=g>1?g-1:null;return{data:m,totalCount:_,...this.controllerWrapper.debug?{sqlDebug:w}:{},...n>0?{pagination:{page:g,limit:d,offset:f,totalPages:W,hasNext:y,hasPrev:g>1,nextPage:A,prevPage:j}}:{}}}catch(t){throw logger.error("QueryService.getQuery error:",t),new Error(`Failed to execute query: ${t.message} on model ${e.name}`)}}getSumQuery(e,t){const{where:r={},join:o,leftJoin:i,rightJoin:n,innerJoin:s}=t,l=t.data||t,a=l.sumColumn,h=l.sumFormula;if(!a&&!h)throw new Error("Sum action requires either data.sumColumn or data.sumFormula");const c=e=>'"'+String(e).replace(/["\\]/g,"")+'"';let p;if(a){const e=String(a).trim().replace(/[^a-zA-Z0-9_]/g,"");if(!e)throw new Error("data.sumColumn must be a valid column name");p="SUM("+c(e)+")"}else{const e=String(h).trim();if(!/\{[a-zA-Z0-9_]+\}/.test(e))throw new Error("data.sumFormula must contain at least one {columnName}");let t=0;for(const r of e)if("("===r)t++;else if(")"===r&&(t--,t<0))break;if(0!==t)throw new Error("data.sumFormula has unbalanced or misordered parentheses ( and )");const r=e.replace(/\{[a-zA-Z0-9_]+\}/g,"@");if(!/^[\s0-9.+*\/\-()@]+$/.test(r))throw new Error("data.sumFormula may only use BODMAS: numbers, + - * /, parentheses, and {columnName}");p="SUM("+e.replace(/\{([a-zA-Z0-9_]+)\}/g,(e,t)=>c(t))+")"}const u=this.getQueryBuilder(e);return o&&this._applyJoins(u,o,"join"),i&&this._applyJoins(u,i,"leftJoin"),n&&this._applyJoins(u,n,"rightJoin"),s&&this._applyJoins(u,s,"innerJoin"),this._applyWhereClause(u,r,[]),u.select(this.db.raw(p+" as sum")),u}_applyWhereWithArray(e,t,r){for(const o of t)this._applyWhereClause(e,o,r)}_applyWhereClause(e,t,r=[]){if(Array.isArray(t))this._applyWhereWithArray(e,t,r);else{if(t&&Object.keys(t).length>0){let r=this.helperUtility.getDotWalkQuery(t);logger.debug({filteredWhere:r}),r=this.helperUtility.objectFilter(r,(e,t)=>!e.startsWith("!")&&("__exists__"!==e&&("object"!=typeof t||null===t)));for(const[t,o]of Object.entries(r)){const{joinType:r="AND",column:i}=this.parseWhereColumn(t),{operator:n,value:s}=this.parseWhereValue(o);"AND"===r?this._applyAndWhereCondition(e,i,n,s):this._applyOrWhereCondition(e,i,n,s)}}this._applyNestedWhere(e,t,r)}}_getNestedWhereConditions(e,t){if(!e||"object"!=typeof e)return{};const r=`${t}.`,o={};for(const[i,n]of Object.entries(e))if(i.startsWith(r)){o[i.slice(r.length)]=n}else i===t&&!0===n&&(o.__exists__=!0);return o}_getTopLevelRelationsFromWhere(e){if(!e||"object"!=typeof e)return[];const t=new Set;for(const r of Object.keys(e))if(r.includes(".")){const e=r.split(".")[0];t.add(e)}else r.startsWith("!")&&t.add(r);return[...t]}_applyNestedWhere(e,t,r){const o=this,i=e._getMyModel(),n=this._getTopLevelRelationsFromWhere(t);if(0!==n.length)for(const r of n){const n=r.startsWith("!"),s=n?r.slice(1):r,l=this._getNestedWhereConditions(t,r);if(0===Object.keys(l).length)continue;const a=i.hasRelations?.[s];if(!a){logger.warn(`Relation ${s} not found in model ${i.modelName}`);continue}let h;try{h=this.utils.getModel(this.controllerWrapper,a.table||s)}catch(e){try{h=this.utils.getModel(this.controllerWrapper,s)}catch(e){logger.warn(`Model for relation ${s} (table: ${a.table}) not found`);continue}}e[n?"whereNotExists":"whereExists"](function(){const e=o.getQueryBuilder(h,this.select("*").from(a.table));e.whereRaw("??.?? = ??.??",[a.table,a.foreignKey,i.table,a.localKey]);if(!(!0===l.__exists__&&1===Object.keys(l).length)){const t={...l};delete t.__exists__,o._applyWhereClause(e,t,[])}})}}_applyJoins(e,t,r){const o=Array.isArray(t)?t:[t];for(const t of o)"string"==typeof t?e[r](t):"object"==typeof t&&(t.table&&t.on?e[r](t.table,t.on):t.table&&t.first&&t.operator&&t.second&&e[r](t.table,t.first,t.operator,t.second))}_applyWithWhere(e,t){try{if(Array.isArray(t))for(const r of t)"string"==typeof r?e.withWhere(r):"object"==typeof r&&e.withWhere(r.column,r.operator,r.value);else if("object"==typeof t)for(const[r,o]of Object.entries(t))e.withWhere(r,o)}catch(e){logger.warn("Failed to apply withWhere:",e.message)}}_applyHavingClause(e,t){for(const[r,o]of Object.entries(t))"object"==typeof o&&o.operator?e.having(r,o.operator,o.value):e.having(r,o)}_applyOrderBy(e,t){if(Array.isArray(t))for(const r of t)"string"==typeof r?e.orderBy(r):"object"==typeof r&&e.orderBy(r.column,r.direction||"asc");else"string"==typeof t?e.orderBy(t):"object"==typeof t&&e.orderBy(t.column,t.direction||"asc")}}module.exports=QueryBuilder;
@@ -1 +1 @@
1
- const QueryBuilder=require("./QueryBuilder");class QueryService{constructor(e,t,r=null){this.db=e,this.utils=t,this.controllerWrapper=r,this.queryBuilder=new QueryBuilder(e,t,r)}async getQuery(e,t){return await this.queryBuilder.getQuery(e,t)}async getSoftDeleteQuery(e,t){return await this.queryBuilder.getQuery(e,{...t,where:{...t.where||{},deleted_at:null}})}async executeShowQuery(e,t){let r=await this.getQuery(e,{...t,limit:1,offset:0});return r.data.length>0?r.data[0]:null}async executeCountQuery(e,t){let r=await this.db(e.table).count();return Object.values(r[0])[0]}async executeSumQuery(e,t){const r=await this.queryBuilder.getSumQuery(e,t).first(),a=r&&null!=r.sum?r.sum:0;return Number(a)}async executeCreateQuery(e,t){return await this.db(e.table).insert(t.data).returning("*")}async executeUpdateQuery(e,t){return await this.db(e.table).where(t.where).update(t.data).returning("*")}async executeDeleteQuery(e,t){return await this.db(e.table).where(t.where).delete()}async executeSoftDeleteQuery(e,t){return await this.db(e.table).where(t.where).update({deleted_at:new Date}).returning("*")}async executeUpsertQuery(e,t){return await this.db(e.table).insert(t.data).onConflict(t.conflict).update(t.data)}async executeReplaceQuery(e,t){return await this.db(e.table).replace(t.data)}async executeSyncQuery(e,t){return{insertOrUpdateQuery:await this.db(e.table).insert(t.data).onConflict(t.conflict).update(t.data),deleteQuery:await this.db(e.table).where(t.where).delete()}}}module.exports=QueryService;
1
+ const QueryBuilder=require("./QueryBuilder");class QueryService{constructor(e,t,r=null){this.db=e,this.utils=t,this.controllerWrapper=r,this.queryBuilder=new QueryBuilder(e,t,r)}async getQuery(e,t){return await this.queryBuilder.getQuery(e,t)}async getSoftDeleteQuery(e,t){return await this.queryBuilder.getQuery(e,{...t,where:{...t.where||{},deleted_at:null}})}async executeShowQuery(e,t){const r=await this.getQuery(e,{...t,limit:1,offset:0});return r.data.length>0?r.data[0]:null}async executeCountQuery(e,t){const r=await this.db(e.table).count();return Object.values(r[0])[0]}async executeSumQuery(e,t){const r=await this.queryBuilder.getSumQuery(e,t).first(),u=r&&null!=r.sum?r.sum:0;return Number(u)}async executeCreateQuery(e,t){return await this.db(e.table).insert(t.data).returning("*")}async executeUpdateQuery(e,t){return await this.db(e.table).where(t.where).update(t.data).returning("*")}async executeDeleteQuery(e,t){return await this.db(e.table).where(t.where).delete()}async executeSoftDeleteQuery(e,t){return await this.db(e.table).where(t.where).update({deleted_at:new Date}).returning("*")}async executeUpsertQuery(e,t){return await this.db(e.table).insert(t.data).onConflict(t.conflict).merge(t.data)}async executeReplaceQuery(e,t){return await this.db(e.table).replace(t.data)}buildDryRun(e,t,r){const u=this._dryRunBuilders(e,t,r).map(e=>{const t=e.toSQL();return{sql:t.sql,bindings:t.bindings}});return{success:!0,dryRun:!0,action:r,model:e.name,sql:u[0]?u[0].sql:null,bindings:u[0]?u[0].bindings:[],statements:u}}_dryRunBuilders(e,t,r){const u=e.table,a=t.where||{};switch(r){case"list":return[this.queryBuilder.buildSelectQuery(e,t)];case"show":return[this.queryBuilder.buildSelectQuery(e,{...t,limit:1,offset:0})];case"count":return[this.db(u).count()];case"sum":return[this.queryBuilder.getSumQuery(e,t)];case"create":return[this.db(u).insert(t.data).returning("*")];case"update":return[this.db(u).where(a).update(t.data).returning("*")];case"softDelete":return[this.db(u).where(a).update({deleted_at:new Date}).returning("*")];case"delete":return[this.db(u).where(a).delete()];case"replace":return[this.db(u).replace(t.data)];case"upsert":return[this.db(u).insert(t.data).onConflict(t.conflict).merge(t.data)];case"sync":return[this.db(u).insert(t.data).onConflict(t.conflict).merge(t.data),this.db(u).where(a).delete()];default:return[]}}async executeSyncQuery(e,t){return this.db.transaction(async r=>({insertOrUpdateQuery:await r(e.table).insert(t.data).onConflict(t.conflict).merge(t.data),deleteQuery:await r(e.table).where(t.where).delete()}))}}module.exports=QueryService;
@@ -1 +1 @@
1
- const CurdTable=require("./CurdTable"),HelperUtility=require("./HelperUtility"),{getSchemaType:getSchemaType}=require("./DataTypeMap"),logger=require("../../Logger");class SyncTable{constructor(e,t,n=null){this.db=e,this.utils=t,this.controllerWrapper=n,this.curd=new CurdTable(e,t,n),this.helperUtility=new HelperUtility}_getClientName(){return"pg"}async executeSql(e,t=[]){return this.db.raw(e,t)}async existsTable(e){return this.db.schema.hasTable(e)}async getTablesReferencedByTable(e,t="public"){return(await this.executeSql("SELECT\n tc.table_name AS \"TABLE_NAME\", -- The table that contains the FK (e.g., 'Posts')\n kcu.column_name AS \"REFERENCING_COLUMN_NAME\", -- The FK column (e.g., 'user_id')\n kcu2.column_name AS \"REFERENCED_COLUMN_NAME\" -- The PK/Unique column (e.g., 'id')\n FROM\n information_schema.referential_constraints AS rc\n -- Join to get the table and column being referenced (the PK/Unique key on the target table)\n JOIN\n information_schema.key_column_usage AS kcu2\n ON rc.unique_constraint_name = kcu2.constraint_name\n AND rc.unique_constraint_schema = kcu2.constraint_schema\n -- Join to get the table constraint information for the foreign key\n JOIN\n information_schema.table_constraints AS tc\n ON rc.constraint_name = tc.constraint_name\n AND rc.constraint_schema = tc.table_schema\n -- Join to get the column in the referencing table (the FK column)\n JOIN\n information_schema.key_column_usage AS kcu\n ON rc.constraint_name = kcu.constraint_name\n AND rc.constraint_schema = kcu.table_schema\n -- Link the FK column to its corresponding PK/Unique column\n AND kcu.position_in_unique_constraint = kcu2.ordinal_position\n WHERE\n kcu2.table_name = ?\n AND kcu2.table_schema = ?\n AND tc.constraint_type = 'FOREIGN KEY'\n ORDER BY\n tc.table_name, kcu.column_name",[e,t])).rows||[]}async getTablesWithColumn(e){return(await this.executeSql("\n SELECT table_name\n FROM information_schema.columns\n WHERE column_name = ?\n ",[e])).rows||[]}async getCurrentColumns(e){const t=(await this.executeSql('\n SELECT \n c.column_name AS "COLUMN_NAME",\n c.data_type AS "DATA_TYPE",\n c.udt_name AS "UDT_NAME",\n c.is_nullable AS "IS_NULLABLE",\n c.column_default AS "COLUMN_DEFAULT",\n c.character_maximum_length AS "CHARACTER_MAXIMUM_LENGTH",\n pgd.description AS "COMMENT",\n tc.constraint_type AS "CONSTRAINT_TYPE",\n kcu2.table_name AS "REFERENCED_TABLE_NAME",\n kcu2.column_name AS "REFERENCED_COLUMN_NAME"\n FROM information_schema.columns c\n LEFT JOIN pg_catalog.pg_statio_all_tables as st\n ON c.table_schema = st.schemaname AND c.table_name = st.relname\n LEFT JOIN pg_catalog.pg_description pgd\n ON pgd.objoid = st.relid AND pgd.objsubid = c.ordinal_position\n LEFT JOIN information_schema.key_column_usage kcu\n ON c.table_name = kcu.table_name\n AND c.column_name = kcu.column_name\n AND c.table_schema = kcu.table_schema\n LEFT JOIN information_schema.table_constraints tc\n ON kcu.constraint_name = tc.constraint_name\n AND kcu.table_schema = tc.table_schema\n LEFT JOIN information_schema.referential_constraints rc\n ON tc.constraint_name = rc.constraint_name\n AND tc.table_schema = rc.constraint_schema\n LEFT JOIN information_schema.key_column_usage kcu2\n ON rc.unique_constraint_name = kcu2.constraint_name\n AND rc.unique_constraint_schema = kcu2.constraint_schema\n AND kcu.ordinal_position = kcu2.ordinal_position\n WHERE c.table_schema = ?\n AND c.table_name = ?\n ORDER BY c.ordinal_position\n ',["public",e])).rows||[],n={};for(const e of t)n[e.COLUMN_NAME]=this.utils.formatColumnDef(e.COLUMN_NAME,e);return n}logColumnChanges(e,t,n){logger.debug(`${t.name} changed`),e.isTypeChanged&&logger.debug(`Type changed from ${t.type} to ${n.type}`),e.isSizeChanged&&logger.debug(`Size changed from ${t.size} to ${n.size}`),e.isNullableChanged&&logger.debug(`Nullable changed from ${t.nullable} to ${n.nullable}`),e.isPrimaryChanged&&logger.debug(`Primary changed from ${t.primary} to ${n.primary}`),e.isUniqueChanged&&logger.debug(`Unique changed from ${t.unique} to ${n.unique}`),e.isAutoIncrementChanged&&logger.debug(`Auto increment changed from ${t.autoIncrement} to ${n.autoIncrement}`),e.isDefaultChanged&&logger.debug(`Default changed from ${t.default} to ${n.default}`),e.isOnUpdateChanged&&logger.debug(`On update changed from ${t.onUpdate} to ${n.onUpdate}`),e.isCommentChanged&&logger.debug(`Comment changed from ${t.comment} to ${n.comment}`),e.isForeignKeyChanged&&logger.debug(`ForeignKey changed from ${t.hasForeignKey} to ${n.hasForeignKey}`)}hasColumnChanged(e,t){const n={isNullableChanged:e.nullable!==t.nullable,isTypeChanged:e.type!==t.type,isSizeChanged:e.size!==t.size,isUnsignedChanged:e.isUnsigned!==t.isUnsigned,isPrimaryChanged:e.primary!==t.primary,isUniqueChanged:e.unique!==t.unique,isAutoIncrementChanged:e.autoIncrement!==t.autoIncrement,isDefaultChanged:e.default!==t.default,isOnUpdateChanged:e.onUpdate!==t.onUpdate,isCommentChanged:e.comment!==t.comment,isForeignKeyChanged:e.hasForeignKey!==t.hasForeignKey},a=Object.values(n).some(Boolean);return a&&this.logColumnChanges(n,e,t),a}async getAlterations(e){const t={add:[],drop:[],modify:[]},n=await this.getCurrentColumns(e.table);for(const[a,o]of Object.entries(e.columns)){const e=this.utils.formatColumnSchema(a,o),i=n[a];i?(e.oldColDef=i,this.hasColumnChanged(i,e)&&t.modify.push(e)):t.add.push(e)}for(const a of Object.keys(n))e.columns[a]||t.drop.push({name:a});return t}getColumnStr(e,t,n={actionType:"CREATE",tableName:""}){const{actionType:a,tableName:o}=n,i="string"==typeof t?this.utils.formatColumnSchema(e,t):t;let l=`"${e}"`,s=i.type,c=i.size??this.utils.getDefaultTypeSize(s);if(c&&["character varying","varchar","char","character"].includes(s)?l+=` ${s}(${c})`:l+="numeric"===s&&c?` ${s}(${c})`:` ${s}`,i.autoIncrement&&("integer"===s||"int4"===s?l=`"${e}" SERIAL`:"bigint"!==s&&"int8"!==s||(l=`"${e}" BIGSERIAL`)),i.primary&&["CREATE","ADD_COLUMN"].includes(a)&&(l+=" PRIMARY KEY"),!1===i.nullable||void 0===i.nullable?l+=" NOT NULL":!0===i.nullable&&(l+=" NULL"),i.unique&&(l+=" UNIQUE"),void 0!==i.default&&null!==i.default&&!i.primary&&!i.autoIncrement){l+=this.utils.isInternalDefault(i.default)?` DEFAULT ${i.default}`:` DEFAULT '${i.default}'`}if(i.hasForeignKey&&1===i.foreignMapTables?.length&&"CREATE"===a){const{table:e,column:t}=i.foreignMapTables[0];l+=` REFERENCES "${e}"("${t}")`,l+=" ON DELETE RESTRICT ON UPDATE RESTRICT"}return l}async createTable(e){const t=e.table,n=e.columns,a=[],o=[];for(const[e,i]of Object.entries(n)){const n="string"==typeof i?this.utils.formatColumnSchema(e,i):i;if(a.push(this.getColumnStr(e,n,{actionType:"CREATE",tableName:t})),n.hasForeignKey&&1===n.foreignMapTables?.length){const{table:a,column:i}=n.foreignMapTables[0],l=`fk_${t}_${e}_${a}_${i}`;o.push(`CONSTRAINT "${l}" FOREIGN KEY ("${e}") REFERENCES "${a}"("${i}") ON DELETE RESTRICT ON UPDATE RESTRICT`)}}const i=`CREATE TABLE IF NOT EXISTS "${t}" (${a.concat(o).join(", ")})`;await this.executeSql(i);for(const[e,a]of Object.entries(n)){const n="string"==typeof a?this.utils.formatColumnSchema(e,a):a;if(n.comment){const a=`COMMENT ON COLUMN "${t}"."${e}" IS '${this.utils.escapeComment(n.comment)}'`;await this.executeSql(a)}}for(const n of e.indexes)if(n?.columns?.length){const e=`CREATE ${n.unique?"UNIQUE":""} INDEX IF NOT EXISTS "${n.name}" ON "${t}" (${n.columns.map(e=>`"${e}"`).join(", ")})`;await this.executeSql(e)}}async alterTable(e,t){if(!t||"object"!=typeof t)throw new Error("alterations must be an object");const n=[];if(t.add?.length)for(const a of t.add)n.push(`ADD COLUMN ${this.getColumnStr(a.name,a,{actionType:"ADD_COLUMN",tableName:e})}`);if(t.drop?.length)for(const e of t.drop)n.push(`DROP COLUMN "${e.name}"`);if(t.modify?.length)for(const e of t.modify){if(e.type){let t=e.type;e.size&&["character varying","varchar","char","character"].includes(e.type)&&(t+=`(${e.size})`),n.push(`ALTER COLUMN "${e.name}" TYPE ${t}`)}if(!1===e.nullable||void 0===e.nullable?n.push(`ALTER COLUMN "${e.name}" SET NOT NULL`):e.nullable,void 0!==e.default&&null!==e.default){let t=this.utils.isInternalDefault(e.default);"string"!=typeof e.default||t?n.push(`ALTER COLUMN "${e.name}" SET DEFAULT ${e.default}`):n.push(`ALTER COLUMN "${e.name}" SET DEFAULT '${e.default}'`)}else n.push(`ALTER COLUMN "${e.name}" DROP DEFAULT`);e.comment}if(!n.length)return void logger.info("No alterations to apply for",e);const a=`ALTER TABLE "${e}" ${n.join(", ")}`;if(await this.executeSql(a),t.modify?.length)for(const n of t.modify)if(n.comment){const t=`COMMENT ON COLUMN "${e}"."${n.name}" IS '${this.utils.escapeComment(n.comment)}'`;await this.executeSql(t)}}async alterColumn(e,t,n){const a="string"==typeof n?this.utils.formatColumnSchema(t,n):n;if(a.type){let n=a.type;a.size&&["character varying","varchar","char","character"].includes(a.type)&&(n+=`(${a.size})`);const o=`ALTER TABLE "${e}" ALTER COLUMN "${t}" TYPE ${n}`;await this.executeSql(o)}if(!1===a.nullable||void 0===a.nullable?await this.executeSql(`ALTER TABLE "${e}" ALTER COLUMN "${t}" SET NOT NULL`):!0===a.nullable&&await this.executeSql(`ALTER TABLE "${e}" ALTER COLUMN "${t}" DROP NOT NULL`),void 0!==a.default&&null!==a.default){this.utils.isInternalDefault(a.default)?await this.executeSql(`ALTER TABLE "${e}" ALTER COLUMN "${t}" SET DEFAULT ${a.default}`):await this.executeSql(`ALTER TABLE "${e}" ALTER COLUMN "${t}" SET DEFAULT '${a.default}'`)}else await this.executeSql(`ALTER TABLE "${e}" ALTER COLUMN "${t}" DROP DEFAULT`);if(a.comment){const n=`COMMENT ON COLUMN "${e}"."${t}" IS '${this.utils.escapeComment(a.comment)}'`;await this.executeSql(n)}}async alterIndex(e,t,n){const a=Array.isArray(n.columns)?n.columns:[n.columns],o=`CREATE ${n.unique?"UNIQUE ":""}INDEX "${t}" ON "${e}" (${a.map(e=>`"${e}"`).join(", ")})`;await this.executeSql(o)}async dropIndex(e,t){const n=`DROP INDEX IF EXISTS "${t}"`;await this.executeSql(n)}async dropTable(e){const t=`DROP TABLE IF EXISTS "${e}" CASCADE`;await this.executeSql(t)}async updateTable(e){logger.warn(`Update table not implemented for ${e.table}`)}async syncTable(e){if(await this.existsTable(e.table)){const t=await this.getAlterations(e);return void await this.alterTable(e.table,t)}await this.createTable(e)}async syncSeedData(e,t){let n=this.utils.getModel(this.controllerWrapper,t),a=await this.curd.processRequest({action:"count"},n.name,{isCallFromServer:!0});if(logger.debug("count",a),a>0)logger.info("Seed data already synced for",t);else if(e.seed&&Array.isArray(e.seed)){for(const t of e.seed)await this.curd.processRequest({action:"create",data:t},n.name,{isCallFromServer:!0});logger.info("Seed data synced for",t)}}async syncDatabase(){if(!this.controllerWrapper?.schema)throw new Error("controllerWrapper.schema not set.");const e=this.controllerWrapper.schema;for(const t of Object.keys(e))await this.syncTable(e[t]),await this.syncSeedData(e[t],t);logger.info("Database synced by SyncTable...")}async getTablesOfDatabase(){return((await this.db.raw("\n SELECT table_name\n FROM information_schema.tables\n WHERE table_schema = 'public'\n AND table_type = 'BASE TABLE'\n ")).rows||[]).map(e=>e.table_name)}getColumnString(e){return Object.keys(e).reduce((t,n)=>{const a=e[n];let o=a.type,i=a.size,l=a.isUnsigned,s=a.primary,c=a.autoIncrement,r=a.nullable,u=a.unique,m=a.default,h=a.onUpdate,g=a.comment,d=a.hasForeignKey,E=a.foreignMapTables?.[0]?.table,f=a.foreignMapTables?.[0]?.column,T=getSchemaType(o);return t[n]=`${T}`,i&&(t[n]+=`|size:${i}`),l&&(t[n]+="|unsigned"),s&&(t[n]+="|primaryKey"),c&&(t[n]+="|autoIncrement"),r&&(t[n]+="|nullable"),u&&(t[n]+="|unique"),m&&(t[n]+=`|default:${m}`),h&&(t[n]+=`|onUpdate:${h}`),g&&(t[n]+=`|comment:${g}`),d&&(t[n]+=`|foreignKey:${E}:${f}`),t},{})}async getRelations(e){let t=await this.getCurrentColumns(e);const n=Object.keys(t).filter(e=>t[e].hasForeignKey).reduce((e,n)=>{let a=t[n];if(!a)return e;if(0===a.foreignMapTables?.length)return e;let o=a.foreignMapTables;for(const t of o){let a=t.table,o=t.column;e[this.helperUtility.modelName(a)]={type:"one",table:a,localKey:n,foreignKey:o,through:null,throughLocalKey:null,throughForeignKey:null}}return e},{}),a=(this.helperUtility.modelName(e).toLowerCase(),await this.getTablesReferencedByTable(e)),o=a.map(e=>e.TABLE_NAME);for(const e of o){const t=this.helperUtility.modelName(e),o=a.find(t=>t.TABLE_NAME===e)?.REFERENCED_COLUMN_NAME,i=a.find(t=>t.TABLE_NAME===e)?.COLUMN_NAME;n[t]={type:"many",table:e,localKey:o,foreignKey:i,through:null,throughLocalKey:null,throughForeignKey:null}}return n}async generateSchema(){const e=await this.getTablesOfDatabase(),t={};for(const n of e){let e=this.helperUtility.modelName(n),a=await this.getRelations(n);t[e]={table:n,alias:e,columns:this.getColumnString(await this.getCurrentColumns(n)),modelName:e,seed:[],hasRelations:a,indexes:[]}}return t}}module.exports=SyncTable;
1
+ const BaseSyncTable=require("../BaseSyncTable"),logger=require("../../Logger");class PostgresSyncTable extends BaseSyncTable{_getClientName(){return"pg"}async _listTables(){return this.db("information_schema.tables").where({table_schema:"public",table_type:"BASE TABLE"}).pluck("table_name")}_supportsUnsigned(){return!1}async _applyExtras(e){for(const[n,t]of Object.entries(e.columns)){("string"==typeof t?this.utils.formatColumnSchema(n,t):t).onUpdate&&this._warnOnUnsupportedModifier("onUpdate",e.table,n)}}async _getRelations(e){const n=await this.db("information_schema.table_constraints AS tc").join("information_schema.key_column_usage AS kcu","tc.constraint_name","kcu.constraint_name").join("information_schema.referential_constraints AS rc","tc.constraint_name","rc.constraint_name").join("information_schema.key_column_usage AS kcu2",function(){this.on("rc.unique_constraint_name","=","kcu2.constraint_name").andOn("kcu.position_in_unique_constraint","=","kcu2.ordinal_position")}).where({"tc.constraint_type":"FOREIGN KEY","tc.table_name":e}).select("kcu.column_name AS local_column","kcu2.table_name AS ref_table","kcu2.column_name AS ref_column"),t={};for(const e of n)t[e.local_column]={one:{table:e.ref_table,column:e.ref_column}};return t}async getTablesOfDatabase(){return this._listTables()}async executeSql(e,n=[]){return logger.debug("executeSql (legacy)",{sql:e,params:n}),this.db.raw(e,n)}}module.exports=PostgresSyncTable;
@@ -1 +1 @@
1
- class BaseUtility{getModel(e,t){let n=e?.schema,r=null,i=Object.keys(n);if(i.forEach(e=>{e===t&&(r=n[e])}),r||i.forEach(e=>{let i=n[e];i.table===t&&(r=i)}),r)return{...r,name:t,columns:Object.keys(r.columns).map(e=>{let t=r.columns[e];return this.parseColumnString(e,t)})};throw new Error(`Model ${t} not found`)}getDefaultTypeSize(e,t="toUpperCase"){let n=e;switch(n?.[t]&&"function"==typeof n[t]&&(n=n[t]()),n){case"VARCHAR":return 255;case"TINYINT":return 1;case"INT":return 11;default:return 0}}map2DbType(e,t="toLowerCase"){let n;switch(e){case"number":n="INT";break;case"string":default:n="VARCHAR";break;case"boolean":n="TINYINT";break;case"date":n="DATETIME";break;case"json":n="JSON"}return n?.[t]&&"function"==typeof n[t]&&(n=n[t]()),n}map2DbDefault(e){return"now"===e?"CURRENT_TIMESTAMP":e}getCollenedValue(e,{splitChar:t=":",give:n="right",trimWrap:r="{}"}={}){if(null==e)return null;const i=String(e),l=i.indexOf(t),a=e=>{if(!r)return e;if("string"==typeof r&&2===r.length){const[t,n]=r;return e.startsWith(t)&&e.endsWith(n)?e.slice(1,-1):e}return"string"==typeof r&&r.length&&e.startsWith(r)&&e.endsWith(r)?e.slice(r.length,-r.length):e};if(l>=0){const e=i.slice(0,l).trim(),r=i.slice(l+t.length).trim();return"both"===n?{left:a(e),right:a(r)}:a("left"===n?e:r)}return a(i)}parseForeignKey(e){if(!e)return{foreignMapTables:[]};const t=this.getCollenedValue(e),[n,r="id"]=String(t||"").split(":"),i=(this.getCollenedValue(n)||"").split(",").filter(Boolean),l=(this.getCollenedValue(r)||"").split(",").filter(Boolean);return{foreignMapTables:i.map((e,t)=>({table:e,column:l[t]||l[0]||"id"}))}}parseColumnString(e,t){const[n,...r]=String(t).split("|"),i=e=>r.find(t=>t.startsWith(e+":")),l=e=>r.join("|").includes(e),a=e=>e&&e.includes(":")?e.slice(e.indexOf(":")+1):null,s=i("default"),u=i("onUpdate"),o=i("comment"),c=i("foreignKey"),p=i("size"),m=this.parseForeignKey(c),g=!!c,f=this.map2DbType(n),E=p?a(p):this.getDefaultTypeSize(f);return{name:e,type:f,size:E,isUnsigned:l("unsigned")||l("primaryKey")||g,columnType:`${n}${E?`(${E})`:""}`,nullable:!l("notNull"),primary:l("primaryKey"),autoIncrement:l("autoIncrement"),unique:l("unique"),default:this.map2DbDefault(a(s)),onUpdate:this.map2DbDefault(a(u)),comment:a(o)||"",hasForeignKey:g,...m}}formatColumnSchema(e,t){return this.parseColumnString(e,t)}formatColumnDef(e,t){return{name:e,type:t.DATA_TYPE,size:t.CHARACTER_MAXIMUM_LENGTH||this.getDefaultTypeSize(t.DATA_TYPE),isUnsigned:String(t.COLUMN_TYPE||"").toLowerCase().includes("unsigned"),columnType:t.COLUMN_TYPE,nullable:"YES"===t.IS_NULLABLE,primary:"PRI"===t.COLUMN_KEY,unique:"UNI"===t.COLUMN_KEY,autoIncrement:String(t.EXTRA||"").toLowerCase().includes("auto_increment"),hasForeignKey:"MUL"===t.COLUMN_KEY,comment:t.COMMENT,default:t.COLUMN_DEFAULT,onUpdate:((e="")=>{const t=String(e).match(/on update\s+([a-zA-Z_]+)/i);return t?t[1]:null})(t.EXTRA),foreignMapTables:"MUL"===t.COLUMN_KEY&&t.REFERENCED_TABLE_NAME?[{table:t.REFERENCED_TABLE_NAME,column:t.REFERENCED_COLUMN_NAME}]:[]}}escapeComment(e){return null==e?"":String(e).replace(/'/g,"\\'")}getDefaultTypeSize(e){return this.getDefaultTypeSize(e)}}module.exports=BaseUtility;
1
+ const KormError=require("../../KormError");class BaseUtility{getModel(e,t){const n=e?.schema;let r=null;const i=Object.keys(n);if(i.forEach(e=>{e===t&&(r=n[e])}),r||i.forEach(e=>{const i=n[e];i.table===t&&(r=i)}),r)return{...r,name:t,columns:Object.keys(r.columns).map(e=>{const t=r.columns[e];return this.parseColumnString(e,t)})};throw KormError.unknownModel({model:t,available:Object.keys(n||{})})}getDefaultTypeSize(e,t="toUpperCase"){let n=e;switch(n?.[t]&&"function"==typeof n[t]&&(n=n[t]()),n){case"VARCHAR":return 255;case"TINYINT":return 1;case"INT":return 11;default:return 0}}map2DbType(e,t="toLowerCase"){let n;switch(e){case"number":n="INT";break;case"string":default:n="VARCHAR";break;case"boolean":n="TINYINT";break;case"date":n="DATETIME";break;case"json":n="JSON"}return n?.[t]&&"function"==typeof n[t]&&(n=n[t]()),n}map2DbDefault(e){return"now"===e?"CURRENT_TIMESTAMP":e}getCollenedValue(e,{splitChar:t=":",give:n="right",trimWrap:r="{}"}={}){if(null==e)return null;const i=String(e),l=i.indexOf(t),a=e=>{if(!r)return e;if("string"==typeof r&&2===r.length){const[t,n]=r;return e.startsWith(t)&&e.endsWith(n)?e.slice(1,-1):e}return"string"==typeof r&&r.length&&e.startsWith(r)&&e.endsWith(r)?e.slice(r.length,-r.length):e};if(l>=0){const e=i.slice(0,l).trim(),r=i.slice(l+t.length).trim();return"both"===n?{left:a(e),right:a(r)}:a("left"===n?e:r)}return a(i)}parseForeignKey(e){if(!e)return{foreignMapTables:[]};const t=this.getCollenedValue(e),[n,r="id"]=String(t||"").split(":"),i=(this.getCollenedValue(n)||"").split(",").filter(Boolean),l=(this.getCollenedValue(r)||"").split(",").filter(Boolean);return{foreignMapTables:i.map((e,t)=>({table:e,column:l[t]||l[0]||"id"}))}}parseColumnString(e,t){const[n,...r]=String(t).split("|"),i=e=>r.find(t=>t.startsWith(e+":")),l=e=>r.join("|").includes(e),a=e=>e&&e.includes(":")?e.slice(e.indexOf(":")+1):null,s=i("default"),o=i("onUpdate"),u=i("comment"),c=i("foreignKey"),m=i("size"),p=this.parseForeignKey(c),g=!!c,E=this.map2DbType(n),f=m?a(m):this.getDefaultTypeSize(E);return{name:e,type:E,size:f,isUnsigned:l("unsigned")||l("primaryKey")||g,columnType:`${n}${f?`(${f})`:""}`,nullable:!l("notNull"),primary:l("primaryKey"),autoIncrement:l("autoIncrement"),unique:l("unique"),default:this.map2DbDefault(a(s)),onUpdate:this.map2DbDefault(a(o)),comment:a(u)||"",hasForeignKey:g,...p}}formatColumnSchema(e,t){return this.parseColumnString(e,t)}formatColumnDef(e,t){return{name:e,type:t.DATA_TYPE,size:t.CHARACTER_MAXIMUM_LENGTH||this.getDefaultTypeSize(t.DATA_TYPE),isUnsigned:String(t.COLUMN_TYPE||"").toLowerCase().includes("unsigned"),columnType:t.COLUMN_TYPE,nullable:"YES"===t.IS_NULLABLE,primary:"PRI"===t.COLUMN_KEY,unique:"UNI"===t.COLUMN_KEY,autoIncrement:String(t.EXTRA||"").toLowerCase().includes("auto_increment"),hasForeignKey:"MUL"===t.COLUMN_KEY,comment:t.COMMENT,default:t.COLUMN_DEFAULT,onUpdate:((e="")=>{const t=String(e).match(/on update\s+([a-zA-Z_]+)/i);return t?t[1]:null})(t.EXTRA),foreignMapTables:"MUL"===t.COLUMN_KEY&&t.REFERENCED_TABLE_NAME?[{table:t.REFERENCED_TABLE_NAME,column:t.REFERENCED_COLUMN_NAME}]:[]}}escapeComment(e){return null==e?"":String(e).replace(/'/g,"\\'")}}module.exports=BaseUtility;
@@ -1 +1 @@
1
- const QueryService=require("./QueryService"),HookService=require("./HookService");class CurdTable{constructor(e,r,t=null){if(this.db=e,this.utils=r,this.controllerWrapper=t,this.hookService=new HookService(e,r,t),this.queryService=new QueryService(e,r,t),!this.queryService)throw new Error("CurdTable requires queryService (execute*Query / getQuery).")}async processRequest(e,r=null,t={}){const o=this.controllerWrapper;let s=this.utils.getModel(this.controllerWrapper,r);const c=e?.action||"list";let a=null;const i={model:s,action:c,request:e,ctx:t,controller:o};switch(this.hookService?.executeValidatorHook&&await this.hookService.executeValidatorHook({...i}),this.hookService?.executeBeforeHook&&(e.beforeActionData=await this.hookService.executeBeforeHook({...i})),c){case"count":a=await this.queryService.executeCountQuery(s,e);break;case"sum":a=await this.queryService.executeSumQuery(s,e);break;case"list":a=await this.hookService.executeHasSoftDeleteHook(s)?await this.queryService.getSoftDeleteQuery(s,e):await this.queryService.getQuery(s,e);break;case"show":a=await this.queryService.executeShowQuery(s,e);break;case"create":a=await this.queryService.executeCreateQuery(s,e);break;case"update":{const r=await this.queryService.executeUpdateQuery(s,e);if(!r)throw new Error(`Record not found or not updated: ${s.table} returned ${r}`);a={message:"Record updated successfully",data:r,success:!0};break}case"replace":if(a=await this.queryService.executeReplaceQuery(s,e),!a)throw new Error(`Record not found or not replaced: ${r} returned ${a}`);a={message:"Record replaced successfully",data:a,success:!0};break;case"upsert":if(a=await this.queryService.executeUpsertQuery(s,e),!a)throw new Error(`Record not found or not upserted: ${r} returned ${a}`);a={message:"Record upserted successfully",data:a,success:!0};break;case"sync":if(a=await this.queryService.executeSyncQuery(s,e),!a)throw new Error(`Record not found or not synced: ${r} returned ${a}`);a={message:"Record synced successfully",data:a,success:!0};break;case"delete":{let t=null;if(t=await this.hookService.executeHasSoftDeleteHook(s)?await this.queryService.executeSoftDeleteQuery(s,e):await this.queryService.executeDeleteQuery(s,e),!t)throw new Error(`Record not found or not deleted: ${r} returned ${t}`);a={message:"Record deleted successfully",data:t,success:!0};break}default:if(!this.hookService?.executeCustomAction)throw new Error(`Unknown action "${c}" and no custom action hook provided.`);a=await this.hookService.executeCustomAction({...i})}if(this.hookService?.executeAfterHook&&(a=await this.hookService.executeAfterHook({...i,data:a})),e?.other_requests&&"object"==typeof e.other_requests){const r={},o=Object.entries(e.other_requests);for(const[e,s]of o)Array.isArray(s)?r[e]=await Promise.all(s.map(r=>this.processRequest(r,e,t))):r[e]=await this.processRequest(s,e,t);a.other_responses=r}return a}}module.exports=CurdTable;
1
+ const QueryService=require("./QueryService"),HookService=require("./HookService"),KormError=require("../../KormError");class CurdTable{constructor(e,r,t=null){if(this.db=e,this.utils=r,this.controllerWrapper=t,this.hookService=new HookService(e,r,t),this.queryService=new QueryService(e,r,t),!this.queryService)throw new KormError("CurdTable requires queryService (execute*Query / getQuery).",{code:KormError.CODES.INTERNAL})}async processRequest(e,r=null,t={}){const o=this.controllerWrapper,s=this.utils.getModel(this.controllerWrapper,r),c=e?.action||"list";let i=null;const a={model:s,action:c,request:e,ctx:t,controller:o};if(this.hookService?.executeValidatorHook&&await this.hookService.executeValidatorHook({...a}),e?.dryRun)return this.buildDryRunResult(s,e,c);switch(this.hookService?.executeBeforeHook&&(e.beforeActionData=await this.hookService.executeBeforeHook({...a})),c){case"count":i=await this.queryService.executeCountQuery(s,e);break;case"sum":i=await this.queryService.executeSumQuery(s,e);break;case"list":i=await this.hookService.executeHasSoftDeleteHook(s)?await this.queryService.getSoftDeleteQuery(s,e):await this.queryService.getQuery(s,e);break;case"show":i=await this.queryService.executeShowQuery(s,e);break;case"create":i=await this.queryService.executeCreateQuery(s,e);break;case"update":{const r=await this.queryService.executeUpdateQuery(s,e);if(!r)throw KormError.noMatchingRow({action:c,model:s.name});i={message:"Record updated successfully",data:r,success:!0};break}case"replace":if(i=await this.queryService.executeReplaceQuery(s,e),!i)throw KormError.noMatchingRow({action:c,model:s.name});i={message:"Record replaced successfully",data:i,success:!0};break;case"upsert":if(i=await this.queryService.executeUpsertQuery(s,e),!i)throw KormError.noMatchingRow({action:c,model:s.name});i={message:"Record upserted successfully",data:i,success:!0};break;case"sync":if(i=await this.queryService.executeSyncQuery(s,e),!i)throw KormError.noMatchingRow({action:c,model:s.name});i={message:"Record synced successfully",data:i,success:!0};break;case"delete":{let r=null;if(r=await this.hookService.executeHasSoftDeleteHook(s)?await this.queryService.executeSoftDeleteQuery(s,e):await this.queryService.executeDeleteQuery(s,e),!r)throw KormError.noMatchingRow({action:c,model:s.name});i={message:"Record deleted successfully",data:r,success:!0};break}default:if(!this.hookService?.executeCustomAction)throw KormError.unknownAction({action:c,model:s?.name});i=await this.hookService.executeCustomAction({...a})}if(this.hookService?.executeAfterHook&&(i=await this.hookService.executeAfterHook({...a,data:i})),e?.other_requests&&"object"==typeof e.other_requests){const r={},o=Object.entries(e.other_requests);for(const[e,s]of o)Array.isArray(s)?r[e]=await Promise.all(s.map(r=>this.processRequest(r,e,t))):r[e]=await this.processRequest(s,e,t);i.other_responses=r}return i}async buildDryRunResult(e,r,t){if(!["list","show","count","sum","create","update","replace","upsert","sync","delete"].includes(t))throw KormError.unknownAction({action:t,model:e?.name});let o=t,s=r;const c=await this.hookService.executeHasSoftDeleteHook(e);return c&&"delete"===t?o="softDelete":c&&"list"===t&&(s={...r,where:{...r.where||{},deleted_at:null}}),this.queryService.buildDryRun(e,s,o)}}module.exports=CurdTable;
@@ -1 +1 @@
1
- const path=require("path");class HookService{constructor(e,t,o=null){this.db=e,this.utils=t,this.controllerWrapper=o,this.controllerWrapper.hookService=this,this.appRoot=o&&o.resolverPath?o.resolverPath:process.cwd()}loadModelClass(e){try{const t=path.join(this.appRoot,"models",`${e}.model.js`);delete require.cache[require.resolve(t)];return require(t)}catch(e){return}}getModelInstance(e){let t="string"==typeof e?e:e.modelName||e.name;const o=this.loadModelClass(t);if(o)return"function"==typeof o?new o:o}resolveModelHook(e,t,o){const r=e.modelName||e.name,s=this.loadModelClass(r);if(!s)return;const l=this.getModelInstance(e);let i;if("validate"===t)i="validate";else if("on"===t)i=`on${o.charAt(0).toUpperCase()+o.slice(1)}`;else if("before"===t)i=`before${o.charAt(0).toUpperCase()+o.slice(1)}`;else if("after"===t)i=`after${o.charAt(0).toUpperCase()+o.slice(1)}`;else{if("custom"!==t)return;i=`on${o.charAt(0).toUpperCase()+o.slice(1)}Action`}return"function"==typeof l[i]?l[i].bind(l):"function"==typeof s[i]?s[i].bind(s):void 0}async executeValidatorHook({model:e,action:t,request:o,ctx:r,controller:s}){const l=this.resolveModelHook(e,"validate",t);if(l)return await l({model:e,action:t,request:o,context:r,db:this.db,utils:this.utils,controller:s})}async executeBeforeHook({model:e,action:t,request:o,ctx:r,controller:s}){const l=this.resolveModelHook(e,"before",t);if(l)return await l({model:e,action:t,request:o,context:r,db:this.db,utils:this.utils,controller:s})}async executeAfterHook({model:e,action:t,data:o,request:r,ctx:s,controller:l}){const i=this.resolveModelHook(e,"after",t);return i?await i({model:e,action:t,data:o,request:r,context:s,db:this.db,utils:this.utils,controller:l}):o}async executeCustomAction({model:e,action:t,request:o,ctx:r,controller:s}){const l=this.resolveModelHook(e,"custom",t);if(l)return await l({model:e,action:t,request:o,context:r,db:this.db,utils:this.utils,controller:s});throw new Error(`No custom action hook found for ${e.modelName||e.name}.${t}`)}async executeHasSoftDeleteHook(e){const t=this.getModelInstance(e);if(!t)return!1;return t.hasOwnProperty("hasSoftDelete")&&!0===t.hasSoftDelete}}module.exports=HookService;
1
+ const path=require("path"),KormError=require("../../KormError");class HookService{constructor(e,t,o=null){this.db=e,this.utils=t,this.controllerWrapper=o,this.controllerWrapper.hookService=this,this.appRoot=o&&o.resolverPath?o.resolverPath:process.cwd()}loadModelClass(e){try{const t=path.join(this.appRoot,"models",`${e}.model.js`);delete require.cache[require.resolve(t)];return require(t)}catch(e){return}}getModelInstance(e){const t="string"==typeof e?e:e.modelName||e.name,o=this.loadModelClass(t);if(o)return"function"==typeof o?new o:o}resolveModelHook(e,t,o){const r=e.modelName||e.name,s=this.loadModelClass(r);if(!s)return;const l=this.getModelInstance(e);let i;if("validate"===t)i="validate";else if("on"===t)i=`on${o.charAt(0).toUpperCase()+o.slice(1)}`;else if("before"===t)i=`before${o.charAt(0).toUpperCase()+o.slice(1)}`;else if("after"===t)i=`after${o.charAt(0).toUpperCase()+o.slice(1)}`;else{if("custom"!==t)return;i=`on${o.charAt(0).toUpperCase()+o.slice(1)}Action`}return"function"==typeof l[i]?l[i].bind(l):"function"==typeof s[i]?s[i].bind(s):void 0}async executeValidatorHook({model:e,action:t,request:o,ctx:r,controller:s}){const l=this.resolveModelHook(e,"validate",t);if(l)return await l({model:e,action:t,request:o,context:r,db:this.db,utils:this.utils,controller:s})}async executeBeforeHook({model:e,action:t,request:o,ctx:r,controller:s}){const l=this.resolveModelHook(e,"before",t);if(l)return await l({model:e,action:t,request:o,context:r,db:this.db,utils:this.utils,controller:s})}async executeAfterHook({model:e,action:t,data:o,request:r,ctx:s,controller:l}){const i=this.resolveModelHook(e,"after",t);return i?await i({model:e,action:t,data:o,request:r,context:s,db:this.db,utils:this.utils,controller:l}):o}async executeCustomAction({model:e,action:t,request:o,ctx:r,controller:s}){const l=this.resolveModelHook(e,"custom",t);if(l)return await l({model:e,action:t,request:o,context:r,db:this.db,utils:this.utils,controller:s});throw KormError.unknownAction({action:t,model:e.modelName||e.name,hasCustomHook:!0})}async executeHasSoftDeleteHook(e){const t=this.getModelInstance(e);if(!t)return!1;return t.hasOwnProperty("hasSoftDelete")&&!0===t.hasSoftDelete}}module.exports=HookService;
@@ -1 +1 @@
1
- const HelperUtility=require("./HelperUtility"),logger=require("../../Logger");class QueryBuilder{constructor(e,t,r=null){this.db=e,this.utils=t,this.controllerWrapper=r,this.helperUtility=new HelperUtility}getHookService(){return this.controllerWrapper.hookService}getQueryBuilder(e,t=null){let r=this.db(e.table);return t&&(r=t),r._getMyModel=()=>e,r}parseValue(e){return this.helperUtility.parseValue(e)}parseWhereValue(e){return this.helperUtility.parseWhereValue(e)}parseWhereColumn(e){return this.helperUtility.parseWhereColumn(e)}_applyOrWhereCondition(e,t,r,o){if(null!==o)if(Array.isArray(o))e.orWhereIn(t,o);else switch(r){case"between":e.orWhereBetween(t,o);break;case"notBetween":e.orWhereNotBetween(t,o);break;case"in":e.orWhereIn(t,o);break;case"notIn":e.orWhereNotIn(t,o);break;case"like":e.orWhere(t,"like",o);break;default:e.orWhere(t,r,o)}else e.orWhereNull(t)}_applyAndWhereCondition(e,t,r,o){if(null!==o)if(Array.isArray(o))e.whereIn(t,o);else switch(r){case"between":e.whereBetween(t,o);break;case"notBetween":e.whereNotBetween(t,o);break;case"in":e.whereIn(t,o);break;case"notIn":e.whereNotIn(t,o);break;case"like":e.where(t,"like",o);break;default:e.where(t,r,o)}else e.whereNull(t)}buildWithTree(e,t=null){return this.helperUtility.dotWalkTree(e,{resolver:({current:e,part:r,source:o})=>t?t({current:e,part:r,source:o}):{}})}_getWithWhereForRelation(e,t){if(!e||"object"!=typeof e)return{direct:{},nested:{}};const r=`${t}.`,o={},i={};for(const[t,s]of Object.entries(e))if(t.startsWith(r)){const e=t.slice(r.length);e.includes(".")?i[e]=s:o[e]=s}return{direct:o,nested:i}}_applyWithWhereConditions(e,t){for(const[r,o]of Object.entries(t)){const{joinType:t="AND",column:i}=this.parseWhereColumn(r),{operator:s,value:n}=this.parseWhereValue(o);"AND"===t?this._applyAndWhereCondition(e,i,s,n):this._applyOrWhereCondition(e,i,s,n)}}async fetchRelatedRows(e,t,r={}){if(e.through){let o=await this.db(e.through).whereIn(e.throughLocalKey,t),i=this.db(e.table).whereIn(e.foreignKey,o.map(t=>t[e.throughForeignKey]));return Object.keys(r).length>0&&this._applyWithWhereConditions(i,r),i}{let o=this.db(e.table).whereIn(e.foreignKey,t);return Object.keys(r).length>0&&this._applyWithWhereConditions(o,r),o}}async fetchAndAttachRelated(e){const{parentRows:t,relName:r,model:o,withTree:i,relation:s,withWhere:n={}}=e;if(!s){const e=this.getHookService().getModelInstance(o),s=`get${r.charAt(0).toUpperCase()+r.slice(1)}Relation`;if("function"==typeof e[s]){const{direct:l,nested:a}=this._getWithWhereForRelation(n,r),h={rows:t,relName:r,model:o,withTree:i,controller:this.controllerWrapper,relation:o.hasRelations[r],qb:this,db:this.db,withWhere:l,nestedWithWhere:a};await e[s](h)}else logger.warn(`Method ${s} not found in model ${o.name}`);return t}let l=t.map(e=>e[s.localKey]);const a="one"===s?.type;let h=[];const{direct:c,nested:p}=this._getWithWhereForRelation(n,r);let u={...c};try{const e=this.utils.getModel(this.controllerWrapper,r);if(this.controllerWrapper?.hookService){await this.controllerWrapper.hookService.executeHasSoftDeleteHook(e)&&(u={...u,deleted_at:null})}}catch(e){}h=await this.fetchRelatedRows(s,l,u);let y=new Map;for(const e of h){let t=e[s.foreignKey];y.has(t)||y.set(t,[]),y.get(t).push(e)}for(const e of t){let t=e[s.localKey];a&&1==y.get(t)?.length?e[r]=y.get(t)[0]:e[r]=y.get(t)||[]}let d=Object.keys(i);for(const e of d){let o=i[e],s=t.filter(e=>a?e[r]:e[r].length>0).map(e=>e[r]).reduce((e,t)=>e.concat(t),[]),n=this.utils.getModel(this.controllerWrapper,r);await this.fetchAndAttachRelated({parentRows:s,relName:e,model:n,withTree:o,relation:n.hasRelations[e],withWhere:p})}return t}filterWhere(e,t=""){return t?Object.keys(e).filter(e=>e.includes(t)).reduce((r,o)=>(r[o.replace(t,"")]=e[o],r),{}):Object.keys(e).filter(e=>!e.includes(".")).reduce((t,r)=>(t[r]=e[r],t),{})}async getQuery(e,t){try{const{where:r={},with:o,withWhere:i,select:s,orderBy:n={column:"id",direction:"asc"},limit:l=10,offset:a=0,page:h,groupBy:c,having:p,distinct:u,join:y,leftJoin:d,rightJoin:f,innerJoin:g,count:W=!1}=t;let w=this.getQueryBuilder(e);s&&(Array.isArray(s)||"string"==typeof s)?w.select(s):w.select("*"),u&&(Array.isArray(u)||"string"==typeof u?w.distinct(u):w.distinct()),y&&this._applyJoins(w,y,"join"),d&&this._applyJoins(w,d,"leftJoin"),f&&this._applyJoins(w,f,"rightJoin"),g&&this._applyJoins(w,g,"innerJoin"),this._applyWhereClause(w,r,o),c&&(Array.isArray(c),w.groupBy(c)),p&&this._applyHavingClause(w,p),n&&this._applyOrderBy(w,n);let m=!1,b=l,_=a,A=1,j=0;h&&l>0&&(A=Math.max(1,parseInt(h)),_=(A-1)*l),l>0&&(w.limit(b),_>0&&w.offset(_));const k=[],C=w.toSQL();k.push(C.sql);const J=await w;if(o&&o.length>0){const t=this.buildWithTree(o);for(const r of Object.keys(t))await this.fetchAndAttachRelated({parentRows:J,relName:r,model:e,withTree:t[r],relation:e.hasRelations[r],withWhere:i||{}})}let B=null;if(l>0)try{let t=this.getQueryBuilder(e);r&&Object.keys(r).length>0&&this._applyWhereClause(t,r),y&&this._applyJoins(t,y,"join"),d&&this._applyJoins(t,d,"leftJoin"),f&&this._applyJoins(t,f,"rightJoin"),g&&this._applyJoins(t,g,"innerJoin");const o=t.count("* as cnt");k.push(o.toSQL().sql);B=(await o.first()).cnt}catch(e){logger.warn("Failed to get total count:",e.message),B=J.length}l>0&&null!==B&&(j=Math.ceil(B/l),m=A<j);const N=m?A+1:null,O=A>1?A-1:null;return{data:J,totalCount:B,...this.controllerWrapper.debug?{sqlDebug:k}:{},...l>0?{pagination:{page:A,limit:b,offset:_,totalPages:j,hasNext:m,hasPrev:A>1,nextPage:N,prevPage:O}}:{}}}catch(t){throw logger.error("QueryService.getQuery error:",t),new Error(`Failed to execute query: ${t.message} on model ${e.name}`)}}getSumQuery(e,t){const{where:r={},join:o,leftJoin:i,rightJoin:s,innerJoin:n}=t,l=t.data||t,a=l.sumColumn,h=l.sumFormula;if(!a&&!h)throw new Error("Sum action requires either data.sumColumn or data.sumFormula");const c=e=>'"'+String(e).replace(/["\\]/g,"")+'"';let p;if(a){const e=String(a).trim().replace(/[^a-zA-Z0-9_]/g,"");if(!e)throw new Error("data.sumColumn must be a valid column name");p="SUM("+c(e)+")"}else{const e=String(h).trim();if(!/\{[a-zA-Z0-9_]+\}/.test(e))throw new Error("data.sumFormula must contain at least one {columnName}");let t=0;for(const r of e)if("("===r)t++;else if(")"===r&&(t--,t<0))break;if(0!==t)throw new Error("data.sumFormula has unbalanced or misordered parentheses ( and )");const r=e.replace(/\{[a-zA-Z0-9_]+\}/g,"@");if(!/^[\s0-9.+*\/\-()@]+$/.test(r))throw new Error("data.sumFormula may only use BODMAS: numbers, + - * /, parentheses, and {columnName}");p="SUM("+e.replace(/\{([a-zA-Z0-9_]+)\}/g,(e,t)=>c(t))+")"}let u=this.getQueryBuilder(e);return o&&this._applyJoins(u,o,"join"),i&&this._applyJoins(u,i,"leftJoin"),s&&this._applyJoins(u,s,"rightJoin"),n&&this._applyJoins(u,n,"innerJoin"),this._applyWhereClause(u,r,[]),u.select(this.db.raw(p+" as sum")),u}_applyWhereWithArray(e,t,r){for(const o of t)this._applyWhereClause(e,o,r)}_applyWhereClause(e,t,r=[]){if(Array.isArray(t))this._applyWhereWithArray(e,t,r);else{if(t&&Object.keys(t).length>0){let r=this.helperUtility.getDotWalkQuery(t);r=this.helperUtility.objectFilter(r,(e,t)=>!e.startsWith("!")&&("__exists__"!==e&&("object"!=typeof t||null===t)));for(const[t,o]of Object.entries(r)){const{joinType:r="AND",column:i}=this.parseWhereColumn(t),{operator:s,value:n}=this.parseWhereValue(o);"AND"===r?this._applyAndWhereCondition(e,i,s,n):this._applyOrWhereCondition(e,i,s,n)}}this._applyNestedWhere(e,t,r)}}_getNestedWhereConditions(e,t){if(!e||"object"!=typeof e)return{};const r=`${t}.`,o={};for(const[i,s]of Object.entries(e))if(i.startsWith(r)){o[i.slice(r.length)]=s}else i===t&&!0===s&&(o.__exists__=!0);return o}_getTopLevelRelationsFromWhere(e){if(!e||"object"!=typeof e)return[];const t=new Set;for(const r of Object.keys(e))if(r.includes(".")){const e=r.split(".")[0];t.add(e)}else r.startsWith("!")&&t.add(r);return[...t]}_applyNestedWhere(e,t,r){let o=this,i=e._getMyModel();const s=this._getTopLevelRelationsFromWhere(t);if(0!==s.length)for(let r of s){let s=r.startsWith("!"),n=s?r.slice(1):r,l=this._getNestedWhereConditions(t,r);if(0===Object.keys(l).length)continue;let a,h=i.hasRelations?.[n];if(!h){logger.warn(`Relation ${n} not found in model ${i.modelName}`);continue}try{a=this.utils.getModel(this.controllerWrapper,h.table||n)}catch(e){try{a=this.utils.getModel(this.controllerWrapper,n)}catch(e){logger.warn(`Model for relation ${n} (table: ${h.table}) not found`);continue}}e[s?"whereNotExists":"whereExists"](function(){let e=o.getQueryBuilder(a,this.select("*").from(h.table));e.whereRaw(`"${h.table}"."${h.foreignKey}" = "${i.table}"."${h.localKey}"`);if(!(!0===l.__exists__&&1===Object.keys(l).length)){const t={...l};delete t.__exists__,o._applyWhereClause(e,t,[])}})}}_applyJoins(e,t,r){const o=Array.isArray(t)?t:[t];for(const t of o)"string"==typeof t?e[r](t):"object"==typeof t&&(t.table&&t.on?e[r](t.table,t.on):t.table&&t.first&&t.operator&&t.second&&e[r](t.table,t.first,t.operator,t.second))}_applyWithWhere(e,t){try{if(Array.isArray(t))for(const r of t)"string"==typeof r?e.withWhere(r):"object"==typeof r&&e.withWhere(r.column,r.operator,r.value);else if("object"==typeof t)for(const[r,o]of Object.entries(t))e.withWhere(r,o)}catch(e){logger.warn("Failed to apply withWhere:",e.message)}}_applyHavingClause(e,t){for(const[r,o]of Object.entries(t))"object"==typeof o&&o.operator?e.having(r,o.operator,o.value):e.having(r,o)}_applyOrderBy(e,t){if(Array.isArray(t))for(const r of t)"string"==typeof r?e.orderBy(r):"object"==typeof r&&e.orderBy(r.column,r.direction||"asc");else"string"==typeof t?e.orderBy(t):"object"==typeof t&&e.orderBy(t.column,t.direction||"asc")}}module.exports=QueryBuilder;
1
+ const HelperUtility=require("./HelperUtility"),logger=require("../../Logger");class QueryBuilder{constructor(e,t,r=null){this.db=e,this.utils=t,this.controllerWrapper=r,this.helperUtility=new HelperUtility}getHookService(){return this.controllerWrapper.hookService}getQueryBuilder(e,t=null){let r=this.db(e.table);return t&&(r=t),r._getMyModel=()=>e,r}parseValue(e){return this.helperUtility.parseValue(e)}parseWhereValue(e){return this.helperUtility.parseWhereValue(e)}parseWhereColumn(e){return this.helperUtility.parseWhereColumn(e)}_applyOrWhereCondition(e,t,r,o){if(null!==o)if(Array.isArray(o))e.orWhereIn(t,o);else switch(r){case"between":e.orWhereBetween(t,o);break;case"notBetween":e.orWhereNotBetween(t,o);break;case"in":e.orWhereIn(t,o);break;case"notIn":e.orWhereNotIn(t,o);break;case"like":e.orWhere(t,"like",o);break;default:e.orWhere(t,r,o)}else e.orWhereNull(t)}_applyAndWhereCondition(e,t,r,o){if(null!==o)if(Array.isArray(o))e.whereIn(t,o);else switch(r){case"between":e.whereBetween(t,o);break;case"notBetween":e.whereNotBetween(t,o);break;case"in":e.whereIn(t,o);break;case"notIn":e.whereNotIn(t,o);break;case"like":e.where(t,"like",o);break;default:e.where(t,r,o)}else e.whereNull(t)}buildWithTree(e,t=null){return this.helperUtility.dotWalkTree(e,{resolver:({current:e,part:r,source:o})=>t?t({current:e,part:r,source:o}):{}})}_getWithWhereForRelation(e,t){if(!e||"object"!=typeof e)return{direct:{},nested:{}};const r=`${t}.`,o={},i={};for(const[t,n]of Object.entries(e))if(t.startsWith(r)){const e=t.slice(r.length);e.includes(".")?i[e]=n:o[e]=n}return{direct:o,nested:i}}_applyWithWhereConditions(e,t){for(const[r,o]of Object.entries(t)){const{joinType:t="AND",column:i}=this.parseWhereColumn(r),{operator:n,value:s}=this.parseWhereValue(o);"AND"===t?this._applyAndWhereCondition(e,i,n,s):this._applyOrWhereCondition(e,i,n,s)}}async fetchRelatedRows(e,t,r={}){if(e.through){const o=await this.db(e.through).whereIn(e.throughLocalKey,t),i=this.db(e.table).whereIn(e.foreignKey,o.map(t=>t[e.throughForeignKey]));return Object.keys(r).length>0&&this._applyWithWhereConditions(i,r),i}{const o=this.db(e.table).whereIn(e.foreignKey,t);return Object.keys(r).length>0&&this._applyWithWhereConditions(o,r),o}}async fetchAndAttachRelated(e){const{parentRows:t,relName:r,model:o,withTree:i,relation:n,withWhere:s={}}=e;if(!n){const e=this.getHookService().getModelInstance(o),n=`get${r.charAt(0).toUpperCase()+r.slice(1)}Relation`;if("function"==typeof e[n]){const{direct:l,nested:a}=this._getWithWhereForRelation(s,r),h={rows:t,relName:r,model:o,withTree:i,controller:this.controllerWrapper,relation:o.hasRelations[r],qb:this,db:this.db,withWhere:l,nestedWithWhere:a};await e[n](h)}else logger.warn(`Method ${n} not found in model ${o.name}`);return t}const l=t.map(e=>e[n.localKey]),a="one"===n?.type;let h=[];const{direct:c,nested:p}=this._getWithWhereForRelation(s,r);let u={...c};try{const e=this.utils.getModel(this.controllerWrapper,r);if(this.controllerWrapper?.hookService){await this.controllerWrapper.hookService.executeHasSoftDeleteHook(e)&&(u={...u,deleted_at:null})}}catch(e){}h=await this.fetchRelatedRows(n,l,u);const y=new Map;for(const e of h){const t=e[n.foreignKey];y.has(t)||y.set(t,[]),y.get(t).push(e)}for(const e of t){const t=e[n.localKey];a&&1==y.get(t)?.length?e[r]=y.get(t)[0]:e[r]=y.get(t)||[]}const d=Object.keys(i);for(const e of d){const o=i[e],n=t.filter(e=>a?e[r]:e[r].length>0).map(e=>e[r]).reduce((e,t)=>e.concat(t),[]),s=this.utils.getModel(this.controllerWrapper,r);await this.fetchAndAttachRelated({parentRows:n,relName:e,model:s,withTree:o,relation:s.hasRelations[e],withWhere:p})}return t}filterWhere(e,t=""){return t?Object.keys(e).filter(e=>e.includes(t)).reduce((r,o)=>(r[o.replace(t,"")]=e[o],r),{}):Object.keys(e).filter(e=>!e.includes(".")).reduce((t,r)=>(t[r]=e[r],t),{})}buildSelectQuery(e,t){const{where:r={},with:o,select:i,orderBy:n={column:"id",direction:"asc"},limit:s=10,offset:l=0,page:a,groupBy:h,having:c,distinct:p,join:u,leftJoin:y,rightJoin:d,innerJoin:f}=t,g=this.getQueryBuilder(e);i&&(Array.isArray(i)||"string"==typeof i)?g.select(i):g.select("*"),p&&(Array.isArray(p)||"string"==typeof p?g.distinct(p):g.distinct()),u&&this._applyJoins(g,u,"join"),y&&this._applyJoins(g,y,"leftJoin"),d&&this._applyJoins(g,d,"rightJoin"),f&&this._applyJoins(g,f,"innerJoin"),this._applyWhereClause(g,r,o),h&&g.groupBy(h),c&&this._applyHavingClause(g,c),n&&this._applyOrderBy(g,n);let W=l;return a&&s>0&&(W=(Math.max(1,parseInt(a))-1)*s),s>0&&(g.limit(s),W>0&&g.offset(W)),g}async getQuery(e,t){try{const{where:r={},with:o,withWhere:i,limit:n=10,offset:s=0,page:l,join:a,leftJoin:h,rightJoin:c,innerJoin:p}=t,u=this.buildSelectQuery(e,t);let y=!1;const d=n;let f=s,g=1,W=0;l&&n>0&&(g=Math.max(1,parseInt(l)),f=(g-1)*n);const w=[],m=u.toSQL();w.push(m.sql);const b=await u;if(o&&o.length>0){const t=this.buildWithTree(o);for(const r of Object.keys(t))await this.fetchAndAttachRelated({parentRows:b,relName:r,model:e,withTree:t[r],relation:e.hasRelations[r],withWhere:i||{}})}let _=null;if(n>0)try{const t=this.getQueryBuilder(e);r&&Object.keys(r).length>0&&this._applyWhereClause(t,r),a&&this._applyJoins(t,a,"join"),h&&this._applyJoins(t,h,"leftJoin"),c&&this._applyJoins(t,c,"rightJoin"),p&&this._applyJoins(t,p,"innerJoin");const o=t.count("* as cnt");w.push(o.toSQL().sql);_=(await o.first()).cnt}catch(e){logger.warn("Failed to get total count:",e.message),_=b.length}n>0&&null!==_&&(W=Math.ceil(_/n),y=g<W);const A=y?g+1:null,j=g>1?g-1:null;return{data:b,totalCount:_,...this.controllerWrapper.debug?{sqlDebug:w}:{},...n>0?{pagination:{page:g,limit:d,offset:f,totalPages:W,hasNext:y,hasPrev:g>1,nextPage:A,prevPage:j}}:{}}}catch(t){throw logger.error("QueryService.getQuery error:",t),new Error(`Failed to execute query: ${t.message} on model ${e.name}`)}}getSumQuery(e,t){const{where:r={},join:o,leftJoin:i,rightJoin:n,innerJoin:s}=t,l=t.data||t,a=l.sumColumn,h=l.sumFormula;if(!a&&!h)throw new Error("Sum action requires either data.sumColumn or data.sumFormula");const c=e=>'"'+String(e).replace(/["\\]/g,"")+'"';let p;if(a){const e=String(a).trim().replace(/[^a-zA-Z0-9_]/g,"");if(!e)throw new Error("data.sumColumn must be a valid column name");p="SUM("+c(e)+")"}else{const e=String(h).trim();if(!/\{[a-zA-Z0-9_]+\}/.test(e))throw new Error("data.sumFormula must contain at least one {columnName}");let t=0;for(const r of e)if("("===r)t++;else if(")"===r&&(t--,t<0))break;if(0!==t)throw new Error("data.sumFormula has unbalanced or misordered parentheses ( and )");const r=e.replace(/\{[a-zA-Z0-9_]+\}/g,"@");if(!/^[\s0-9.+*\/\-()@]+$/.test(r))throw new Error("data.sumFormula may only use BODMAS: numbers, + - * /, parentheses, and {columnName}");p="SUM("+e.replace(/\{([a-zA-Z0-9_]+)\}/g,(e,t)=>c(t))+")"}const u=this.getQueryBuilder(e);return o&&this._applyJoins(u,o,"join"),i&&this._applyJoins(u,i,"leftJoin"),n&&this._applyJoins(u,n,"rightJoin"),s&&this._applyJoins(u,s,"innerJoin"),this._applyWhereClause(u,r,[]),u.select(this.db.raw(p+" as sum")),u}_applyWhereWithArray(e,t,r){for(const o of t)this._applyWhereClause(e,o,r)}_applyWhereClause(e,t,r=[]){if(Array.isArray(t))this._applyWhereWithArray(e,t,r);else{if(t&&Object.keys(t).length>0){let r=this.helperUtility.getDotWalkQuery(t);r=this.helperUtility.objectFilter(r,(e,t)=>!e.startsWith("!")&&("__exists__"!==e&&("object"!=typeof t||null===t)));for(const[t,o]of Object.entries(r)){const{joinType:r="AND",column:i}=this.parseWhereColumn(t),{operator:n,value:s}=this.parseWhereValue(o);"AND"===r?this._applyAndWhereCondition(e,i,n,s):this._applyOrWhereCondition(e,i,n,s)}}this._applyNestedWhere(e,t,r)}}_getNestedWhereConditions(e,t){if(!e||"object"!=typeof e)return{};const r=`${t}.`,o={};for(const[i,n]of Object.entries(e))if(i.startsWith(r)){o[i.slice(r.length)]=n}else i===t&&!0===n&&(o.__exists__=!0);return o}_getTopLevelRelationsFromWhere(e){if(!e||"object"!=typeof e)return[];const t=new Set;for(const r of Object.keys(e))if(r.includes(".")){const e=r.split(".")[0];t.add(e)}else r.startsWith("!")&&t.add(r);return[...t]}_applyNestedWhere(e,t,r){const o=this,i=e._getMyModel(),n=this._getTopLevelRelationsFromWhere(t);if(0!==n.length)for(const r of n){const n=r.startsWith("!"),s=n?r.slice(1):r,l=this._getNestedWhereConditions(t,r);if(0===Object.keys(l).length)continue;const a=i.hasRelations?.[s];if(!a){logger.warn(`Relation ${s} not found in model ${i.modelName}`);continue}let h;try{h=this.utils.getModel(this.controllerWrapper,a.table||s)}catch(e){try{h=this.utils.getModel(this.controllerWrapper,s)}catch(e){logger.warn(`Model for relation ${s} (table: ${a.table}) not found`);continue}}e[n?"whereNotExists":"whereExists"](function(){const e=o.getQueryBuilder(h,this.select("*").from(a.table));e.whereRaw("??.?? = ??.??",[a.table,a.foreignKey,i.table,a.localKey]);if(!(!0===l.__exists__&&1===Object.keys(l).length)){const t={...l};delete t.__exists__,o._applyWhereClause(e,t,[])}})}}_applyJoins(e,t,r){const o=Array.isArray(t)?t:[t];for(const t of o)"string"==typeof t?e[r](t):"object"==typeof t&&(t.table&&t.on?e[r](t.table,t.on):t.table&&t.first&&t.operator&&t.second&&e[r](t.table,t.first,t.operator,t.second))}_applyWithWhere(e,t){try{if(Array.isArray(t))for(const r of t)"string"==typeof r?e.withWhere(r):"object"==typeof r&&e.withWhere(r.column,r.operator,r.value);else if("object"==typeof t)for(const[r,o]of Object.entries(t))e.withWhere(r,o)}catch(e){logger.warn("Failed to apply withWhere:",e.message)}}_applyHavingClause(e,t){for(const[r,o]of Object.entries(t))"object"==typeof o&&o.operator?e.having(r,o.operator,o.value):e.having(r,o)}_applyOrderBy(e,t){if(Array.isArray(t))for(const r of t)"string"==typeof r?e.orderBy(r):"object"==typeof r&&e.orderBy(r.column,r.direction||"asc");else"string"==typeof t?e.orderBy(t):"object"==typeof t&&e.orderBy(t.column,t.direction||"asc")}}module.exports=QueryBuilder;
@@ -1 +1 @@
1
- const QueryBuilder=require("./QueryBuilder");class QueryService{constructor(e,t,r=null){this.db=e,this.utils=t,this.controllerWrapper=r,this.queryBuilder=new QueryBuilder(e,t,r)}async getQuery(e,t){return await this.queryBuilder.getQuery(e,t)}async getSoftDeleteQuery(e,t){return await this.queryBuilder.getQuery(e,{...t,where:{...t.where||{},deleted_at:null}})}async executeShowQuery(e,t){let r=await this.getQuery(e,{...t,limit:1,offset:0});return r.data.length>0?r.data[0]:null}async executeCountQuery(e,t){let r=await this.db(e.table).count();return Object.values(r[0])[0]}async executeSumQuery(e,t){const r=await this.queryBuilder.getSumQuery(e,t).first(),a=r&&null!=r.sum?r.sum:0;return Number(a)}async executeCreateQuery(e,t){return await this.db(e.table).insert(t.data).returning("*")}async executeUpdateQuery(e,t){return await this.db(e.table).where(t.where).update(t.data).returning("*")}async executeDeleteQuery(e,t){return await this.db(e.table).where(t.where).delete()}async executeSoftDeleteQuery(e,t){return await this.db(e.table).where(t.where).update({deleted_at:new Date}).returning("*")}async executeUpsertQuery(e,t){return await this.db(e.table).insert(t.data).onConflict(t.conflict).update(t.data)}async executeReplaceQuery(e,t){return await this.db(e.table).replace(t.data)}async executeSyncQuery(e,t){return{insertOrUpdateQuery:await this.db(e.table).insert(t.data).onConflict(t.conflict).update(t.data),deleteQuery:await this.db(e.table).where(t.where).delete()}}}module.exports=QueryService;
1
+ const QueryBuilder=require("./QueryBuilder");class QueryService{constructor(e,t,r=null){this.db=e,this.utils=t,this.controllerWrapper=r,this.queryBuilder=new QueryBuilder(e,t,r)}async getQuery(e,t){return await this.queryBuilder.getQuery(e,t)}async getSoftDeleteQuery(e,t){return await this.queryBuilder.getQuery(e,{...t,where:{...t.where||{},deleted_at:null}})}async executeShowQuery(e,t){const r=await this.getQuery(e,{...t,limit:1,offset:0});return r.data.length>0?r.data[0]:null}async executeCountQuery(e,t){const r=await this.db(e.table).count();return Object.values(r[0])[0]}async executeSumQuery(e,t){const r=await this.queryBuilder.getSumQuery(e,t).first(),u=r&&null!=r.sum?r.sum:0;return Number(u)}async executeCreateQuery(e,t){return await this.db(e.table).insert(t.data).returning("*")}async executeUpdateQuery(e,t){return await this.db(e.table).where(t.where).update(t.data).returning("*")}async executeDeleteQuery(e,t){return await this.db(e.table).where(t.where).delete()}async executeSoftDeleteQuery(e,t){return await this.db(e.table).where(t.where).update({deleted_at:new Date}).returning("*")}async executeUpsertQuery(e,t){return await this.db(e.table).insert(t.data).onConflict(t.conflict).merge(t.data)}async executeReplaceQuery(e,t){return await this.db(e.table).replace(t.data)}buildDryRun(e,t,r){const u=this._dryRunBuilders(e,t,r).map(e=>{const t=e.toSQL();return{sql:t.sql,bindings:t.bindings}});return{success:!0,dryRun:!0,action:r,model:e.name,sql:u[0]?u[0].sql:null,bindings:u[0]?u[0].bindings:[],statements:u}}_dryRunBuilders(e,t,r){const u=e.table,a=t.where||{};switch(r){case"list":return[this.queryBuilder.buildSelectQuery(e,t)];case"show":return[this.queryBuilder.buildSelectQuery(e,{...t,limit:1,offset:0})];case"count":return[this.db(u).count()];case"sum":return[this.queryBuilder.getSumQuery(e,t)];case"create":return[this.db(u).insert(t.data).returning("*")];case"update":return[this.db(u).where(a).update(t.data).returning("*")];case"softDelete":return[this.db(u).where(a).update({deleted_at:new Date}).returning("*")];case"delete":return[this.db(u).where(a).delete()];case"replace":return[this.db(u).replace(t.data)];case"upsert":return[this.db(u).insert(t.data).onConflict(t.conflict).merge(t.data)];case"sync":return[this.db(u).insert(t.data).onConflict(t.conflict).merge(t.data),this.db(u).where(a).delete()];default:return[]}}async executeSyncQuery(e,t){return this.db.transaction(async r=>({insertOrUpdateQuery:await r(e.table).insert(t.data).onConflict(t.conflict).merge(t.data),deleteQuery:await r(e.table).where(t.where).delete()}))}}module.exports=QueryService;
@@ -1 +1 @@
1
- const CurdTable=require("./CurdTable"),HelperUtility=require("./HelperUtility"),logger=require("../../Logger");class SyncTable{constructor(e,t,n=null){this.db=e,this.utils=t,this.controllerWrapper=n,this.curd=new CurdTable(e,t,n),this.helperUtility=new HelperUtility}_getClientName(){return"mysql"}async executeSql(e,t=[]){return this.db.raw(e,t)}async existsTable(e){return this.db.schema.hasTable(e)}async getCurrentColumns(e){const t=this.db.client.database(),[n]=await this.executeSql("\n SELECT \n c.COLUMN_NAME,\n c.DATA_TYPE,\n c.COLUMN_TYPE,\n c.IS_NULLABLE,\n c.COLUMN_KEY,\n c.EXTRA,\n c.CHARACTER_MAXIMUM_LENGTH,\n c.COLUMN_DEFAULT,\n c.COLUMN_COMMENT AS COMMENT,\n kcu.REFERENCED_TABLE_NAME,\n kcu.REFERENCED_COLUMN_NAME\n FROM information_schema.COLUMNS c\n LEFT JOIN information_schema.KEY_COLUMN_USAGE kcu\n ON c.TABLE_SCHEMA = kcu.TABLE_SCHEMA\n AND c.TABLE_NAME = kcu.TABLE_NAME\n AND c.COLUMN_NAME = kcu.COLUMN_NAME\n WHERE c.TABLE_SCHEMA = ?\n AND c.TABLE_NAME = ?\n ",[t,e]),a={};for(const e of n)a[e.COLUMN_NAME]=this.utils.formatColumnDef(e.COLUMN_NAME,e);return a}hasColumnChanged(e,t){const n={isNullableChanged:e.nullable!==t.nullable,isTypeChanged:e.type!==t.type,isSizeChanged:e.size!==t.size,isUnsignedChanged:e.isUnsigned!==t.isUnsigned,isPrimaryChanged:e.primary!==t.primary,isUniqueChanged:e.unique!==t.unique,isAutoIncrementChanged:e.autoIncrement!==t.autoIncrement,isDefaultChanged:e.default!==t.default,isOnUpdateChanged:e.onUpdate!==t.onUpdate,isCommentChanged:e.comment!==t.comment,isForeignKeyChanged:e.hasForeignKey!==t.hasForeignKey},a=Object.values(n).some(Boolean);return a&&logger.debug({changes:n,oldComment:e.comment,newComment:t.comment,name:e.name}),a}async getAlterations(e){const t={add:[],drop:[],modify:[]},n=await this.getCurrentColumns(e.table);for(const[a,s]of Object.entries(e.columns)){const e=this.utils.formatColumnSchema(a,s),o=n[a];o?(e.oldColDef=o,this.hasColumnChanged(o,e)&&t.modify.push(e)):t.add.push(e)}for(const a of Object.keys(n))e.columns[a]||t.drop.push({name:a});return t}getColumnStr(e,t,n={actionType:"CREATE",tableName:""}){const{actionType:a,tableName:s}=n,o="string"==typeof t?this.utils.formatColumnSchema(e,t):t,i=o.type,r=o.size??this.utils.getDefaultTypeSize(i);let l=`\`${e}\` ${i}${r?`(${r})`:""}`;if(o.isUnsigned&&(l+=" UNSIGNED"),o.primary&&["CREATE","ADD_COLUMN"].includes(a)&&(l+=" PRIMARY KEY"),o.autoIncrement&&(l+=" AUTO_INCREMENT"),o.nullable||(l+=" NOT NULL"),o.unique&&(l+=" UNIQUE"),o.default&&(l+=` DEFAULT ${o.default}`),o.onUpdate&&(l+=` ON UPDATE ${o.onUpdate}`),o.comment&&(l+=` COMMENT '${this.utils.escapeComment(o.comment)}'`),o.hasForeignKey&&1===o.foreignMapTables?.length&&"CREATE"===a){const{table:t,column:n}=o.foreignMapTables[0],a=`idx_${s}__${e}__fk_${t}_${n}`;l+=`, KEY \`${a}\` (\`${e}\`), CONSTRAINT \`cn_${a}\`\n FOREIGN KEY (\`${e}\`) REFERENCES \`${t}\` (\`${n}\`)\n ON DELETE RESTRICT ON UPDATE RESTRICT`}return l}async createTable(e){const t=e.table,n=e.columns,a=[];for(const[e,s]of Object.entries(n))a.push(this.getColumnStr(e,s,{actionType:"CREATE",tableName:t}));const s=`CREATE TABLE IF NOT EXISTS \`${t}\` (${a.join(", ")})`;await this.executeSql(s)}async alterTable(e,t){if(!t||"object"!=typeof t)throw new Error("alterations must be an object");const n=[];if(t.add?.length)for(const a of t.add)n.push(`ADD COLUMN ${this.getColumnStr(a.name,a,{actionType:"ADD_COLUMN",tableName:e})}`);if(t.drop?.length)for(const e of t.drop)n.push(`DROP COLUMN \`${e.name}\``);if(t.modify?.length)for(const a of t.modify)n.push(`MODIFY COLUMN ${this.getColumnStr(a.name,a,{actionType:"MODIFY_COLUMN",tableName:e})}`);if(!n.length)return void logger.info("No alterations to apply for",e);const a=`ALTER TABLE \`${e}\` ${n.join(", ")}`;await this.executeSql(a)}async alterColumn(e,t,n){const a=`ALTER TABLE \`${e}\` MODIFY COLUMN ${this.getColumnStr(t,n,{actionType:"MODIFY_COLUMN",tableName:e})}`;await this.executeSql(a)}async alterIndex(e,t,n){const a=`ALTER TABLE \`${e}\` MODIFY INDEX ${`${t} ${n.type} ${n.unique?"UNIQUE":""}`}`;await this.executeSql(a)}async dropIndex(e,t){const n=`DROP INDEX \`${t}\` ON \`${e}\``;await this.executeSql(n)}async dropTable(e){const t=`DROP TABLE IF EXISTS \`${e}\``;await this.executeSql(t)}async updateTable(e){logger.warn(`Update table not implemented for ${e.table}`)}async syncTable(e){if(await this.existsTable(e.table)){const t=await this.getAlterations(e);return logger.debug(...Object.values(t)),void await this.alterTable(e.table,t)}await this.createTable(e)}async syncSeedData(e,t){let n=this.utils.getModel(this.controllerWrapper,t),a=await this.curd.processRequest({action:"count"},n.name,{isCallFromServer:!0});if(logger.debug("count",a),a>0)logger.info("Seed data already synced for",t);else if(e.seed&&Array.isArray(e.seed)){for(const t of e.seed)await this.curd.processRequest({action:"create",data:t},n.name,{isCallFromServer:!0});logger.info("Seed data synced for",t)}}async syncDatabase(){if(!this.controllerWrapper?.schema)throw new Error("controllerWrapper.schema not set.");const e=this.controllerWrapper.schema;for(const t of Object.keys(e))await this.syncTable(e[t]),await this.syncSeedData(e[t],t);logger.info("Database synced by SyncTable...")}async getTablesOfDatabase(){const[e]=await this.db.raw("SHOW TABLES");return e.map(e=>e[`Tables_in_${this.db.client.database()}`])}getColumnString(e){return Object.keys(e).reduce((t,n)=>{const a=e[n];let s=a.type,o=a.size,i=a.isUnsigned,r=a.primary,l=a.autoIncrement,c=a.nullable,u=a.unique,m=a.default,d=a.onUpdate,E=a.comment,h=a.hasForeignKey,C=a.foreignMapTables?.[0]?.table,T=a.foreignMapTables?.[0]?.column;return t[n]=`${s}`,o&&(t[n]+=`|size:${o}`),i&&(t[n]+="|unsigned"),r&&(t[n]+="|primaryKey"),l&&(t[n]+="|autoIncrement"),c&&(t[n]+="|nullable"),u&&(t[n]+="|unique"),m&&(t[n]+=`|default:${m}`),d&&(t[n]+=`|onUpdate:${d}`),E&&(t[n]+=`|comment:${E}`),h&&(t[n]+=`|foreignKey:${C}:${T}`),t},{})}async generateSchema(){const e=await this.getTablesOfDatabase(),t={};for(const n of e){let e=this.helperUtility.modelName(n);t[e]={table:n,alias:e,columns:this.getColumnString(await this.getCurrentColumns(n)),modelName:e,seed:[],hasRelations:{},indexes:[]}}return t}}module.exports=SyncTable;
1
+ const BaseSyncTable=require("../BaseSyncTable"),logger=require("../../Logger");class SQLiteSyncTable extends BaseSyncTable{_getClientName(){return"sqlite"}async _listTables(){return await this.db("sqlite_master").where({type:"table"}).whereNot("name","like","sqlite_%").pluck("name")}_supportsUnsigned(){return!1}async _applyExtras(e){for(const[t,s]of Object.entries(e.columns)){("string"==typeof s?this.utils.formatColumnSchema(t,s):s).onUpdate&&this._warnOnUnsupportedModifier("onUpdate",e.table,t)}}async _getRelations(e){return{}}async getTablesOfDatabase(){return this._listTables()}async executeSql(e,t=[]){return logger.debug("executeSql (legacy)",{sql:e,params:t}),this.db.raw(e,t)}}module.exports=SQLiteSyncTable;
@@ -0,0 +1 @@
1
+ "use strict";const DB_TYPE_TO_JSON={tinyint:{type:"integer"},smallint:{type:"integer"},mediumint:{type:"integer"},int:{type:"integer"},integer:{type:"integer"},bigint:{type:"integer"},decimal:{type:"number"},numeric:{type:"number"},float:{type:"number"},double:{type:"number"},real:{type:"number"},bit:{type:"integer"},varchar:{type:"string"},char:{type:"string"},text:{type:"string"},tinytext:{type:"string"},mediumtext:{type:"string"},longtext:{type:"string"},enum:{type:"string"},set:{type:"string"},uuid:{type:"string",format:"uuid"},json:{},jsonb:{},boolean:{type:"boolean"},date:{type:"string",format:"date"},datetime:{type:"string",format:"date-time"},timestamp:{type:"string",format:"date-time"},time:{type:"string",format:"time"},year:{type:"integer"},binary:{type:"string",contentEncoding:"base64"},varbinary:{type:"string",contentEncoding:"base64"},tinyblob:{type:"string",contentEncoding:"base64"},blob:{type:"string",contentEncoding:"base64"},mediumblob:{type:"string",contentEncoding:"base64"},longblob:{type:"string",contentEncoding:"base64"}},KNOWN_FLAGS=new Set(["primaryKey","autoIncrement","notNull","unique","nullable","index"]);function emptyFlags(){return{primaryKey:!1,autoIncrement:!1,notNull:!1,unique:!1,nullable:!0,hasDefault:!1,defaultValue:void 0,size:null,baseType:null}}function applySegmentToFlags(e,t){if(e.startsWith("size:")){const n=Number(e.slice(5));return void(Number.isFinite(n)&&(t.size=n))}if(e.startsWith("default:"))return t.hasDefault=!0,void(t.defaultValue=e.slice(8));KNOWN_FLAGS.has(e)&&("nullable"===e?t.nullable=!0:t[e]=!0)}function jsonSchemaForBase(e,t){const n={...DB_TYPE_TO_JSON[e]||{}};return"string"!==n.type||null==t.size||n.format||(n.maxLength=t.size),n}function parseColumnDef(e){if("string"!=typeof e||0===e.length)return{jsonSchema:{},flags:emptyFlags()};const t=e.split("|").map(e=>e.trim()).filter(Boolean),n=(t.shift()||"").toLowerCase(),i={...emptyFlags(),baseType:n};for(const e of t)applySegmentToFlags(e,i);return i.notNull&&(i.nullable=!1),{jsonSchema:jsonSchemaForBase(n,i),flags:i}}function isWritableOnCreate(e){return!e.flags.autoIncrement}function isRequiredOnCreate(e){return!e.flags.autoIncrement&&(!e.flags.hasDefault&&!0===e.flags.notNull)}function applyNullability(e,t){return!t.flags.notNull&&e.type?{...e,type:[e.type,"null"]}:e}module.exports={parseColumnDef:parseColumnDef,isWritableOnCreate:isWritableOnCreate,isRequiredOnCreate:isRequiredOnCreate,applyNullability:applyNullability,DB_TYPE_TO_JSON:DB_TYPE_TO_JSON};
package/helpers/files.js CHANGED
@@ -1 +1 @@
1
- const fs=require("fs"),path=require("path"),{S3Client:S3Client,PutObjectCommand:PutObjectCommand}=require("@aws-sdk/client-s3"),logger=require("../Logger");class Files{s3Client=null;config=null;validateConfig(e){let t=[];if(e.region||t.push("Region as config.region"),e.endpoint||e.host||t.push("Endpoint as config.endpoint or Host as config.host"),e.accessKeyId||t.push("Access key ID as config.accessKeyId"),e.secretAccessKey||t.push("Secret access key as config.secretAccessKey"),e.bucketName||t.push("Bucket name as config.bucketName"),t.length>0)throw new Error(`Missing config: ${t.join(", ")}. Please set the config in the config file.`)}setConfig(e){this.validateConfig(e),this.config=e;let t={region:e.region,endpoint:e.endpoint||`https://${e.region}.${e.host}`,credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}};this.s3Client=new S3Client(t)}async upload2Spaces(e){const{fileBuffer:t,originalName:i,mimeType:s}=e;logger.debug("Uploading file to Spaces",{fileBuffer:t,originalName:i,mimeType:s},e);const n=i.split(".").pop(),r=this.config.bucketName,a=`${this.config.folderName||"uploads"}/${`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}-${i}.${n}`,c={Bucket:r,Key:a,Body:t,ContentType:s,ACL:"public-read",CacheControl:"max-age=31536000"};try{const e=new PutObjectCommand(c);await this.s3Client.send(e);const t=`https://${r}.${this.config.region}.cdn.digitaloceanspaces.com/${a}`;return logger.info(`File uploaded to Spaces key: ${a}`),{key:a,url:t}}catch(e){throw logger.error("DigitalOcean Spaces Upload Error:",e),new Error(`Spaces upload failed: ${e.message}`)}}needSync(e,t){let i=this.readJSON(e),s=this.checkFileUpdatedAt(e),n=this.readFile(t);return n&&(n=new Date(+n)),{needSync:n&&n<s||!n,syncSchema:i,lastSyncedAt:s.getTime().toString()}}writeFromTemplate(e,t,i){const s=__dirname,n=fs.readFileSync(`${s}/${t}`,"utf8").replace(/{{(.*?)}}/g,(e,t)=>i[t]||e);this.createDirectory(path.dirname(e)),fs.writeFileSync(e,n)}writeModel(e,t){this.exists(e)?logger.debug("File already exists",e):(logger.debug("Writing model to",e),this.writeFromTemplate(e,"../templates/model.template",t))}checkFileUpdatedAt(e){return this.exists(e)?fs.statSync(e).mtime:null}isLatestFile(e,t=1e3){let i=Date.now(),s=this.checkFileUpdatedAt(e);return!!s&&i-new Date(s).getTime()<t}createDirectory(e){this.exists(e)||fs.mkdirSync(e,{recursive:!0})}deleteDirectory(e){this.exists(e)&&fs.rmSync(e,{recursive:!0,force:!0})}exists(e){return fs.existsSync(e)}rename(e,t){this.exists(e)&&fs.renameSync(e,t)}deleteFile(e){this.exists(e)&&fs.unlinkSync(e)}readFile(e,t="utf8"){return this.exists(e)?fs.readFileSync(e,t):null}writeFile(e,t,i="utf8"){fs.writeFileSync(e,t,i)}appendFile(e,t,i="utf8"){fs.appendFileSync(e,t,i)}readJSON(e){return JSON.parse(this.readFile(e))}writeJSON(e,t){this.writeFile(e,JSON.stringify(t,null,2))}readJSONL(e){return this.readFile(e).trim().split("\n").map(e=>JSON.parse(e))}writeJSONL(e,t){const i=t.map(e=>JSON.stringify(e)).join("\n");this.writeFile(e,i)}appendJSONL(e,t){const i=t.map(e=>JSON.stringify(e)).join("\n");this.appendFile(e,"\n"+i)}escapeCSV(e){if(null==e)return"";const t=String(e);return t.includes('"')||t.includes(",")||t.includes("\n")?`"${t.replace(/"/g,'""')}"`:t}writeCSV(e,t){if(!Array.isArray(t)||0===t.length)throw new Error("Data must be a non-empty array");const i=Object.keys(t[0]),s=[i.join(","),...t.map(e=>i.map(t=>this.escapeCSV(e[t])).join(","))];this.writeFile(e,s.join("\n"))}readCSV(e){return this.readFile(e).trim().split("\n").map(e=>e.split(","))}appendCSV(e,t){if(!Array.isArray(t)||0===t.length)return;const[i]=this.readFile(e).split("\n"),s=i.split(","),n=t.map(e=>s.map(t=>this.escapeCSV(e[t])).join(","));this.appendFile(e,"\n"+n.join("\n"))}}module.exports=Files;
1
+ const fs=require("fs"),path=require("path"),{S3Client:S3Client,PutObjectCommand:PutObjectCommand}=require("@aws-sdk/client-s3"),logger=require("../Logger");class Files{s3Client=null;config=null;validateConfig(e){const t=[];if(e.region||t.push("Region as config.region"),e.endpoint||e.host||t.push("Endpoint as config.endpoint or Host as config.host"),e.accessKeyId||t.push("Access key ID as config.accessKeyId"),e.secretAccessKey||t.push("Secret access key as config.secretAccessKey"),e.bucketName||t.push("Bucket name as config.bucketName"),t.length>0)throw new Error(`Missing config: ${t.join(", ")}. Please set the config in the config file.`)}setConfig(e){this.validateConfig(e),this.config=e;const t={region:e.region,endpoint:e.endpoint||`https://${e.region}.${e.host}`,credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}};this.s3Client=new S3Client(t)}async upload2Spaces(e){const{fileBuffer:t,originalName:i,mimeType:s}=e;logger.debug("Uploading file to Spaces",{fileBuffer:t,originalName:i,mimeType:s},e);const n=i.split(".").pop(),r=this.config.bucketName,a=`${this.config.folderName||"uploads"}/${`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}-${i}.${n}`,c={Bucket:r,Key:a,Body:t,ContentType:s,ACL:"public-read",CacheControl:"max-age=31536000"};try{const e=new PutObjectCommand(c);await this.s3Client.send(e);const t=`https://${r}.${this.config.region}.cdn.digitaloceanspaces.com/${a}`;return logger.info(`File uploaded to Spaces key: ${a}`),{key:a,url:t}}catch(e){throw logger.error("DigitalOcean Spaces Upload Error:",e),new Error(`Spaces upload failed: ${e.message}`)}}needSync(e,t){const i=this.readJSON(e),s=this.checkFileUpdatedAt(e);let n=this.readFile(t);return n&&(n=new Date(+n)),{needSync:n&&n<s||!n,syncSchema:i,lastSyncedAt:s.getTime().toString()}}writeFromTemplate(e,t,i){const s=__dirname,n=fs.readFileSync(`${s}/${t}`,"utf8").replace(/{{(.*?)}}/g,(e,t)=>i[t]||e);this.createDirectory(path.dirname(e)),fs.writeFileSync(e,n)}writeModel(e,t){this.exists(e)?logger.debug("File already exists",e):(logger.debug("Writing model to",e),this.writeFromTemplate(e,"../templates/model.template",t))}checkFileUpdatedAt(e){return this.exists(e)?fs.statSync(e).mtime:null}isLatestFile(e,t=1e3){const i=Date.now(),s=this.checkFileUpdatedAt(e);if(!s)return!1;return i-new Date(s).getTime()<t}createDirectory(e){this.exists(e)||fs.mkdirSync(e,{recursive:!0})}deleteDirectory(e){this.exists(e)&&fs.rmSync(e,{recursive:!0,force:!0})}exists(e){return fs.existsSync(e)}rename(e,t){this.exists(e)&&fs.renameSync(e,t)}deleteFile(e){this.exists(e)&&fs.unlinkSync(e)}readFile(e,t="utf8"){return this.exists(e)?fs.readFileSync(e,t):null}writeFile(e,t,i="utf8"){fs.writeFileSync(e,t,i)}appendFile(e,t,i="utf8"){fs.appendFileSync(e,t,i)}readJSON(e){return JSON.parse(this.readFile(e))}writeJSON(e,t){this.writeFile(e,JSON.stringify(t,null,2))}readJSONL(e){return this.readFile(e).trim().split("\n").map(e=>JSON.parse(e))}writeJSONL(e,t){const i=t.map(e=>JSON.stringify(e)).join("\n");this.writeFile(e,i)}appendJSONL(e,t){const i=t.map(e=>JSON.stringify(e)).join("\n");this.appendFile(e,"\n"+i)}escapeCSV(e){if(null==e)return"";const t=String(e);return t.includes('"')||t.includes(",")||t.includes("\n")?`"${t.replace(/"/g,'""')}"`:t}writeCSV(e,t){if(!Array.isArray(t)||0===t.length)throw new Error("Data must be a non-empty array");const i=Object.keys(t[0]),s=[i.join(","),...t.map(e=>i.map(t=>this.escapeCSV(e[t])).join(","))];this.writeFile(e,s.join("\n"))}readCSV(e){return this.readFile(e).trim().split("\n").map(e=>e.split(","))}appendCSV(e,t){if(!Array.isArray(t)||0===t.length)return;const[i]=this.readFile(e).split("\n"),s=i.split(","),n=t.map(e=>s.map(t=>this.escapeCSV(e[t])).join(","));this.appendFile(e,"\n"+n.join("\n"))}}module.exports=Files;
package/index.d.ts ADDED
@@ -0,0 +1,213 @@
1
+ export interface InitializeOptions {
2
+ db: any;
3
+ dbClient: string;
4
+ schema?: any;
5
+ resolverPath?: string;
6
+ debug?: boolean;
7
+ }
8
+
9
+ /**
10
+ * Response when a request is sent with `dryRun: true`: the SQL that
11
+ * would run, without executing it. See docs/agents/06-request-contract.md §9.
12
+ */
13
+ export interface DryRunResult {
14
+ success: true;
15
+ dryRun: true;
16
+ action: string;
17
+ model: string;
18
+ sql: string;
19
+ bindings: any[];
20
+ statements: Array<{ sql: string; bindings: any[] }>;
21
+ }
22
+
23
+ /** One column in a ModelDescription (issue #15). */
24
+ export interface ColumnDescription {
25
+ name: string;
26
+ type: string | null;
27
+ nullable: boolean;
28
+ primaryKey: boolean;
29
+ autoIncrement: boolean;
30
+ unique: boolean;
31
+ size?: number;
32
+ default?: string;
33
+ }
34
+
35
+ /** One relation in a ModelDescription. */
36
+ export interface RelationDescription {
37
+ name: string;
38
+ type: string | null;
39
+ table: string | null;
40
+ localKey: string | null;
41
+ foreignKey: string | null;
42
+ through?: string;
43
+ throughLocalKey?: string | null;
44
+ throughForeignKey?: string | null;
45
+ }
46
+
47
+ /** Pure-data description of one model (korm.describeModel). */
48
+ export interface ModelDescription {
49
+ schemaApiVersion: number;
50
+ model: string;
51
+ table: string | null;
52
+ alias: string;
53
+ columns: ColumnDescription[];
54
+ relations: RelationDescription[];
55
+ softDelete: boolean;
56
+ actions: string[];
57
+ }
58
+
59
+ /** Pure-data description of all models (korm.describeSchema). */
60
+ export interface SchemaDescription {
61
+ schemaApiVersion: number;
62
+ models: ModelDescription[];
63
+ }
64
+
65
+ export interface KormInstance {
66
+ processRequest(requestBody: any, modelName: string, context?: any): Promise<any | DryRunResult>;
67
+ syncDatabase?(options?: any): Promise<any>;
68
+ generateSchema?(options?: any): Promise<any>;
69
+ /**
70
+ * Draft-2020-12 JSON Schema for every valid processRequest body for
71
+ * `modelName` (an action-discriminated `oneOf`). For OpenAI/Anthropic
72
+ * tool definitions + client-side prevalidation. Throws KormError
73
+ * (code 'UNKNOWN_MODEL') for an unregistered model.
74
+ */
75
+ getRequestJsonSchema(modelName: string): Record<string, any>;
76
+ /** Pure-data description of all registered models (issue #15). */
77
+ describeSchema(): SchemaDescription;
78
+ /**
79
+ * Pure-data description of one model. Throws KormError (code
80
+ * 'UNKNOWN_MODEL') for an unregistered model.
81
+ */
82
+ describeModel(modelName: string): ModelDescription;
83
+ setSchema(schema: any): void;
84
+ loadModelClass?(name: string): any;
85
+ getModelInstance?(name: string): any;
86
+ }
87
+
88
+ export function initializeKORM(opts: InitializeOptions): KormInstance;
89
+ export function validate(body: any, rules: any, opts?: any): Promise<any>;
90
+ export const helperUtility: any;
91
+ export const emitter: any;
92
+ export const logger: any;
93
+
94
+ // ---- Structured errors --------------------------------------------------
95
+
96
+ export type KormErrorCode =
97
+ | 'NO_MATCHING_ROW'
98
+ | 'UNKNOWN_ACTION'
99
+ | 'VALIDATION_FAILED'
100
+ | 'UNKNOWN_MODEL'
101
+ | 'NO_CUSTOM_ACTION_HOOK'
102
+ | 'INTERNAL';
103
+
104
+ export interface KormErrorContext {
105
+ action?: string;
106
+ model?: string;
107
+ validActions?: string[];
108
+ closest?: string | null;
109
+ available?: string[];
110
+ source?: string | null;
111
+ fields?: Array<{ field?: string; message?: string; value?: unknown; rule?: unknown }>;
112
+ [key: string]: unknown;
113
+ }
114
+
115
+ export interface KormErrorJSON {
116
+ name: 'KormError';
117
+ code: KormErrorCode;
118
+ message: string;
119
+ hint: string | null;
120
+ context: KormErrorContext;
121
+ suggestedFixes: Array<{ description: string; request?: object }> | null;
122
+ }
123
+
124
+ /**
125
+ * Structured error thrown by processRequest / validate. Extends the
126
+ * native Error, so `catch (e) { e.message }` keeps working; `e.code`
127
+ * and `e.context` let callers (and agents) branch programmatically.
128
+ */
129
+ export class KormError extends Error {
130
+ name: 'KormError';
131
+ code: KormErrorCode;
132
+ hint: string | null;
133
+ context: KormErrorContext;
134
+ suggestedFixes: Array<{ description: string; request?: object }> | null;
135
+ /** Present when code === 'VALIDATION_FAILED' (back-compat alias). */
136
+ errors?: any[];
137
+ toJSON(): KormErrorJSON;
138
+
139
+ static CODES: Record<KormErrorCode, KormErrorCode>;
140
+ static ACTIONS: readonly string[];
141
+ static closestAction(input: string, candidates?: string[]): string | null;
142
+ static noMatchingRow(opts: { action: string; model: string }): KormError;
143
+ static unknownAction(opts: { action: string; model?: string; hasCustomHook?: boolean }): KormError;
144
+ static unknownModel(opts: { model: string; available?: string[] }): KormError;
145
+ static validationFailed(opts: { errors?: any[]; source?: string | null }): KormError;
146
+ }
147
+
148
+ export const LibClasses: { Emitter: any; KormError: typeof KormError };
149
+ export const lib: {
150
+ createValidationMiddleware(...args: any[]): any;
151
+ validateEmail(...args: any[]): any;
152
+ validatePassword(...args: any[]): any;
153
+ validatePhone(...args: any[]): any;
154
+ validatePAN(...args: any[]): any;
155
+ validateAadhaar(...args: any[]): any;
156
+ };
157
+
158
+ // ---- MCP (Model Context Protocol) optional surface ----------------------
159
+
160
+ export type McpMode = 'ro' | 'rw' | 'rw-sync';
161
+
162
+ export interface McpCustomAction {
163
+ table: string;
164
+ action: string;
165
+ schema?: any;
166
+ description?: string;
167
+ }
168
+
169
+ export interface McpConfig {
170
+ mode?: McpMode;
171
+ allowlist?: string[] | '*';
172
+ blocklist?: string[];
173
+ metaTools?: boolean;
174
+ allowNestedRequests?: boolean;
175
+ customActions?: McpCustomAction[];
176
+ rateLimit?: { perMinute?: number };
177
+ logLevel?: string;
178
+ }
179
+
180
+ export interface McpToolResult {
181
+ content: Array<{ type: string; text: string }>;
182
+ isError?: boolean;
183
+ }
184
+
185
+ export interface McpTool {
186
+ name: string;
187
+ description: string;
188
+ inputSchema: any;
189
+ handler: (input: any) => Promise<McpToolResult>;
190
+ }
191
+
192
+ export interface McpServer {
193
+ tools: McpTool[];
194
+ toolsByName: Map<string, McpTool>;
195
+ start(opts?: { logger?: any }): Promise<any>;
196
+ stop(): Promise<void>;
197
+ }
198
+
199
+ export interface CreateMcpServerOptions {
200
+ controller: any;
201
+ schema: any;
202
+ mcpConfig: McpConfig;
203
+ packageInfo?: { name?: string; version?: string };
204
+ }
205
+
206
+ export const mcp: {
207
+ createServer(opts: CreateMcpServerOptions): McpServer;
208
+ generateTools(opts: {
209
+ controller: any;
210
+ schema: any;
211
+ mcpConfig: McpConfig;
212
+ }): McpTool[];
213
+ };
package/index.js CHANGED
@@ -1 +1 @@
1
- const ControllerWrapper=require("./ControllerWrapper"),BaseHelperUtility=require("./BaseHelperUtility"),RequestValidator=require("./RequestValidator"),Emitter=require("./Emitter"),logger=require("./Logger");module.exports={LibClasses:{Emitter:Emitter},initializeKORM(){return ControllerWrapper.initializeKORM(...arguments)},helperUtility:new BaseHelperUtility,emitter:new Emitter,logger:logger,validate:RequestValidator.validate,lib:{createValidationMiddleware:RequestValidator.createValidationMiddleware,validateEmail:RequestValidator.validateEmail,validatePassword:RequestValidator.validatePassword,validatePhone:RequestValidator.validatePhone,validatePAN:RequestValidator.validatePAN,validateAadhaar:RequestValidator.validateAadhaar}};
1
+ const ControllerWrapper=require("./ControllerWrapper"),BaseHelperUtility=require("./BaseHelperUtility"),RequestValidator=require("./RequestValidator"),Emitter=require("./Emitter"),logger=require("./Logger"),KormError=require("./KormError"),{createServer:createMcpServer}=require("./src/mcp/server"),{generateTools:generateMcpTools}=require("./src/mcp/toolGenerator");module.exports={LibClasses:{Emitter:Emitter,KormError:KormError},KormError:KormError,initializeKORM(){return ControllerWrapper.initializeKORM(...arguments)},helperUtility:new BaseHelperUtility,emitter:new Emitter,logger:logger,validate:RequestValidator.validate,lib:{createValidationMiddleware:RequestValidator.createValidationMiddleware,validateEmail:RequestValidator.validateEmail,validatePassword:RequestValidator.validatePassword,validatePhone:RequestValidator.validatePhone,validatePAN:RequestValidator.validatePAN,validateAadhaar:RequestValidator.validateAadhaar},mcp:{createServer:createMcpServer,generateTools:generateMcpTools}};
package/jest.config.js CHANGED
@@ -1 +1 @@
1
- module.exports={testEnvironment:"node",testMatch:["**/test/**/*.test.js","**/test/**/*.spec.js","**/__tests__/**/*.js"],collectCoverage:!0,coverageDirectory:"coverage",coverageReporters:["text","lcov","html"],collectCoverageFrom:["**/*.js","!**/node_modules/**","!**/test/**","!**/coverage/**","!jest.config.js","!**/dist/**","!build.js","!version-manager.js"],testTimeout:1e4,clearMocks:!0,verbose:!0};
1
+ module.exports={testEnvironment:"node",testMatch:["**/test/**/*.test.js","**/test/**/*.spec.js","**/__tests__/**/*.js"],testPathIgnorePatterns:["/node_modules/"],collectCoverage:!1,coverageDirectory:"coverage",coverageReporters:["text","lcov","html"],collectCoverageFrom:["clients/sqlite/**/*.js","clients/Base*.js","ControllerWrapper.js","RequestValidator.js","BaseHelperUtility.js","Logger.js","Emitter.js","index.js","cli.js","helpers/**/*.js","src/mcp/**/*.js","bin/korm-mcp.js","!**/node_modules/**","!**/test/**","!**/coverage/**","!**/dist/**"],coverageThreshold:{global:{statements:60,branches:50,functions:60,lines:61}},testTimeout:1e4,moduleNameMapper:{"^@modelcontextprotocol/sdk/(.*)$":"<rootDir>/node_modules/@modelcontextprotocol/sdk/dist/cjs/$1"},clearMocks:!0,verbose:!0};