rawsql-ts 0.11.23-beta → 0.11.25-beta
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.min.js +2 -2
- package/dist/esm/index.min.js.map +2 -2
- package/dist/esm/src/transformers/SqlParamInjector.d.ts +2 -0
- package/dist/esm/src/transformers/SqlParamInjector.js +4 -0
- package/dist/esm/src/transformers/SqlParamInjector.js.map +1 -1
- package/dist/esm/tsconfig.browser.tsbuildinfo +1 -1
- package/dist/index.min.js +1 -1
- package/dist/index.min.js.map +2 -2
- package/dist/src/transformers/SqlParamInjector.d.ts +2 -0
- package/dist/src/transformers/SqlParamInjector.js +4 -0
- package/dist/src/transformers/SqlParamInjector.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
package/dist/index.min.js
CHANGED
|
@@ -56,7 +56,7 @@ ${e}`}getCTEName(e){return e.aliasExpression.table.name}};var Ut=class{construct
|
|
|
56
56
|
`);r&&(n+=r+`
|
|
57
57
|
`),this.nodes.size>0&&this.edges.getAll().length>0&&(n+=`
|
|
58
58
|
`);let i=this.edges.getMermaidRepresentation();return i&&(n+=` ${i}
|
|
59
|
-
`),n}getOrCreateTable(e){let t=`table_${e}`,n=this.nodes.get(t);return n||(n=At.createTable(e),this.addNode(n)),n}getOrCreateCTE(e){let t=`cte_${e}`,n=this.nodes.get(t);return n||(n=At.createCTE(e),this.addNode(n)),n}getOrCreateSubquery(e){let t=`subquery_${e}`,n=this.nodes.get(t);return n||(n=At.createSubquery(e),this.addNode(n)),n}createProcessNode(e,t){let n=new _n(t,e);return this.addNode(n),n}createJoinNode(e,t){let n=_t.createJoin(e,t);return this.addNode(n),n}createSetOperationNode(e,t){let n=_t.createSetOperation(e,t);return this.addNode(n),n}createOutputNode(e="main"){let t=new zn(e);return this.addNode(t),t}};var Ht=class{constructor(e){this.graph=e}processSource(e,t,n){if(e.datasource instanceof R)return this.processTableSource(e.datasource,t);if(e.datasource instanceof J)return this.processSubquerySource(e,t,n);throw new Error("Unsupported source type")}processTableSource(e,t){let n=e.getSourceName();return t.has(n)?this.graph.getOrCreateCTE(n).id:this.graph.getOrCreateTable(n).id}processSubquerySource(e,t,n){let r=e.aliasExpression?.table.name||"subquery",i=this.graph.getOrCreateSubquery(r),s=n(e.datasource.query,`subquery_${r}_internal`,t);return s&&!this.graph.hasConnection(s,i.id)&&this.graph.addConnection(s,i.id),i.id}extractTableNodeIds(e,t){let n=[],r=e.source;if(r.datasource instanceof R){let i=r.datasource.getSourceName();if(t.has(i)){let s=this.graph.getOrCreateCTE(i);n.push(s.id)}else{let s=this.graph.getOrCreateTable(i);n.push(s.id)}}if(e.joins&&e.joins.length>0)for(let i of e.joins){let s=i.source;if(s.datasource instanceof R){let a=s.datasource.getSourceName();if(t.has(a)){let l=this.graph.getOrCreateCTE(a);n.push(l.id)}else{let l=this.graph.getOrCreateTable(a);n.push(l.id)}}}return n}};var Gt=class{constructor(e,t){this.graph=e;this.dataSourceHandler=t;this.joinIdCounter=0}resetJoinCounter(){this.joinIdCounter=0}getNextJoinId(){return String(++this.joinIdCounter)}processFromClause(e,t,n){let r=this.dataSourceHandler.processSource(e.source,t,n);return e.joins&&e.joins.length>0?this.processJoins(e.joins,r,t,n):r}processJoins(e,t,n,r){let i=t;for(let s of e){let a=this.dataSourceHandler.processSource(s.source,n,r),l=this.getNextJoinId(),u=this.graph.createJoinNode(l,s.joinType.value),{leftLabel:c,rightLabel:m}=this.getJoinNullabilityLabels(s.joinType.value);i&&!this.graph.hasConnection(i,u.id)&&this.graph.addConnection(i,u.id,c),a&&!this.graph.hasConnection(a,u.id)&&this.graph.addConnection(a,u.id,m),i=u.id}return i}getJoinNullabilityLabels(e){switch(e.toLowerCase()){case"left join":return{leftLabel:"NOT NULL",rightLabel:"NULLABLE"};case"right join":return{leftLabel:"NULLABLE",rightLabel:"NOT NULL"};case"inner join":case"join":return{leftLabel:"NOT NULL",rightLabel:"NOT NULL"};case"full join":case"full outer join":return{leftLabel:"NULLABLE",rightLabel:"NULLABLE"};case"cross join":return{leftLabel:"NOT NULL",rightLabel:"NOT NULL"};default:return{leftLabel:"",rightLabel:""}}}};var Yt=class{constructor(e,t){this.graph=e;this.dataSourceHandler=t}processQueryClauses(e,t,n,r,i){return n}};var Xt=class{constructor(e){this.graph=e}processCTEs(e,t,n){for(let r=0;r<e.tables.length;r++){let s=e.tables[r].getSourceAliasName(),a=this.graph.getOrCreateCTE(s);t.add(s),e.recursive&&r===0&&a.addAnnotation("recursive")}for(let r=0;r<e.tables.length;r++){let i=e.tables[r],s=i.getSourceAliasName(),a=this.graph.getOrCreateCTE(s),l=n(i.query,`cte_${s}`,t);if(l&&!this.graph.hasConnection(l,a.id)){let c=e.recursive&&r===0?"RECURSIVE":void 0;this.graph.addConnection(l,a.id,c)}}}detectRecursiveReference(e,t){return e.toString().toLowerCase().includes(t.toLowerCase())}};var fr=class o{constructor(){this.graph=new zt,this.dataSourceHandler=new Ht(this.graph),this.joinHandler=new Gt(this.graph,this.dataSourceHandler),this.processHandler=new Yt(this.graph,this.dataSourceHandler),this.cteHandler=new Xt(this.graph)}generateMermaidFlow(e,t){this.graph=new zt,this.dataSourceHandler=new Ht(this.graph),this.joinHandler=new Gt(this.graph,this.dataSourceHandler),this.processHandler=new Yt(this.graph,this.dataSourceHandler),this.cteHandler=new Xt(this.graph),this.joinHandler.resetJoinCounter();let n=typeof e=="string"?A.parse(e):e,r=new Set;return this.processQuery(n,"main",r),this.graph.generateMermaid(t?.direction||"TD",t?.title)}static generate(e){return new o().generateMermaidFlow(e)}processQuery(e,t,n){if(e instanceof y)return this.processSimpleQuery(e,t,n);if(e instanceof Q)return this.processBinaryQuery(e,t,n);throw new Error("Unsupported query type")}processSimpleQuery(e,t,n){e.withClause&&this.cteHandler.processCTEs(e.withClause,n,this.processQuery.bind(this));let r="";return e.fromClause&&(e.fromClause.joins&&e.fromClause.joins.length>0?r=this.joinHandler.processFromClause(e.fromClause,n,this.processQuery.bind(this)):r=this.dataSourceHandler.processSource(e.fromClause.source,n,this.processQuery.bind(this))),r&&(r=this.processHandler.processQueryClauses(e,t,r,n,this.processQuery.bind(this))),this.handleOutputNode(r,t)}processBinaryQuery(e,t,n){let r=this.flattenBinaryChain(e,e.operator.value);return r.length>2?this.processMultiPartOperation(r,e.operator.value,t,n):this.processSimpleBinaryOperation(e,t,n)}processSimpleBinaryOperation(e,t,n){let r=this.processQuery(e.left,`${t}_left`,n),i=this.processQuery(e.right,`${t}_right`,n),s=t==="main"?"main":t.replace(/^cte_/,""),a=this.graph.createSetOperationNode(s,e.operator.value);return r&&!this.graph.hasConnection(r,a.id)&&this.graph.addConnection(r,a.id),i&&!this.graph.hasConnection(i,a.id)&&this.graph.addConnection(i,a.id),a.id}processMultiPartOperation(e,t,n,r){let i=[],s=n==="main"?"main":n.replace(/^cte_/,""),a=this.graph.createSetOperationNode(s,t);for(let l=0;l<e.length;l++){let u=`${n}_part${l+1}`,c=this.processQuery(e[l],u,r);i.push(c)}for(let l of i)l&&!this.graph.hasConnection(l,a.id)&&this.graph.addConnection(l,a.id);return a.id}handleOutputNode(e,t){if(t==="main"){let n=this.graph.createOutputNode(t);return e&&this.graph.addConnection(e,n.id),n.id}return e}flattenBinaryChain(e,t){let n=[],r=i=>{i instanceof Q&&i.operator.value===t?(r(i.left),r(i.right)):n.push(i)};return r(e),n}};var Zt=class{constructor(e,t){typeof e=="function"?(this.tableColumnResolver=e,this.options=t||{}):(this.tableColumnResolver=void 0,this.options=e||{})}inject(e,t){typeof e=="string"&&(e=A.parse(e));let n=new Ct(this.tableColumnResolver,this.options),r=new Ie(this.tableColumnResolver),i=d=>this.options.ignoreCaseAndUnderscore?d.toLowerCase().replace(/_/g,""):d,s=["min","max","like","ilike","in","any","=","<",">","!=","<>","<=",">=","or","and","column"],a=Object.values(t);if(a.length>0&&a.every(d=>d===void 0)&&!this.options.allowAllUndefined)throw new Error("All parameters are undefined. This would result in fetching all records. Use allowAllUndefined: true option to explicitly allow this behavior.");for(let[d,w]of Object.entries(t))w!==void 0&&this.processStateParameter(d,w,e,n,r,i,s,m,c,g,b,h);function c(d,w,L,E,O,N){for(let V=0;V<L.length;V++){let v=L[V],I=v.column||w,Lt=O.find(M=>E(M.name)===E(I));if(!Lt)throw new Error(`Column '${I}' not found in query for AND condition`);let Se=Lt.value;if("="in v&&v["="]!==void 0){let M=`${w}_and_${V}_eq`,F=new T(M,v["="]);d.appendWhere(new C(Se,"=",F))}if("min"in v&&v.min!==void 0){let M=`${w}_and_${V}_min`,F=new T(M,v.min);d.appendWhere(new C(Se,">=",F))}if("max"in v&&v.max!==void 0){let M=`${w}_and_${V}_max`,F=new T(M,v.max);d.appendWhere(new C(Se,"<=",F))}if("like"in v&&v.like!==void 0){let M=`${w}_and_${V}_like`,F=new T(M,v.like);d.appendWhere(new C(Se,"like",F))}if("ilike"in v&&v.ilike!==void 0){let M=`${w}_and_${V}_ilike`,F=new T(M,v.ilike);d.appendWhere(new C(Se,"ilike",F))}if("in"in v&&v.in!==void 0){let F=v.in.map((q,z)=>new T(`${w}_and_${V}_in_${z}`,q));d.appendWhere(new C(Se,"in",new G(new K(F))))}if("any"in v&&v.any!==void 0){let M=`${w}_and_${V}_any`,F=new T(M,v.any);d.appendWhere(new C(Se,"=",new W(null,"any",F,null)))}if("<"in v&&v["<"]!==void 0){let M=`${w}_and_${V}_lt`,F=new T(M,v["<"]);d.appendWhere(new C(Se,"<",F))}if(">"in v&&v[">"]!==void 0){let M=`${w}_and_${V}_gt`,F=new T(M,v[">"]);d.appendWhere(new C(Se,">",F))}if("!="in v&&v["!="]!==void 0){let M=`${w}_and_${V}_neq`,F=new T(M,v["!="]);d.appendWhere(new C(Se,"!=",F))}if("<>"in v&&v["<>"]!==void 0){let M=`${w}_and_${V}_ne`,F=new T(M,v["<>"]);d.appendWhere(new C(Se,"<>",F))}if("<="in v&&v["<="]!==void 0){let M=`${w}_and_${V}_le`,F=new T(M,v["<="]);d.appendWhere(new C(Se,"<=",F))}if(">="in v&&v[">="]!==void 0){let M=`${w}_and_${V}_ge`,F=new T(M,v[">="]);d.appendWhere(new C(Se,">=",F))}}}function m(d,w,L,E,O,N){let V=[];for(let v=0;v<L.length;v++){let I=L[v],Lt=I.column||w,Se=O.find(q=>E(q.name)===E(Lt));if(!Se)throw new Error(`Column '${Lt}' not found in query for OR condition`);let M=Se.value,F=[];if("="in I&&I["="]!==void 0){let q=`${w}_or_${v}_eq`,z=new T(q,I["="]);F.push(new C(M,"=",z))}if("min"in I&&I.min!==void 0){let q=`${w}_or_${v}_min`,z=new T(q,I.min);F.push(new C(M,">=",z))}if("max"in I&&I.max!==void 0){let q=`${w}_or_${v}_max`,z=new T(q,I.max);F.push(new C(M,"<=",z))}if("like"in I&&I.like!==void 0){let q=`${w}_or_${v}_like`,z=new T(q,I.like);F.push(new C(M,"like",z))}if("ilike"in I&&I.ilike!==void 0){let q=`${w}_or_${v}_ilike`,z=new T(q,I.ilike);F.push(new C(M,"ilike",z))}if("in"in I&&I.in!==void 0){let z=I.in.map((Pr,Or)=>new T(`${w}_or_${v}_in_${Or}`,Pr));F.push(new C(M,"in",new G(new K(z))))}if("any"in I&&I.any!==void 0){let q=`${w}_or_${v}_any`,z=new T(q,I.any);F.push(new C(M,"=",new W(null,"any",z,null)))}if("<"in I&&I["<"]!==void 0){let q=`${w}_or_${v}_lt`,z=new T(q,I["<"]);F.push(new C(M,"<",z))}if(">"in I&&I[">"]!==void 0){let q=`${w}_or_${v}_gt`,z=new T(q,I[">"]);F.push(new C(M,">",z))}if("!="in I&&I["!="]!==void 0){let q=`${w}_or_${v}_neq`,z=new T(q,I["!="]);F.push(new C(M,"!=",z))}if("<>"in I&&I["<>"]!==void 0){let q=`${w}_or_${v}_ne`,z=new T(q,I["<>"]);F.push(new C(M,"<>",z))}if("<="in I&&I["<="]!==void 0){let q=`${w}_or_${v}_le`,z=new T(q,I["<="]);F.push(new C(M,"<=",z))}if(">="in I&&I[">="]!==void 0){let q=`${w}_or_${v}_ge`,z=new T(q,I[">="]);F.push(new C(M,">=",z))}if(F.length>0){let q=F[0];for(let z=1;z<F.length;z++)q=new C(q,"and",F[z]);F.length>1?V.push(new G(q)):V.push(q)}}if(V.length>0){let v=V[0];for(let I=1;I<V.length;I++)v=new C(v,"or",V[I]);d.appendWhere(new G(v))}}function h(d,w,L){Object.keys(d).forEach(E=>{if(!w.includes(E))throw new Error(`Unsupported operator '${E}' for state key '${L}'`)})}function g(d,w,L,E){let O=new T(L,E);d.appendWhere(new C(w,"=",O))}function b(d,w,L,E){let O=[];if("="in E){let N=new T(L,E["="]);O.push(new C(w,"=",N))}if("min"in E){let N=new T(L+"_min",E.min);O.push(new C(w,">=",N))}if("max"in E){let N=new T(L+"_max",E.max);O.push(new C(w,"<=",N))}if("like"in E){let N=new T(L+"_like",E.like);O.push(new C(w,"like",N))}if("ilike"in E){let N=new T(L+"_ilike",E.ilike);O.push(new C(w,"ilike",N))}if("in"in E){let V=E.in.map((v,I)=>new T(`${L}_in_${I}`,v));O.push(new C(w,"in",new G(new K(V))))}if("any"in E){let N=new T(L+"_any",E.any);O.push(new C(w,"=",new W(null,"any",N,null)))}if("<"in E){let N=new T(L+"_lt",E["<"]);O.push(new C(w,"<",N))}if(">"in E){let N=new T(L+"_gt",E[">"]);O.push(new C(w,">",N))}if("!="in E){let N=new T(L+"_neq",E["!="]);O.push(new C(w,"!=",N))}if("<>"in E){let N=new T(L+"_ne",E["<>"]);O.push(new C(w,"<>",N))}if("<="in E){let N=new T(L+"_le",E["<="]);O.push(new C(w,"<=",N))}if(">="in E){let N=new T(L+"_ge",E[">="]);O.push(new C(w,">=",N))}if(O.length===1)d.appendWhere(O[0]);else if(O.length>1){let N=O[0];for(let V=1;V<O.length;V++)N=new C(N,"and",O[V]);d.appendWhere(new G(N))}}return e}isOrCondition(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"or"in e}isAndCondition(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"and"in e}isExplicitColumnMapping(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"column"in e&&!("or"in e)}isValidatableObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}hasColumnMapping(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"column"in e}isSimpleValue(e){return e===null||typeof e!="object"||Array.isArray(e)||e instanceof Date}processStateParameter(e,t,n,r,i,s,a,l,u,c,m,h){if(this.isOrCondition(t)){let g=t.or;if(g&&g.length>0){let b=this.findTargetQueryForLogicalCondition(r,n,e,g),d=this.getAllAvailableColumns(b,i);l(b,e,g,s,d,i);return}}if(this.isAndCondition(t)){let g=t.and;if(g&&g.length>0){let b=this.findTargetQueryForLogicalCondition(r,n,e,g),d=this.getAllAvailableColumns(b,i);u(b,e,g,s,d,i);return}}if(this.isExplicitColumnMapping(t)){let g=t.column;if(g){let b=r.find(n,g);if(b.length===0)throw new Error(`Explicit column '${g}' not found in query`);for(let d of b){let L=this.getAllAvailableColumns(d,i).find(E=>s(E.name)===s(g));if(!L)throw new Error(`Explicit column '${g}' not found in query`);this.isValidatableObject(t)&&h(t,a,e),m(d,L.value,e,t)}return}}this.processRegularColumnCondition(e,t,n,r,i,s,a,c,m,h)}processRegularColumnCondition(e,t,n,r,i,s,a,l,u,c){let m=r.find(n,e);if(m.length===0)throw new Error(`Column '${e}' not found in query`);for(let h of m){let g=this.getAllAvailableColumns(h,i),b=g.find(E=>s(E.name)===s(e));if(!b)throw new Error(`Column '${e}' not found in query`);let d=b.value;this.isValidatableObject(t)&&c(t,a,e);let w=d,L=e;if(this.hasColumnMapping(t)){let E=t.column;if(E){let O=g.find(N=>s(N.name)===s(E));O&&(w=O.value,L=E)}}this.isSimpleValue(t)?l(h,w,L,t):u(h,w,L,t)}}findTargetQueryForLogicalCondition(e,t,n,r){let i=r.map(a=>a.column||n).filter((a,l,u)=>u.indexOf(a)===l);for(let a of i){let l=e.find(t,a);if(l.length>0)return l[0]}let s=r===r.or?"OR":"AND";throw new Error(`None of the ${s} condition columns [${i.join(", ")}] found in query`)}getAllAvailableColumns(e,t){let n=t.collect(e),r=this.collectCTEColumns(e);return[...n,...r]}collectCTEColumns(e){let t=[];if(e.withClause)for(let n of e.withClause.tables)try{let r=this.collectColumnsFromSelectQuery(n.query);t.push(...r)}catch(r){console.warn(`Failed to collect columns from CTE '${n.getSourceAliasName()}':`,r)}return t}collectColumnsFromSelectQuery(e){return e instanceof y?new Ie(this.tableColumnResolver).collect(e):e instanceof Q?this.collectColumnsFromSelectQuery(e.left):[]}};var en=class{constructor(e){this.tableColumnResolver=e}static removeOrderBy(e){if(typeof e=="string"&&(e=A.parse(e)),!(e instanceof y))throw new Error("Complex queries are not supported for ORDER BY removal");return new y({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:null,windowClause:e.windowClause,limitClause:e.limitClause,offsetClause:e.offsetClause,fetchClause:e.fetchClause,forClause:e.forClause})}inject(e,t){if(typeof e=="string"&&(e=A.parse(e)),!(e instanceof y))throw new Error("Complex queries are not supported for sorting");let r=new Ie(this.tableColumnResolver).collect(e);for(let l of Object.keys(t))if(!r.find(c=>c.name===l))throw new Error(`Column or alias '${l}' not found in current query`);let i=[];for(let[l,u]of Object.entries(t)){let c=r.find(d=>d.name===l);if(!c)continue;let m=c.value;this.validateSortCondition(l,u);let h;u.desc?h="desc":h="asc";let g=null;u.nullsFirst?g="first":u.nullsLast&&(g="last");let b=new Oe(m,h,g);i.push(b)}let s=[];e.orderByClause?s=[...e.orderByClause.order,...i]:s=i;let a=s.length>0?new ue(s):null;return new y({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:a,windowClause:e.windowClause,limitClause:e.limitClause,offsetClause:e.offsetClause,fetchClause:e.fetchClause,forClause:e.forClause})}validateSortCondition(e,t){if(t.asc&&t.desc)throw new Error(`Conflicting sort directions for column '${e}': both asc and desc specified`);if(t.nullsFirst&&t.nullsLast)throw new Error(`Conflicting nulls positions for column '${e}': both nullsFirst and nullsLast specified`);if(!t.asc&&!t.desc&&!t.nullsFirst&&!t.nullsLast)throw new Error(`Empty sort condition for column '${e}': at least one sort option must be specified`)}};var tn=class{inject(e,t){if(this.validatePaginationOptions(t),typeof e=="string"&&(e=A.parse(e)),!(e instanceof y))throw new Error("Complex queries are not supported for pagination");if(e.limitClause||e.offsetClause)throw new Error("Query already contains LIMIT or OFFSET clause. Use removePagination() first if you want to override existing pagination.");let n=(t.page-1)*t.pageSize,r=new oe(new T("paging_limit",t.pageSize)),i=new Re(new T("paging_offset",n));return new y({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:e.orderByClause,windowClause:e.windowClause,limitClause:r,offsetClause:i,fetchClause:e.fetchClause,forClause:e.forClause})}static removePagination(e){if(typeof e=="string"&&(e=A.parse(e)),!(e instanceof y))throw new Error("Complex queries are not supported for pagination removal");return new y({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:e.orderByClause,windowClause:e.windowClause,limitClause:null,offsetClause:null,fetchClause:e.fetchClause,forClause:e.forClause})}validatePaginationOptions(e){if(!e)throw new Error("Pagination options are required");if(typeof e.page!="number"||e.page<1)throw new Error("Page number must be a positive integer (1 or greater)");if(typeof e.pageSize!="number"||e.pageSize<1)throw new Error("Page size must be a positive integer (1 or greater)");if(e.pageSize>1e3)throw new Error("Page size cannot exceed 1000 items")}};var Ft=class{static extractParameterNames(e){return lt.collect(e).map(n=>n.name.value)}static hasParameter(e,t){return this.extractParameterNames(e).includes(t)}static separateFilters(e,t){let n=this.extractParameterNames(e),r={},i={};for(let[s,a]of Object.entries(t))n.includes(s)?r[s]=a:i[s]=a;return{hardcodedParams:r,dynamicFilters:i}}};var Yn=class{constructor(e={}){this.options={requireAllParameters:!0,...e}}bind(e,t){let n=e,r=Ft.extractParameterNames(n);if(this.options.requireAllParameters){let i=r.filter(s=>!(s in t)||t[s]===void 0);if(i.length>0)throw new Error(`Missing values for required parameters: ${i.join(", ")}`)}for(let[i,s]of Object.entries(t))if(r.includes(i))try{Ye.set(n,i,s)}catch(a){throw new Error(`Failed to bind parameter '${i}': ${a instanceof Error?a.message:"Unknown error"}`)}return n}bindToSimpleQuery(e,t){return this.bind(e,t)}};var Cr=class{constructor(e){this.tableColumnResolver=e}buildQuery(e,t={}){let n;try{n=A.parse(e)}catch(i){throw new Error(`Failed to parse SQL: ${i instanceof Error?i.message:"Unknown error"}`)}let r=n;if(t.filter&&Object.keys(t.filter).length>0){let{hardcodedParams:i,dynamicFilters:s}=Ft.separateFilters(r,t.filter);if(Object.keys(i).length>0&&(r=new Yn({requireAllParameters:!1}).bind(r,i)),Object.keys(s).length>0){let a=new Zt(this.tableColumnResolver),l=Ne.buildSimpleQuery(r);r=a.inject(l,s)}}if(t.sort&&Object.keys(t.sort).length>0){let i=new en(this.tableColumnResolver),s=Ne.buildSimpleQuery(r);r=i.inject(s,t.sort)}if(t.paging){let{page:i=1,pageSize:s}=t.paging;if(s!==void 0){let a=new tn,l={page:i,pageSize:s},u=Ne.buildSimpleQuery(r);r=a.inject(u,l)}}if(t.serialize&&typeof t.serialize=="object"){let i=new Jt,s=Ne.buildSimpleQuery(r);r=i.buildJsonQuery(s,t.serialize)}return r}buildFilteredQuery(e,t){return this.buildQuery(e,{filter:t})}buildSortedQuery(e,t){return this.buildQuery(e,{sort:t})}buildPaginatedQuery(e,t){return this.buildQuery(e,{paging:t})}buildSerializedQuery(e,t){return this.buildQuery(e,{serialize:t})}validateSql(e){try{return A.parse(e),!0}catch(t){throw new Error(`Invalid SQL: ${t instanceof Error?t.message:"Unknown error"}`)}}};var yr=class{static validate(e,t){let n=this.extractStructureFromJsonMapping(e);return this.compareStructures(n,t)}static validateStrict(e,t){let n=this.validate(e,t);if(!n.isValid){let r=["JsonMapping validation failed:",...n.errors].join(`
|
|
59
|
+
`),n}getOrCreateTable(e){let t=`table_${e}`,n=this.nodes.get(t);return n||(n=At.createTable(e),this.addNode(n)),n}getOrCreateCTE(e){let t=`cte_${e}`,n=this.nodes.get(t);return n||(n=At.createCTE(e),this.addNode(n)),n}getOrCreateSubquery(e){let t=`subquery_${e}`,n=this.nodes.get(t);return n||(n=At.createSubquery(e),this.addNode(n)),n}createProcessNode(e,t){let n=new _n(t,e);return this.addNode(n),n}createJoinNode(e,t){let n=_t.createJoin(e,t);return this.addNode(n),n}createSetOperationNode(e,t){let n=_t.createSetOperation(e,t);return this.addNode(n),n}createOutputNode(e="main"){let t=new zn(e);return this.addNode(t),t}};var Ht=class{constructor(e){this.graph=e}processSource(e,t,n){if(e.datasource instanceof R)return this.processTableSource(e.datasource,t);if(e.datasource instanceof J)return this.processSubquerySource(e,t,n);throw new Error("Unsupported source type")}processTableSource(e,t){let n=e.getSourceName();return t.has(n)?this.graph.getOrCreateCTE(n).id:this.graph.getOrCreateTable(n).id}processSubquerySource(e,t,n){let r=e.aliasExpression?.table.name||"subquery",i=this.graph.getOrCreateSubquery(r),s=n(e.datasource.query,`subquery_${r}_internal`,t);return s&&!this.graph.hasConnection(s,i.id)&&this.graph.addConnection(s,i.id),i.id}extractTableNodeIds(e,t){let n=[],r=e.source;if(r.datasource instanceof R){let i=r.datasource.getSourceName();if(t.has(i)){let s=this.graph.getOrCreateCTE(i);n.push(s.id)}else{let s=this.graph.getOrCreateTable(i);n.push(s.id)}}if(e.joins&&e.joins.length>0)for(let i of e.joins){let s=i.source;if(s.datasource instanceof R){let a=s.datasource.getSourceName();if(t.has(a)){let l=this.graph.getOrCreateCTE(a);n.push(l.id)}else{let l=this.graph.getOrCreateTable(a);n.push(l.id)}}}return n}};var Gt=class{constructor(e,t){this.graph=e;this.dataSourceHandler=t;this.joinIdCounter=0}resetJoinCounter(){this.joinIdCounter=0}getNextJoinId(){return String(++this.joinIdCounter)}processFromClause(e,t,n){let r=this.dataSourceHandler.processSource(e.source,t,n);return e.joins&&e.joins.length>0?this.processJoins(e.joins,r,t,n):r}processJoins(e,t,n,r){let i=t;for(let s of e){let a=this.dataSourceHandler.processSource(s.source,n,r),l=this.getNextJoinId(),u=this.graph.createJoinNode(l,s.joinType.value),{leftLabel:c,rightLabel:m}=this.getJoinNullabilityLabels(s.joinType.value);i&&!this.graph.hasConnection(i,u.id)&&this.graph.addConnection(i,u.id,c),a&&!this.graph.hasConnection(a,u.id)&&this.graph.addConnection(a,u.id,m),i=u.id}return i}getJoinNullabilityLabels(e){switch(e.toLowerCase()){case"left join":return{leftLabel:"NOT NULL",rightLabel:"NULLABLE"};case"right join":return{leftLabel:"NULLABLE",rightLabel:"NOT NULL"};case"inner join":case"join":return{leftLabel:"NOT NULL",rightLabel:"NOT NULL"};case"full join":case"full outer join":return{leftLabel:"NULLABLE",rightLabel:"NULLABLE"};case"cross join":return{leftLabel:"NOT NULL",rightLabel:"NOT NULL"};default:return{leftLabel:"",rightLabel:""}}}};var Yt=class{constructor(e,t){this.graph=e;this.dataSourceHandler=t}processQueryClauses(e,t,n,r,i){return n}};var Xt=class{constructor(e){this.graph=e}processCTEs(e,t,n){for(let r=0;r<e.tables.length;r++){let s=e.tables[r].getSourceAliasName(),a=this.graph.getOrCreateCTE(s);t.add(s),e.recursive&&r===0&&a.addAnnotation("recursive")}for(let r=0;r<e.tables.length;r++){let i=e.tables[r],s=i.getSourceAliasName(),a=this.graph.getOrCreateCTE(s),l=n(i.query,`cte_${s}`,t);if(l&&!this.graph.hasConnection(l,a.id)){let c=e.recursive&&r===0?"RECURSIVE":void 0;this.graph.addConnection(l,a.id,c)}}}detectRecursiveReference(e,t){return e.toString().toLowerCase().includes(t.toLowerCase())}};var fr=class o{constructor(){this.graph=new zt,this.dataSourceHandler=new Ht(this.graph),this.joinHandler=new Gt(this.graph,this.dataSourceHandler),this.processHandler=new Yt(this.graph,this.dataSourceHandler),this.cteHandler=new Xt(this.graph)}generateMermaidFlow(e,t){this.graph=new zt,this.dataSourceHandler=new Ht(this.graph),this.joinHandler=new Gt(this.graph,this.dataSourceHandler),this.processHandler=new Yt(this.graph,this.dataSourceHandler),this.cteHandler=new Xt(this.graph),this.joinHandler.resetJoinCounter();let n=typeof e=="string"?A.parse(e):e,r=new Set;return this.processQuery(n,"main",r),this.graph.generateMermaid(t?.direction||"TD",t?.title)}static generate(e){return new o().generateMermaidFlow(e)}processQuery(e,t,n){if(e instanceof y)return this.processSimpleQuery(e,t,n);if(e instanceof Q)return this.processBinaryQuery(e,t,n);throw new Error("Unsupported query type")}processSimpleQuery(e,t,n){e.withClause&&this.cteHandler.processCTEs(e.withClause,n,this.processQuery.bind(this));let r="";return e.fromClause&&(e.fromClause.joins&&e.fromClause.joins.length>0?r=this.joinHandler.processFromClause(e.fromClause,n,this.processQuery.bind(this)):r=this.dataSourceHandler.processSource(e.fromClause.source,n,this.processQuery.bind(this))),r&&(r=this.processHandler.processQueryClauses(e,t,r,n,this.processQuery.bind(this))),this.handleOutputNode(r,t)}processBinaryQuery(e,t,n){let r=this.flattenBinaryChain(e,e.operator.value);return r.length>2?this.processMultiPartOperation(r,e.operator.value,t,n):this.processSimpleBinaryOperation(e,t,n)}processSimpleBinaryOperation(e,t,n){let r=this.processQuery(e.left,`${t}_left`,n),i=this.processQuery(e.right,`${t}_right`,n),s=t==="main"?"main":t.replace(/^cte_/,""),a=this.graph.createSetOperationNode(s,e.operator.value);return r&&!this.graph.hasConnection(r,a.id)&&this.graph.addConnection(r,a.id),i&&!this.graph.hasConnection(i,a.id)&&this.graph.addConnection(i,a.id),a.id}processMultiPartOperation(e,t,n,r){let i=[],s=n==="main"?"main":n.replace(/^cte_/,""),a=this.graph.createSetOperationNode(s,t);for(let l=0;l<e.length;l++){let u=`${n}_part${l+1}`,c=this.processQuery(e[l],u,r);i.push(c)}for(let l of i)l&&!this.graph.hasConnection(l,a.id)&&this.graph.addConnection(l,a.id);return a.id}handleOutputNode(e,t){if(t==="main"){let n=this.graph.createOutputNode(t);return e&&this.graph.addConnection(e,n.id),n.id}return e}flattenBinaryChain(e,t){let n=[],r=i=>{i instanceof Q&&i.operator.value===t?(r(i.left),r(i.right)):n.push(i)};return r(e),n}};var Zt=class{constructor(e,t){typeof e=="function"?(this.tableColumnResolver=e,this.options=t||{}):(this.tableColumnResolver=void 0,this.options=e||{})}inject(e,t){typeof e=="string"&&(e=A.parse(e));let n=new Ct(this.tableColumnResolver,this.options),r=new Ie(this.tableColumnResolver),i=d=>this.options.ignoreCaseAndUnderscore?d.toLowerCase().replace(/_/g,""):d,s=["min","max","like","ilike","in","any","=","<",">","!=","<>","<=",">=","or","and","column"],a=Object.values(t);if(a.length>0&&a.every(d=>d===void 0)&&!this.options.allowAllUndefined)throw new Error("All parameters are undefined. This would result in fetching all records. Use allowAllUndefined: true option to explicitly allow this behavior.");for(let[d,w]of Object.entries(t))w!==void 0&&this.processStateParameter(d,w,e,n,r,i,s,m,c,g,b,h);function c(d,w,L,E,O,N){for(let V=0;V<L.length;V++){let v=L[V],I=v.column||w,Lt=O.find(M=>E(M.name)===E(I));if(!Lt)throw new Error(`Column '${I}' not found in query for AND condition`);let Se=Lt.value;if("="in v&&v["="]!==void 0){let M=`${w}_and_${V}_eq`,F=new T(M,v["="]);d.appendWhere(new C(Se,"=",F))}if("min"in v&&v.min!==void 0){let M=`${w}_and_${V}_min`,F=new T(M,v.min);d.appendWhere(new C(Se,">=",F))}if("max"in v&&v.max!==void 0){let M=`${w}_and_${V}_max`,F=new T(M,v.max);d.appendWhere(new C(Se,"<=",F))}if("like"in v&&v.like!==void 0){let M=`${w}_and_${V}_like`,F=new T(M,v.like);d.appendWhere(new C(Se,"like",F))}if("ilike"in v&&v.ilike!==void 0){let M=`${w}_and_${V}_ilike`,F=new T(M,v.ilike);d.appendWhere(new C(Se,"ilike",F))}if("in"in v&&v.in!==void 0){let F=v.in.map((q,z)=>new T(`${w}_and_${V}_in_${z}`,q));d.appendWhere(new C(Se,"in",new G(new K(F))))}if("any"in v&&v.any!==void 0){let M=`${w}_and_${V}_any`,F=new T(M,v.any);d.appendWhere(new C(Se,"=",new W(null,"any",F,null)))}if("<"in v&&v["<"]!==void 0){let M=`${w}_and_${V}_lt`,F=new T(M,v["<"]);d.appendWhere(new C(Se,"<",F))}if(">"in v&&v[">"]!==void 0){let M=`${w}_and_${V}_gt`,F=new T(M,v[">"]);d.appendWhere(new C(Se,">",F))}if("!="in v&&v["!="]!==void 0){let M=`${w}_and_${V}_neq`,F=new T(M,v["!="]);d.appendWhere(new C(Se,"!=",F))}if("<>"in v&&v["<>"]!==void 0){let M=`${w}_and_${V}_ne`,F=new T(M,v["<>"]);d.appendWhere(new C(Se,"<>",F))}if("<="in v&&v["<="]!==void 0){let M=`${w}_and_${V}_le`,F=new T(M,v["<="]);d.appendWhere(new C(Se,"<=",F))}if(">="in v&&v[">="]!==void 0){let M=`${w}_and_${V}_ge`,F=new T(M,v[">="]);d.appendWhere(new C(Se,">=",F))}}}function m(d,w,L,E,O,N){let V=[];for(let v=0;v<L.length;v++){let I=L[v],Lt=I.column||w,Se=O.find(q=>E(q.name)===E(Lt));if(!Se)throw new Error(`Column '${Lt}' not found in query for OR condition`);let M=Se.value,F=[];if("="in I&&I["="]!==void 0){let q=`${w}_or_${v}_eq`,z=new T(q,I["="]);F.push(new C(M,"=",z))}if("min"in I&&I.min!==void 0){let q=`${w}_or_${v}_min`,z=new T(q,I.min);F.push(new C(M,">=",z))}if("max"in I&&I.max!==void 0){let q=`${w}_or_${v}_max`,z=new T(q,I.max);F.push(new C(M,"<=",z))}if("like"in I&&I.like!==void 0){let q=`${w}_or_${v}_like`,z=new T(q,I.like);F.push(new C(M,"like",z))}if("ilike"in I&&I.ilike!==void 0){let q=`${w}_or_${v}_ilike`,z=new T(q,I.ilike);F.push(new C(M,"ilike",z))}if("in"in I&&I.in!==void 0){let z=I.in.map((Pr,Or)=>new T(`${w}_or_${v}_in_${Or}`,Pr));F.push(new C(M,"in",new G(new K(z))))}if("any"in I&&I.any!==void 0){let q=`${w}_or_${v}_any`,z=new T(q,I.any);F.push(new C(M,"=",new W(null,"any",z,null)))}if("<"in I&&I["<"]!==void 0){let q=`${w}_or_${v}_lt`,z=new T(q,I["<"]);F.push(new C(M,"<",z))}if(">"in I&&I[">"]!==void 0){let q=`${w}_or_${v}_gt`,z=new T(q,I[">"]);F.push(new C(M,">",z))}if("!="in I&&I["!="]!==void 0){let q=`${w}_or_${v}_neq`,z=new T(q,I["!="]);F.push(new C(M,"!=",z))}if("<>"in I&&I["<>"]!==void 0){let q=`${w}_or_${v}_ne`,z=new T(q,I["<>"]);F.push(new C(M,"<>",z))}if("<="in I&&I["<="]!==void 0){let q=`${w}_or_${v}_le`,z=new T(q,I["<="]);F.push(new C(M,"<=",z))}if(">="in I&&I[">="]!==void 0){let q=`${w}_or_${v}_ge`,z=new T(q,I[">="]);F.push(new C(M,">=",z))}if(F.length>0){let q=F[0];for(let z=1;z<F.length;z++)q=new C(q,"and",F[z]);F.length>1?V.push(new G(q)):V.push(q)}}if(V.length>0){let v=V[0];for(let I=1;I<V.length;I++)v=new C(v,"or",V[I]);d.appendWhere(new G(v))}}function h(d,w,L){Object.keys(d).forEach(E=>{if(!w.includes(E))throw new Error(`Unsupported operator '${E}' for state key '${L}'`)})}function g(d,w,L,E){let O=new T(L,E);d.appendWhere(new C(w,"=",O))}function b(d,w,L,E){let O=[];if("="in E){let N=new T(L,E["="]);O.push(new C(w,"=",N))}if("min"in E){let N=new T(L+"_min",E.min);O.push(new C(w,">=",N))}if("max"in E){let N=new T(L+"_max",E.max);O.push(new C(w,"<=",N))}if("like"in E){let N=new T(L+"_like",E.like);O.push(new C(w,"like",N))}if("ilike"in E){let N=new T(L+"_ilike",E.ilike);O.push(new C(w,"ilike",N))}if("in"in E){let V=E.in.map((v,I)=>new T(`${L}_in_${I}`,v));O.push(new C(w,"in",new G(new K(V))))}if("any"in E){let N=new T(L+"_any",E.any);O.push(new C(w,"=",new W(null,"any",N,null)))}if("<"in E){let N=new T(L+"_lt",E["<"]);O.push(new C(w,"<",N))}if(">"in E){let N=new T(L+"_gt",E[">"]);O.push(new C(w,">",N))}if("!="in E){let N=new T(L+"_neq",E["!="]);O.push(new C(w,"!=",N))}if("<>"in E){let N=new T(L+"_ne",E["<>"]);O.push(new C(w,"<>",N))}if("<="in E){let N=new T(L+"_le",E["<="]);O.push(new C(w,"<=",N))}if(">="in E){let N=new T(L+"_ge",E[">="]);O.push(new C(w,">=",N))}if(O.length===1)d.appendWhere(O[0]);else if(O.length>1){let N=O[0];for(let V=1;V<O.length;V++)N=new C(N,"and",O[V]);d.appendWhere(new G(N))}}return e}isOrCondition(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"or"in e}isAndCondition(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"and"in e}isExplicitColumnMapping(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"column"in e&&!("or"in e)}isValidatableObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}hasColumnMapping(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"column"in e}isSimpleValue(e){return e===null||typeof e!="object"||Array.isArray(e)||e instanceof Date}processStateParameter(e,t,n,r,i,s,a,l,u,c,m,h){if(this.isOrCondition(t)){let g=t.or;if(g&&g.length>0){let b=this.findTargetQueryForLogicalCondition(r,n,e,g),d=this.getAllAvailableColumns(b,i);l(b,e,g,s,d,i);return}}if(this.isAndCondition(t)){let g=t.and;if(g&&g.length>0){let b=this.findTargetQueryForLogicalCondition(r,n,e,g),d=this.getAllAvailableColumns(b,i);u(b,e,g,s,d,i);return}}if(this.isExplicitColumnMapping(t)){let g=t.column;if(g){let b=r.find(n,g);if(b.length===0)throw new Error(`Explicit column '${g}' not found in query`);for(let d of b){let L=this.getAllAvailableColumns(d,i).find(E=>s(E.name)===s(g));if(!L)throw new Error(`Explicit column '${g}' not found in query`);this.isValidatableObject(t)&&h(t,a,e),m(d,L.value,e,t)}return}}this.processRegularColumnCondition(e,t,n,r,i,s,a,c,m,h)}processRegularColumnCondition(e,t,n,r,i,s,a,l,u,c){let m=r.find(n,e);if(m.length===0){if(this.options.ignoreNonExistentColumns)return;throw new Error(`Column '${e}' not found in query`)}for(let h of m){let g=this.getAllAvailableColumns(h,i),b=g.find(E=>s(E.name)===s(e));if(!b)throw new Error(`Column '${e}' not found in query`);let d=b.value;this.isValidatableObject(t)&&c(t,a,e);let w=d,L=e;if(this.hasColumnMapping(t)){let E=t.column;if(E){let O=g.find(N=>s(N.name)===s(E));O&&(w=O.value,L=E)}}this.isSimpleValue(t)?l(h,w,L,t):u(h,w,L,t)}}findTargetQueryForLogicalCondition(e,t,n,r){let i=r.map(a=>a.column||n).filter((a,l,u)=>u.indexOf(a)===l);for(let a of i){let l=e.find(t,a);if(l.length>0)return l[0]}let s=r===r.or?"OR":"AND";throw new Error(`None of the ${s} condition columns [${i.join(", ")}] found in query`)}getAllAvailableColumns(e,t){let n=t.collect(e),r=this.collectCTEColumns(e);return[...n,...r]}collectCTEColumns(e){let t=[];if(e.withClause)for(let n of e.withClause.tables)try{let r=this.collectColumnsFromSelectQuery(n.query);t.push(...r)}catch(r){console.warn(`Failed to collect columns from CTE '${n.getSourceAliasName()}':`,r)}return t}collectColumnsFromSelectQuery(e){return e instanceof y?new Ie(this.tableColumnResolver).collect(e):e instanceof Q?this.collectColumnsFromSelectQuery(e.left):[]}};var en=class{constructor(e){this.tableColumnResolver=e}static removeOrderBy(e){if(typeof e=="string"&&(e=A.parse(e)),!(e instanceof y))throw new Error("Complex queries are not supported for ORDER BY removal");return new y({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:null,windowClause:e.windowClause,limitClause:e.limitClause,offsetClause:e.offsetClause,fetchClause:e.fetchClause,forClause:e.forClause})}inject(e,t){if(typeof e=="string"&&(e=A.parse(e)),!(e instanceof y))throw new Error("Complex queries are not supported for sorting");let r=new Ie(this.tableColumnResolver).collect(e);for(let l of Object.keys(t))if(!r.find(c=>c.name===l))throw new Error(`Column or alias '${l}' not found in current query`);let i=[];for(let[l,u]of Object.entries(t)){let c=r.find(d=>d.name===l);if(!c)continue;let m=c.value;this.validateSortCondition(l,u);let h;u.desc?h="desc":h="asc";let g=null;u.nullsFirst?g="first":u.nullsLast&&(g="last");let b=new Oe(m,h,g);i.push(b)}let s=[];e.orderByClause?s=[...e.orderByClause.order,...i]:s=i;let a=s.length>0?new ue(s):null;return new y({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:a,windowClause:e.windowClause,limitClause:e.limitClause,offsetClause:e.offsetClause,fetchClause:e.fetchClause,forClause:e.forClause})}validateSortCondition(e,t){if(t.asc&&t.desc)throw new Error(`Conflicting sort directions for column '${e}': both asc and desc specified`);if(t.nullsFirst&&t.nullsLast)throw new Error(`Conflicting nulls positions for column '${e}': both nullsFirst and nullsLast specified`);if(!t.asc&&!t.desc&&!t.nullsFirst&&!t.nullsLast)throw new Error(`Empty sort condition for column '${e}': at least one sort option must be specified`)}};var tn=class{inject(e,t){if(this.validatePaginationOptions(t),typeof e=="string"&&(e=A.parse(e)),!(e instanceof y))throw new Error("Complex queries are not supported for pagination");if(e.limitClause||e.offsetClause)throw new Error("Query already contains LIMIT or OFFSET clause. Use removePagination() first if you want to override existing pagination.");let n=(t.page-1)*t.pageSize,r=new oe(new T("paging_limit",t.pageSize)),i=new Re(new T("paging_offset",n));return new y({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:e.orderByClause,windowClause:e.windowClause,limitClause:r,offsetClause:i,fetchClause:e.fetchClause,forClause:e.forClause})}static removePagination(e){if(typeof e=="string"&&(e=A.parse(e)),!(e instanceof y))throw new Error("Complex queries are not supported for pagination removal");return new y({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:e.orderByClause,windowClause:e.windowClause,limitClause:null,offsetClause:null,fetchClause:e.fetchClause,forClause:e.forClause})}validatePaginationOptions(e){if(!e)throw new Error("Pagination options are required");if(typeof e.page!="number"||e.page<1)throw new Error("Page number must be a positive integer (1 or greater)");if(typeof e.pageSize!="number"||e.pageSize<1)throw new Error("Page size must be a positive integer (1 or greater)");if(e.pageSize>1e3)throw new Error("Page size cannot exceed 1000 items")}};var Ft=class{static extractParameterNames(e){return lt.collect(e).map(n=>n.name.value)}static hasParameter(e,t){return this.extractParameterNames(e).includes(t)}static separateFilters(e,t){let n=this.extractParameterNames(e),r={},i={};for(let[s,a]of Object.entries(t))n.includes(s)?r[s]=a:i[s]=a;return{hardcodedParams:r,dynamicFilters:i}}};var Yn=class{constructor(e={}){this.options={requireAllParameters:!0,...e}}bind(e,t){let n=e,r=Ft.extractParameterNames(n);if(this.options.requireAllParameters){let i=r.filter(s=>!(s in t)||t[s]===void 0);if(i.length>0)throw new Error(`Missing values for required parameters: ${i.join(", ")}`)}for(let[i,s]of Object.entries(t))if(r.includes(i))try{Ye.set(n,i,s)}catch(a){throw new Error(`Failed to bind parameter '${i}': ${a instanceof Error?a.message:"Unknown error"}`)}return n}bindToSimpleQuery(e,t){return this.bind(e,t)}};var Cr=class{constructor(e){this.tableColumnResolver=e}buildQuery(e,t={}){let n;try{n=A.parse(e)}catch(i){throw new Error(`Failed to parse SQL: ${i instanceof Error?i.message:"Unknown error"}`)}let r=n;if(t.filter&&Object.keys(t.filter).length>0){let{hardcodedParams:i,dynamicFilters:s}=Ft.separateFilters(r,t.filter);if(Object.keys(i).length>0&&(r=new Yn({requireAllParameters:!1}).bind(r,i)),Object.keys(s).length>0){let a=new Zt(this.tableColumnResolver),l=Ne.buildSimpleQuery(r);r=a.inject(l,s)}}if(t.sort&&Object.keys(t.sort).length>0){let i=new en(this.tableColumnResolver),s=Ne.buildSimpleQuery(r);r=i.inject(s,t.sort)}if(t.paging){let{page:i=1,pageSize:s}=t.paging;if(s!==void 0){let a=new tn,l={page:i,pageSize:s},u=Ne.buildSimpleQuery(r);r=a.inject(u,l)}}if(t.serialize&&typeof t.serialize=="object"){let i=new Jt,s=Ne.buildSimpleQuery(r);r=i.buildJsonQuery(s,t.serialize)}return r}buildFilteredQuery(e,t){return this.buildQuery(e,{filter:t})}buildSortedQuery(e,t){return this.buildQuery(e,{sort:t})}buildPaginatedQuery(e,t){return this.buildQuery(e,{paging:t})}buildSerializedQuery(e,t){return this.buildQuery(e,{serialize:t})}validateSql(e){try{return A.parse(e),!0}catch(t){throw new Error(`Invalid SQL: ${t instanceof Error?t.message:"Unknown error"}`)}}};var yr=class{static validate(e,t){let n=this.extractStructureFromJsonMapping(e);return this.compareStructures(n,t)}static validateStrict(e,t){let n=this.validate(e,t);if(!n.isValid){let r=["JsonMapping validation failed:",...n.errors].join(`
|
|
60
60
|
`);throw new Error(r)}}static extractStructureFromJsonMapping(e){let t={};return e.rootEntity&&e.rootEntity.columns&&Object.keys(e.rootEntity.columns).forEach(n=>{t[n]="primitive"}),e.nestedEntities&&e.nestedEntities.filter(n=>n.parentId===e.rootEntity.id).forEach(n=>{n.propertyName&&n.columns&&(n.relationshipType==="object"?t[n.propertyName]=this.extractNestedEntityStructure(n,e):n.relationshipType==="array"&&(t[n.propertyName]=[this.extractNestedEntityStructure(n,e)]))}),t}static extractNestedEntityStructure(e,t){let n={};return e.columns&&Object.keys(e.columns).forEach(r=>{n[r]="primitive"}),t.nestedEntities&&t.nestedEntities.filter(r=>r.parentId===e.id).forEach(r=>{r.propertyName&&r.columns&&(r.relationshipType==="object"?n[r.propertyName]=this.extractNestedEntityStructure(r,t):r.relationshipType==="array"&&(n[r.propertyName]=[this.extractNestedEntityStructure(r,t)]))}),n}static compareStructures(e,t,n=""){let r=[],i=[],s=[];if(e==="primitive"&&t==="primitive")return{isValid:!0,errors:[],missingProperties:[],extraProperties:[]};if(Array.isArray(t)&&Array.isArray(e)){if(t.length>0&&e.length>0){let u=this.compareStructures(e[0],t[0],`${n}[]`);r.push(...u.errors),i.push(...u.missingProperties),s.push(...u.extraProperties)}return{isValid:r.length===0,errors:r,missingProperties:i,extraProperties:s}}if(typeof e!="object"||typeof t!="object"||Array.isArray(e)||Array.isArray(t)||e===null||t===null)return{isValid:!0,errors:[],missingProperties:[],extraProperties:[]};let a=e,l=t;return Object.keys(l).forEach(u=>{let c=n?`${n}.${u}`:u;if(!(u in a)){i.push(c),r.push(`Missing property: ${c}`);return}let m=a[u],h=l[u],g=this.compareStructures(m,h,c);r.push(...g.errors),i.push(...g.missingProperties),s.push(...g.extraProperties)}),Object.keys(a).forEach(u=>{let c=n?`${n}.${u}`:u;u in l||s.push(c)}),{isValid:r.length===0,errors:r,missingProperties:i,extraProperties:s}}static validateAgainstSample(e,t){let n=this.extractStructureFromSample(t);return this.validate(e,n)}static validateAgainstSampleStrict(e,t){let n=this.validateAgainstSample(e,t);if(!n.isValid){let r=["JsonMapping validation against sample object failed:",...n.errors].join(`
|
|
61
61
|
`);throw new Error(r)}}static extractStructureFromSample(e){if(e==null)return"primitive";if(Array.isArray(e))return e.length===0?[]:[this.extractStructureFromSample(e[0])];if(typeof e=="object"){let t={};return Object.keys(e).forEach(n=>{t[n]=this.extractStructureFromSample(e[n])}),t}return"primitive"}};var Qt=class{constructor(e){this.schemas=e,this.validateSchemas()}validateSchemas(){let e=Object.keys(this.schemas),t=[];if(Object.entries(this.schemas).forEach(([n,r])=>{Object.entries(r.columns).filter(([s,a])=>a.isPrimaryKey).map(([s,a])=>s).length===0&&t.push(`Table '${n}' has no primary key defined`),r.relationships?.forEach(s=>{e.includes(s.table)||t.push(`Table '${n}' references unknown table '${s.table}' in relationship`)})}),t.length>0)throw new Error(`Schema validation failed:\\n${t.join("\\n")}`)}getTableColumns(e){let t=this.schemas[e];return t?Object.keys(t.columns):[]}createTableColumnResolver(){return e=>this.getTableColumns(e)}createJsonMapping(e){let t=this.schemas[e];if(!t)throw new Error(`Table '${e}' not found in schema registry`);let n={};Object.entries(t.columns).forEach(([i,s])=>{n[i]=s.jsonAlias||s.name});let r=[];return t.relationships?.forEach(i=>{let s=this.schemas[i.table];if(!s)throw new Error(`Related table '${i.table}' not found in schema registry`);let a={};Object.entries(s.columns).forEach(([u,c])=>{a[u]=c.jsonAlias||c.name});let l=i.type;r.push({id:i.propertyName,name:s.displayName||i.table,parentId:e,propertyName:i.propertyName,relationshipType:l,columns:a})}),{rootName:e,rootEntity:{id:e,name:t.displayName||e,columns:n},nestedEntities:r,resultFormat:"single"}}getTableNames(){return Object.keys(this.schemas)}getTable(e){return this.schemas[e]}getPrimaryKey(e){let t=this.schemas[e];if(!t)return;let n=Object.entries(t.columns).find(([r,i])=>i.isPrimaryKey);return n?n[0]:void 0}getForeignKeys(e){let t=this.schemas[e];if(!t)return[];let n=[];return Object.entries(t.columns).forEach(([r,i])=>{i.foreignKey&&n.push({column:r,referencedTable:i.foreignKey.table,referencedColumn:i.foreignKey.column})}),n}};function si(o){return new Qt(o)}function oi(o){return new Qt(o).createTableColumnResolver()}function ai(o,e){return new Qt(o).createJsonMapping(e)}var wr=class{static{this.SQL_COMMANDS=new Set(["select","from","where","and","or","order","by","group","having","limit","offset","as","on","inner","left","right","join","union","insert","update","delete","into","values","set"])}static findLexemeAtPosition(e,t){if(t<0||t>=e.length)return null;let n=this.getAllLexemesWithPosition(e);for(let r of n)if(r.position&&t>=r.position.startPosition&&t<r.position.endPosition)return r;return null}static getAllLexemesWithPosition(e){if(!e?.trim())return[];try{let t=[],n=0;for(;n<e.length&&(n=this.skipWhitespace(e,n),!(n>=e.length));){let r=this.parseNextToken(e,n);r?(t.push(r),n=r.position.endPosition):n++}return t}catch{return[]}}static skipWhitespace(e,t){for(;t<e.length&&/\s/.test(e[t]);)t++;return t}static parseNextToken(e,t){let n=e[t];return n==="'"||n==='"'?this.parseStringLiteral(e,t):/[=<>!+\-*/%().*]/.test(n)?this.parseOperator(e,t):n===","?this.createLexeme(16,",",t,t+1):/[a-zA-Z0-9_]/.test(n)?this.parseWordToken(e,t):null}static parseStringLiteral(e,t){let n=e[t],r=t+1,i=n;for(;r<e.length&&e[r]!==n;)i+=e[r++];return r<e.length&&(i+=e[r++]),this.createLexeme(1,i,t,r)}static parseOperator(e,t){let n=e[t],r=t+1;r<e.length&&/[=<>!]/.test(e[r])&&/[=<>!]/.test(n)&&(n+=e[r++]);let i=this.getOperatorTokenType(n);return this.createLexeme(i,n,t,r)}static parseWordToken(e,t){let n=t,r="";for(;n<e.length&&/[a-zA-Z0-9_]/.test(e[n]);)r+=e[n++];let i=this.getWordTokenType(r,e,n),s=this.shouldLowercase(i)?r.toLowerCase():r;return this.createLexeme(i,s,t,n)}static getOperatorTokenType(e){switch(e){case"(":return 4;case")":return 8;case"*":return 64;default:return 2}}static getWordTokenType(e,t,n){let r=e.toLowerCase();if(this.SQL_COMMANDS.has(r))return 128;let i=this.skipWhitespace(t,n);return i<t.length&&t[i]==="("?2048:64}static shouldLowercase(e){return!!(e&128)||!!(e&2)||!!(e&2048)}static createLexeme(e,t,n,r){return{type:e,value:t,comments:null,position:{startPosition:n,endPosition:r}}}};
|
|
62
62
|
//# sourceMappingURL=index.min.js.map
|