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.
@@ -56,7 +56,7 @@ ${e}`}getCTEName(e){return e.aliasExpression.table.name}};var Bn=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=It.createTable(e),this.addNode(n)),n}getOrCreateCTE(e){let t=`cte_${e}`,n=this.nodes.get(t);return n||(n=It.createCTE(e),this.addNode(n)),n}getOrCreateSubquery(e){let t=`subquery_${e}`,n=this.nodes.get(t);return n||(n=It.createSubquery(e),this.addNode(n)),n}createProcessNode(e,t){let n=new jn(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 Un(e);return this.addNode(t),t}};var Dt=class{constructor(e){this.graph=e}processSource(e,t,n){if(e.datasource instanceof L)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 L){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 L){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 Wt=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 jt=class{constructor(e,t){this.graph=e;this.dataSourceHandler=t}processQueryClauses(e,t,n,r,i){return n}};var Ut=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 wr=class o{constructor(){this.graph=new Mt,this.dataSourceHandler=new Dt(this.graph),this.joinHandler=new Wt(this.graph,this.dataSourceHandler),this.processHandler=new jt(this.graph,this.dataSourceHandler),this.cteHandler=new Ut(this.graph)}generateMermaidFlow(e,t){this.graph=new Mt,this.dataSourceHandler=new Dt(this.graph),this.joinHandler=new Wt(this.graph,this.dataSourceHandler),this.processHandler=new jt(this.graph,this.dataSourceHandler),this.cteHandler=new Ut(this.graph),this.joinHandler.resetJoinCounter();let n=typeof e=="string"?F.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 R)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 R&&i.operator.value===t?(r(i.left),r(i.right)):n.push(i)};return r(e),n}};var Kn=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=F.parse(e));let n=new bt(this.tableColumnResolver,this.options),r=new Ae(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,Q,E,O,N){for(let V=0;V<Q.length;V++){let v=Q[V],I=v.column||w,Pt=O.find($=>E($.name)===E(I));if(!Pt)throw new Error(`Column '${I}' not found in query for AND condition`);let ge=Pt.value;if("="in v&&v["="]!==void 0){let $=`${w}_and_${V}_eq`,A=new T($,v["="]);d.appendWhere(new C(ge,"=",A))}if("min"in v&&v.min!==void 0){let $=`${w}_and_${V}_min`,A=new T($,v.min);d.appendWhere(new C(ge,">=",A))}if("max"in v&&v.max!==void 0){let $=`${w}_and_${V}_max`,A=new T($,v.max);d.appendWhere(new C(ge,"<=",A))}if("like"in v&&v.like!==void 0){let $=`${w}_and_${V}_like`,A=new T($,v.like);d.appendWhere(new C(ge,"like",A))}if("ilike"in v&&v.ilike!==void 0){let $=`${w}_and_${V}_ilike`,A=new T($,v.ilike);d.appendWhere(new C(ge,"ilike",A))}if("in"in v&&v.in!==void 0){let A=v.in.map((q,z)=>new T(`${w}_and_${V}_in_${z}`,q));d.appendWhere(new C(ge,"in",new G(new _(A))))}if("any"in v&&v.any!==void 0){let $=`${w}_and_${V}_any`,A=new T($,v.any);d.appendWhere(new C(ge,"=",new j(null,"any",A,null)))}if("<"in v&&v["<"]!==void 0){let $=`${w}_and_${V}_lt`,A=new T($,v["<"]);d.appendWhere(new C(ge,"<",A))}if(">"in v&&v[">"]!==void 0){let $=`${w}_and_${V}_gt`,A=new T($,v[">"]);d.appendWhere(new C(ge,">",A))}if("!="in v&&v["!="]!==void 0){let $=`${w}_and_${V}_neq`,A=new T($,v["!="]);d.appendWhere(new C(ge,"!=",A))}if("<>"in v&&v["<>"]!==void 0){let $=`${w}_and_${V}_ne`,A=new T($,v["<>"]);d.appendWhere(new C(ge,"<>",A))}if("<="in v&&v["<="]!==void 0){let $=`${w}_and_${V}_le`,A=new T($,v["<="]);d.appendWhere(new C(ge,"<=",A))}if(">="in v&&v[">="]!==void 0){let $=`${w}_and_${V}_ge`,A=new T($,v[">="]);d.appendWhere(new C(ge,">=",A))}}}function m(d,w,Q,E,O,N){let V=[];for(let v=0;v<Q.length;v++){let I=Q[v],Pt=I.column||w,ge=O.find(q=>E(q.name)===E(Pt));if(!ge)throw new Error(`Column '${Pt}' not found in query for OR condition`);let $=ge.value,A=[];if("="in I&&I["="]!==void 0){let q=`${w}_or_${v}_eq`,z=new T(q,I["="]);A.push(new C($,"=",z))}if("min"in I&&I.min!==void 0){let q=`${w}_or_${v}_min`,z=new T(q,I.min);A.push(new C($,">=",z))}if("max"in I&&I.max!==void 0){let q=`${w}_or_${v}_max`,z=new T(q,I.max);A.push(new C($,"<=",z))}if("like"in I&&I.like!==void 0){let q=`${w}_or_${v}_like`,z=new T(q,I.like);A.push(new C($,"like",z))}if("ilike"in I&&I.ilike!==void 0){let q=`${w}_or_${v}_ilike`,z=new T(q,I.ilike);A.push(new C($,"ilike",z))}if("in"in I&&I.in!==void 0){let z=I.in.map((Er,br)=>new T(`${w}_or_${v}_in_${br}`,Er));A.push(new C($,"in",new G(new _(z))))}if("any"in I&&I.any!==void 0){let q=`${w}_or_${v}_any`,z=new T(q,I.any);A.push(new C($,"=",new j(null,"any",z,null)))}if("<"in I&&I["<"]!==void 0){let q=`${w}_or_${v}_lt`,z=new T(q,I["<"]);A.push(new C($,"<",z))}if(">"in I&&I[">"]!==void 0){let q=`${w}_or_${v}_gt`,z=new T(q,I[">"]);A.push(new C($,">",z))}if("!="in I&&I["!="]!==void 0){let q=`${w}_or_${v}_neq`,z=new T(q,I["!="]);A.push(new C($,"!=",z))}if("<>"in I&&I["<>"]!==void 0){let q=`${w}_or_${v}_ne`,z=new T(q,I["<>"]);A.push(new C($,"<>",z))}if("<="in I&&I["<="]!==void 0){let q=`${w}_or_${v}_le`,z=new T(q,I["<="]);A.push(new C($,"<=",z))}if(">="in I&&I[">="]!==void 0){let q=`${w}_or_${v}_ge`,z=new T(q,I[">="]);A.push(new C($,">=",z))}if(A.length>0){let q=A[0];for(let z=1;z<A.length;z++)q=new C(q,"and",A[z]);A.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,Q){Object.keys(d).forEach(E=>{if(!w.includes(E))throw new Error(`Unsupported operator '${E}' for state key '${Q}'`)})}function g(d,w,Q,E){let O=new T(Q,E);d.appendWhere(new C(w,"=",O))}function b(d,w,Q,E){let O=[];if("="in E){let N=new T(Q,E["="]);O.push(new C(w,"=",N))}if("min"in E){let N=new T(Q+"_min",E.min);O.push(new C(w,">=",N))}if("max"in E){let N=new T(Q+"_max",E.max);O.push(new C(w,"<=",N))}if("like"in E){let N=new T(Q+"_like",E.like);O.push(new C(w,"like",N))}if("ilike"in E){let N=new T(Q+"_ilike",E.ilike);O.push(new C(w,"ilike",N))}if("in"in E){let V=E.in.map((v,I)=>new T(`${Q}_in_${I}`,v));O.push(new C(w,"in",new G(new _(V))))}if("any"in E){let N=new T(Q+"_any",E.any);O.push(new C(w,"=",new j(null,"any",N,null)))}if("<"in E){let N=new T(Q+"_lt",E["<"]);O.push(new C(w,"<",N))}if(">"in E){let N=new T(Q+"_gt",E[">"]);O.push(new C(w,">",N))}if("!="in E){let N=new T(Q+"_neq",E["!="]);O.push(new C(w,"!=",N))}if("<>"in E){let N=new T(Q+"_ne",E["<>"]);O.push(new C(w,"<>",N))}if("<="in E){let N=new T(Q+"_le",E["<="]);O.push(new C(w,"<=",N))}if(">="in E){let N=new T(Q+"_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 Q=this.getAllAvailableColumns(d,i).find(E=>s(E.name)===s(g));if(!Q)throw new Error(`Explicit column '${g}' not found in query`);this.isValidatableObject(t)&&h(t,a,e),m(d,Q.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,Q=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,Q=E)}}this.isSimpleValue(t)?l(h,w,Q,t):u(h,w,Q,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 Ae(this.tableColumnResolver).collect(e):e instanceof R?this.collectColumnsFromSelectQuery(e.left):[]}};var _n=class{constructor(e){this.tableColumnResolver=e}static removeOrderBy(e){if(typeof e=="string"&&(e=F.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=F.parse(e)),!(e instanceof y))throw new Error("Complex queries are not supported for sorting");let r=new Ae(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 Ie(m,h,g);i.push(b)}let s=[];e.orderByClause?s=[...e.orderByClause.order,...i]:s=i;let a=s.length>0?new le(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 zn=class{inject(e,t){if(this.validatePaginationOptions(t),typeof e=="string"&&(e=F.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 Le(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=F.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 Nt=class{static extractParameterNames(e){return ot.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 Hn=class{constructor(e={}){this.options={requireAllParameters:!0,...e}}bind(e,t){let n=e,r=Nt.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{Ge.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 gr=class{constructor(e){this.tableColumnResolver=e}buildQuery(e,t={}){let n;try{n=F.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}=Nt.separateFilters(r,t.filter);if(Object.keys(i).length>0&&(r=new Hn({requireAllParameters:!1}).bind(r,i)),Object.keys(s).length>0){let a=new Kn(this.tableColumnResolver),l=Fe.buildSimpleQuery(r);r=a.inject(l,s)}}if(t.sort&&Object.keys(t.sort).length>0){let i=new _n(this.tableColumnResolver),s=Fe.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 zn,l={page:i,pageSize:s},u=Fe.buildSimpleQuery(r);r=a.inject(u,l)}}if(t.serialize&&typeof t.serialize=="object"){let i=new Mn,s=Fe.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 F.parse(e),!0}catch(t){throw new Error(`Invalid SQL: ${t instanceof Error?t.message:"Unknown error"}`)}}};var Sr=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=It.createTable(e),this.addNode(n)),n}getOrCreateCTE(e){let t=`cte_${e}`,n=this.nodes.get(t);return n||(n=It.createCTE(e),this.addNode(n)),n}getOrCreateSubquery(e){let t=`subquery_${e}`,n=this.nodes.get(t);return n||(n=It.createSubquery(e),this.addNode(n)),n}createProcessNode(e,t){let n=new jn(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 Un(e);return this.addNode(t),t}};var Dt=class{constructor(e){this.graph=e}processSource(e,t,n){if(e.datasource instanceof L)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 L){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 L){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 Wt=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 jt=class{constructor(e,t){this.graph=e;this.dataSourceHandler=t}processQueryClauses(e,t,n,r,i){return n}};var Ut=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 wr=class o{constructor(){this.graph=new Mt,this.dataSourceHandler=new Dt(this.graph),this.joinHandler=new Wt(this.graph,this.dataSourceHandler),this.processHandler=new jt(this.graph,this.dataSourceHandler),this.cteHandler=new Ut(this.graph)}generateMermaidFlow(e,t){this.graph=new Mt,this.dataSourceHandler=new Dt(this.graph),this.joinHandler=new Wt(this.graph,this.dataSourceHandler),this.processHandler=new jt(this.graph,this.dataSourceHandler),this.cteHandler=new Ut(this.graph),this.joinHandler.resetJoinCounter();let n=typeof e=="string"?F.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 R)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 R&&i.operator.value===t?(r(i.left),r(i.right)):n.push(i)};return r(e),n}};var Kn=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=F.parse(e));let n=new bt(this.tableColumnResolver,this.options),r=new Ae(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,Q,E,O,N){for(let V=0;V<Q.length;V++){let v=Q[V],I=v.column||w,Pt=O.find($=>E($.name)===E(I));if(!Pt)throw new Error(`Column '${I}' not found in query for AND condition`);let ge=Pt.value;if("="in v&&v["="]!==void 0){let $=`${w}_and_${V}_eq`,A=new T($,v["="]);d.appendWhere(new C(ge,"=",A))}if("min"in v&&v.min!==void 0){let $=`${w}_and_${V}_min`,A=new T($,v.min);d.appendWhere(new C(ge,">=",A))}if("max"in v&&v.max!==void 0){let $=`${w}_and_${V}_max`,A=new T($,v.max);d.appendWhere(new C(ge,"<=",A))}if("like"in v&&v.like!==void 0){let $=`${w}_and_${V}_like`,A=new T($,v.like);d.appendWhere(new C(ge,"like",A))}if("ilike"in v&&v.ilike!==void 0){let $=`${w}_and_${V}_ilike`,A=new T($,v.ilike);d.appendWhere(new C(ge,"ilike",A))}if("in"in v&&v.in!==void 0){let A=v.in.map((q,z)=>new T(`${w}_and_${V}_in_${z}`,q));d.appendWhere(new C(ge,"in",new G(new _(A))))}if("any"in v&&v.any!==void 0){let $=`${w}_and_${V}_any`,A=new T($,v.any);d.appendWhere(new C(ge,"=",new j(null,"any",A,null)))}if("<"in v&&v["<"]!==void 0){let $=`${w}_and_${V}_lt`,A=new T($,v["<"]);d.appendWhere(new C(ge,"<",A))}if(">"in v&&v[">"]!==void 0){let $=`${w}_and_${V}_gt`,A=new T($,v[">"]);d.appendWhere(new C(ge,">",A))}if("!="in v&&v["!="]!==void 0){let $=`${w}_and_${V}_neq`,A=new T($,v["!="]);d.appendWhere(new C(ge,"!=",A))}if("<>"in v&&v["<>"]!==void 0){let $=`${w}_and_${V}_ne`,A=new T($,v["<>"]);d.appendWhere(new C(ge,"<>",A))}if("<="in v&&v["<="]!==void 0){let $=`${w}_and_${V}_le`,A=new T($,v["<="]);d.appendWhere(new C(ge,"<=",A))}if(">="in v&&v[">="]!==void 0){let $=`${w}_and_${V}_ge`,A=new T($,v[">="]);d.appendWhere(new C(ge,">=",A))}}}function m(d,w,Q,E,O,N){let V=[];for(let v=0;v<Q.length;v++){let I=Q[v],Pt=I.column||w,ge=O.find(q=>E(q.name)===E(Pt));if(!ge)throw new Error(`Column '${Pt}' not found in query for OR condition`);let $=ge.value,A=[];if("="in I&&I["="]!==void 0){let q=`${w}_or_${v}_eq`,z=new T(q,I["="]);A.push(new C($,"=",z))}if("min"in I&&I.min!==void 0){let q=`${w}_or_${v}_min`,z=new T(q,I.min);A.push(new C($,">=",z))}if("max"in I&&I.max!==void 0){let q=`${w}_or_${v}_max`,z=new T(q,I.max);A.push(new C($,"<=",z))}if("like"in I&&I.like!==void 0){let q=`${w}_or_${v}_like`,z=new T(q,I.like);A.push(new C($,"like",z))}if("ilike"in I&&I.ilike!==void 0){let q=`${w}_or_${v}_ilike`,z=new T(q,I.ilike);A.push(new C($,"ilike",z))}if("in"in I&&I.in!==void 0){let z=I.in.map((Er,br)=>new T(`${w}_or_${v}_in_${br}`,Er));A.push(new C($,"in",new G(new _(z))))}if("any"in I&&I.any!==void 0){let q=`${w}_or_${v}_any`,z=new T(q,I.any);A.push(new C($,"=",new j(null,"any",z,null)))}if("<"in I&&I["<"]!==void 0){let q=`${w}_or_${v}_lt`,z=new T(q,I["<"]);A.push(new C($,"<",z))}if(">"in I&&I[">"]!==void 0){let q=`${w}_or_${v}_gt`,z=new T(q,I[">"]);A.push(new C($,">",z))}if("!="in I&&I["!="]!==void 0){let q=`${w}_or_${v}_neq`,z=new T(q,I["!="]);A.push(new C($,"!=",z))}if("<>"in I&&I["<>"]!==void 0){let q=`${w}_or_${v}_ne`,z=new T(q,I["<>"]);A.push(new C($,"<>",z))}if("<="in I&&I["<="]!==void 0){let q=`${w}_or_${v}_le`,z=new T(q,I["<="]);A.push(new C($,"<=",z))}if(">="in I&&I[">="]!==void 0){let q=`${w}_or_${v}_ge`,z=new T(q,I[">="]);A.push(new C($,">=",z))}if(A.length>0){let q=A[0];for(let z=1;z<A.length;z++)q=new C(q,"and",A[z]);A.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,Q){Object.keys(d).forEach(E=>{if(!w.includes(E))throw new Error(`Unsupported operator '${E}' for state key '${Q}'`)})}function g(d,w,Q,E){let O=new T(Q,E);d.appendWhere(new C(w,"=",O))}function b(d,w,Q,E){let O=[];if("="in E){let N=new T(Q,E["="]);O.push(new C(w,"=",N))}if("min"in E){let N=new T(Q+"_min",E.min);O.push(new C(w,">=",N))}if("max"in E){let N=new T(Q+"_max",E.max);O.push(new C(w,"<=",N))}if("like"in E){let N=new T(Q+"_like",E.like);O.push(new C(w,"like",N))}if("ilike"in E){let N=new T(Q+"_ilike",E.ilike);O.push(new C(w,"ilike",N))}if("in"in E){let V=E.in.map((v,I)=>new T(`${Q}_in_${I}`,v));O.push(new C(w,"in",new G(new _(V))))}if("any"in E){let N=new T(Q+"_any",E.any);O.push(new C(w,"=",new j(null,"any",N,null)))}if("<"in E){let N=new T(Q+"_lt",E["<"]);O.push(new C(w,"<",N))}if(">"in E){let N=new T(Q+"_gt",E[">"]);O.push(new C(w,">",N))}if("!="in E){let N=new T(Q+"_neq",E["!="]);O.push(new C(w,"!=",N))}if("<>"in E){let N=new T(Q+"_ne",E["<>"]);O.push(new C(w,"<>",N))}if("<="in E){let N=new T(Q+"_le",E["<="]);O.push(new C(w,"<=",N))}if(">="in E){let N=new T(Q+"_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 Q=this.getAllAvailableColumns(d,i).find(E=>s(E.name)===s(g));if(!Q)throw new Error(`Explicit column '${g}' not found in query`);this.isValidatableObject(t)&&h(t,a,e),m(d,Q.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,Q=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,Q=E)}}this.isSimpleValue(t)?l(h,w,Q,t):u(h,w,Q,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 Ae(this.tableColumnResolver).collect(e):e instanceof R?this.collectColumnsFromSelectQuery(e.left):[]}};var _n=class{constructor(e){this.tableColumnResolver=e}static removeOrderBy(e){if(typeof e=="string"&&(e=F.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=F.parse(e)),!(e instanceof y))throw new Error("Complex queries are not supported for sorting");let r=new Ae(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 Ie(m,h,g);i.push(b)}let s=[];e.orderByClause?s=[...e.orderByClause.order,...i]:s=i;let a=s.length>0?new le(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 zn=class{inject(e,t){if(this.validatePaginationOptions(t),typeof e=="string"&&(e=F.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 Le(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=F.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 Nt=class{static extractParameterNames(e){return ot.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 Hn=class{constructor(e={}){this.options={requireAllParameters:!0,...e}}bind(e,t){let n=e,r=Nt.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{Ge.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 gr=class{constructor(e){this.tableColumnResolver=e}buildQuery(e,t={}){let n;try{n=F.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}=Nt.separateFilters(r,t.filter);if(Object.keys(i).length>0&&(r=new Hn({requireAllParameters:!1}).bind(r,i)),Object.keys(s).length>0){let a=new Kn(this.tableColumnResolver),l=Fe.buildSimpleQuery(r);r=a.inject(l,s)}}if(t.sort&&Object.keys(t.sort).length>0){let i=new _n(this.tableColumnResolver),s=Fe.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 zn,l={page:i,pageSize:s},u=Fe.buildSimpleQuery(r);r=a.inject(u,l)}}if(t.serialize&&typeof t.serialize=="object"){let i=new Mn,s=Fe.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 F.parse(e),!0}catch(t){throw new Error(`Invalid SQL: ${t instanceof Error?t.message:"Unknown error"}`)}}};var Sr=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
- `);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 Jt=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 sy(o){return new Jt(o)}function oy(o){return new Jt(o).createTableColumnResolver()}function ay(o,e){return new Jt(o).createJsonMapping(e)}var vr=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}}}};export{fe as ArrayExpression,et as ArrayIndexExpression,Ce as ArrayQueryExpression,Ze as ArraySliceExpression,ye as BetweenExpression,C as BinaryExpression,R as BinarySelectQuery,ee as CTECollector,Rn as CTEComposer,lt as CTEDependencyAnalyzer,gt as CTEDisabler,He as CTENormalizer,Lt as CTENotFoundError,hr as CTEQueryDecomposer,fr as CTERenamer,ie as CaseExpression,be as CaseKeyValuePair,ae as CastExpression,S as ColumnReference,Bn as ColumnReferenceCollector,Fn as CommentEditor,Qt as DuplicateCTEError,Zn as DuplicateDetectionMode,gr as DynamicQueryBuilder,at as Formatter,j as FunctionCall,x as IdentifierString,Se as InlineQuery,Ye as InsertQuery,dr as InsertQueryParser,Et as InvalidCTENameError,Vt as JsonMappingConverter,Sr as JsonSchemaValidator,vr as LexemeCursor,H as LiteralValue,T as ParameterExpression,G as ParenExpression,Mn as PostgresJsonQueryBuilder,Ve as QualifiedName,Fe as QueryBuilder,wr as QueryFlowDiagramGenerator,M as RawString,Qn as SchemaCollector,Jt as SchemaManager,F as SelectQueryParser,Oe as SelectValueCollector,Ae as SelectableColumnCollector,y as SimpleSelectQuery,Ue as SqlFormatter,zn as SqlPaginationInjector,Kn as SqlParamInjector,Ln as SqlSchemaValidator,_n as SqlSortInjector,We as StringSpecifierExpression,Ee as SwitchCaseArgument,Bt as TableSchema,it as TableSourceCollector,D as TokenType,Te as TupleExpression,Wn as TypeTransformationPostProcessor,Hf as TypeTransformers,xe as TypeValue,te as UnaryExpression,bt as UpstreamSelectQueryFinder,xu as VALID_PRESETS,_ as ValueList,he as ValuesQuery,lr as WindowFrameBound,dt as WindowFrameBoundStatic,ht as WindowFrameBoundaryValue,ve as WindowFrameExpression,Je as WindowFrameSpec,ar as WindowFrameType,Tt as WithClauseParser,Dn as convertColumnsToLegacy,tr as convertModelDrivenMapping,Bf as convertToLegacyJsonMapping,ay as createJsonMappingFromSchema,sy as createSchemaManager,oy as createTableColumnResolver,yr as extractTypeProtection,_r as isLegacyFormat,qr as isModelDrivenFormat,Kr as isUnifiedFormat,Ur as processJsonMapping,Cr as toLegacyMapping,zf as transformDatabaseResult,Jr as unifyJsonMapping,Wr as validateModelDrivenMapping};
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 Jt=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 oy(o){return new Jt(o)}function ay(o){return new Jt(o).createTableColumnResolver()}function ly(o,e){return new Jt(o).createJsonMapping(e)}var vr=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}}}};export{fe as ArrayExpression,et as ArrayIndexExpression,Ce as ArrayQueryExpression,Ze as ArraySliceExpression,ye as BetweenExpression,C as BinaryExpression,R as BinarySelectQuery,ee as CTECollector,Rn as CTEComposer,lt as CTEDependencyAnalyzer,gt as CTEDisabler,He as CTENormalizer,Lt as CTENotFoundError,hr as CTEQueryDecomposer,fr as CTERenamer,ie as CaseExpression,be as CaseKeyValuePair,ae as CastExpression,S as ColumnReference,Bn as ColumnReferenceCollector,Fn as CommentEditor,Qt as DuplicateCTEError,Zn as DuplicateDetectionMode,gr as DynamicQueryBuilder,at as Formatter,j as FunctionCall,x as IdentifierString,Se as InlineQuery,Ye as InsertQuery,dr as InsertQueryParser,Et as InvalidCTENameError,Vt as JsonMappingConverter,Sr as JsonSchemaValidator,vr as LexemeCursor,H as LiteralValue,T as ParameterExpression,G as ParenExpression,Mn as PostgresJsonQueryBuilder,Ve as QualifiedName,Fe as QueryBuilder,wr as QueryFlowDiagramGenerator,M as RawString,Qn as SchemaCollector,Jt as SchemaManager,F as SelectQueryParser,Oe as SelectValueCollector,Ae as SelectableColumnCollector,y as SimpleSelectQuery,Ue as SqlFormatter,zn as SqlPaginationInjector,Kn as SqlParamInjector,Ln as SqlSchemaValidator,_n as SqlSortInjector,We as StringSpecifierExpression,Ee as SwitchCaseArgument,Bt as TableSchema,it as TableSourceCollector,D as TokenType,Te as TupleExpression,Wn as TypeTransformationPostProcessor,Hf as TypeTransformers,xe as TypeValue,te as UnaryExpression,bt as UpstreamSelectQueryFinder,xu as VALID_PRESETS,_ as ValueList,he as ValuesQuery,lr as WindowFrameBound,dt as WindowFrameBoundStatic,ht as WindowFrameBoundaryValue,ve as WindowFrameExpression,Je as WindowFrameSpec,ar as WindowFrameType,Tt as WithClauseParser,Dn as convertColumnsToLegacy,tr as convertModelDrivenMapping,Bf as convertToLegacyJsonMapping,ly as createJsonMappingFromSchema,oy as createSchemaManager,ay as createTableColumnResolver,yr as extractTypeProtection,_r as isLegacyFormat,qr as isModelDrivenFormat,Kr as isUnifiedFormat,Ur as processJsonMapping,Cr as toLegacyMapping,zf as transformDatabaseResult,Jr as unifyJsonMapping,Wr as validateModelDrivenMapping};
62
62
  //# sourceMappingURL=index.min.js.map