semanticdb-v2 2.0.0-alpha.1 → 2.0.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/README.md +24 -17
  2. package/dist/cache/redis-query-cache.js +1 -1
  3. package/dist/calendar/constants.d.ts +2 -2
  4. package/dist/compatibility/index.d.ts +1 -1
  5. package/dist/compatibility/logicform.d.ts +1 -7
  6. package/dist/compiler/compile-cte.d.ts +17 -2
  7. package/dist/compiler/index.d.ts +2 -1
  8. package/dist/compiler/shorten-sql.d.ts +1 -1
  9. package/dist/errors.d.ts +2 -0
  10. package/dist/executor/fetch-entities.d.ts +2 -1
  11. package/dist/executor/row-identity.d.ts +2 -1
  12. package/dist/executor/types.d.ts +14 -11
  13. package/dist/index.d.ts +5 -7
  14. package/dist/logicform-types.d.ts +11 -12
  15. package/dist/normalizer/core.d.ts +2 -2
  16. package/dist/normalizer/property-resolve.d.ts +5 -0
  17. package/dist/operators/builtins/constant.d.ts +2 -0
  18. package/dist/operators/builtins/period-value.d.ts +2 -0
  19. package/dist/operators/builtins/scalar-extremum.d.ts +3 -0
  20. package/dist/operators/index.d.ts +1 -1
  21. package/dist/operators/types.d.ts +25 -21
  22. package/dist/physical/clickhouse-provider.d.ts +1 -0
  23. package/dist/physical/mysql-protocol-provider.d.ts +2 -0
  24. package/dist/physical/oracle-provider.d.ts +1 -0
  25. package/dist/physical/postgresql-provider.d.ts +1 -0
  26. package/dist/physical/provider.d.ts +2 -0
  27. package/dist/physical/snowflake-provider.d.ts +1 -0
  28. package/dist/planner/semantics/observation/operator-policy.d.ts +1 -1
  29. package/dist/planner/semantics/observation/types.d.ts +1 -1
  30. package/dist/planner/types.d.ts +10 -2
  31. package/dist/plugins/hierarchy/types.d.ts +3 -2
  32. package/dist/schema/entity-identity.d.ts +1 -1
  33. package/dist/schema-mappings/index.d.ts +3 -1
  34. package/dist/schema-mappings/types.d.ts +9 -8
  35. package/dist/schema-mappings/yiask.d.ts +22 -0
  36. package/dist/semantic-types/index.d.ts +1 -1
  37. package/dist/semantic-types/types.d.ts +14 -2
  38. package/dist/semanticdb.js +3 -0
  39. package/package.json +4 -3
  40. package/dist/cache/expiry.js +0 -1
  41. package/dist/cache/identity.js +0 -1
  42. package/dist/cache/serialization.js +0 -1
  43. package/dist/calendar/constants.js +0 -1
  44. package/dist/calendar/provider-relation-store.js +0 -1
  45. package/dist/calendar/resolver.js +0 -1
  46. package/dist/calendar/system-schemas.js +0 -1
  47. package/dist/compatibility/logicform.js +0 -1
  48. package/dist/compiler/compile-cte.js +0 -1
  49. package/dist/compiler/compile-plan.js +0 -1
  50. package/dist/compiler/shorten-sql.js +0 -2
  51. package/dist/custom-functions/custom-functions.d.ts +0 -6
  52. package/dist/custom-functions/custom-functions.js +0 -1
  53. package/dist/custom-functions/index.d.ts +0 -3
  54. package/dist/custom-functions/operator-adapter.d.ts +0 -12
  55. package/dist/custom-functions/operator-adapter.js +0 -1
  56. package/dist/custom-functions/types.d.ts +0 -62
  57. package/dist/errors.js +0 -1
  58. package/dist/executor/compatibility.js +0 -1
  59. package/dist/executor/components.js +0 -1
  60. package/dist/executor/connection-registry.js +0 -1
  61. package/dist/executor/evaluate.js +0 -1
  62. package/dist/executor/execute-query.js +0 -1
  63. package/dist/executor/execute.js +0 -1
  64. package/dist/executor/fetch-entities.js +0 -1
  65. package/dist/executor/result-hydrator/entity-loader.js +0 -1
  66. package/dist/executor/result-hydrator/format-values.js +0 -1
  67. package/dist/executor/result-hydrator/hydrate-result.js +0 -1
  68. package/dist/executor/result-hydrator/missing-entity.js +0 -1
  69. package/dist/executor/result-hydrator/populate-entities.js +0 -1
  70. package/dist/executor/row-identity.js +0 -1
  71. package/dist/index.js +0 -1
  72. package/dist/logicform-types.js +0 -1
  73. package/dist/normalizer/core.js +0 -1
  74. package/dist/normalizer/default-pred-name.js +0 -1
  75. package/dist/normalizer/entity-id.js +0 -1
  76. package/dist/normalizer/groupby.js +0 -1
  77. package/dist/normalizer/normalize-logicform.js +0 -1
  78. package/dist/normalizer/pagination.js +0 -1
  79. package/dist/normalizer/pred-query-name.js +0 -1
  80. package/dist/normalizer/preds.js +0 -1
  81. package/dist/normalizer/query.js +0 -1
  82. package/dist/normalizer/version.js +0 -1
  83. package/dist/operators/builtins/abs.js +0 -1
  84. package/dist/operators/builtins/accumulate.js +0 -1
  85. package/dist/operators/builtins/add.js +0 -1
  86. package/dist/operators/builtins/arithmetic.js +0 -1
  87. package/dist/operators/builtins/average-per-period.js +0 -1
  88. package/dist/operators/builtins/avg.js +0 -1
  89. package/dist/operators/builtins/case.js +0 -1
  90. package/dist/operators/builtins/concat.js +0 -1
  91. package/dist/operators/builtins/count-distinct.js +0 -1
  92. package/dist/operators/builtins/count.js +0 -1
  93. package/dist/operators/builtins/date-bucket.js +0 -1
  94. package/dist/operators/builtins/divide.js +0 -1
  95. package/dist/operators/builtins/index.js +0 -1
  96. package/dist/operators/builtins/max.js +0 -1
  97. package/dist/operators/builtins/min.js +0 -1
  98. package/dist/operators/builtins/multiply.js +0 -1
  99. package/dist/operators/builtins/newly.js +0 -1
  100. package/dist/operators/builtins/period-boundary.js +0 -1
  101. package/dist/operators/builtins/period-difference.js +0 -1
  102. package/dist/operators/builtins/period-growth.js +0 -1
  103. package/dist/operators/builtins/period-name.js +0 -1
  104. package/dist/operators/builtins/period-shift.js +0 -1
  105. package/dist/operators/builtins/rank.js +0 -1
  106. package/dist/operators/builtins/row-number.js +0 -1
  107. package/dist/operators/builtins/share-of-total.js +0 -1
  108. package/dist/operators/builtins/sql.js +0 -1
  109. package/dist/operators/builtins/substring.js +0 -1
  110. package/dist/operators/builtins/subtract.js +0 -1
  111. package/dist/operators/builtins/sum.js +0 -1
  112. package/dist/operators/builtins/time-range.js +0 -1
  113. package/dist/operators/groupby.js +0 -1
  114. package/dist/operators/index.js +0 -1
  115. package/dist/operators/registry.js +0 -1
  116. package/dist/operators/sql-expression.js +0 -1
  117. package/dist/permissions/permissions.js +0 -1
  118. package/dist/physical/clickhouse-provider.js +0 -1
  119. package/dist/physical/connection.js +0 -1
  120. package/dist/physical/display-query.js +0 -1
  121. package/dist/physical/doris-provider.js +0 -1
  122. package/dist/physical/mysql-compatible-sql.js +0 -1
  123. package/dist/physical/mysql-protocol-provider.js +0 -1
  124. package/dist/physical/mysql-provider.js +0 -1
  125. package/dist/physical/oracle-provider.js +0 -1
  126. package/dist/physical/postgresql-provider.js +0 -1
  127. package/dist/physical/snowflake-provider.js +0 -1
  128. package/dist/physical/starrocks-provider.js +0 -1
  129. package/dist/planner/build-lineage.js +0 -1
  130. package/dist/planner/create-logical-plan.js +0 -1
  131. package/dist/planner/select-schema-mapping.js +0 -1
  132. package/dist/planner/semantics/lifecycle/classification.js +0 -1
  133. package/dist/planner/semantics/lifecycle/query-policy.js +0 -1
  134. package/dist/planner/semantics/lifecycle/rule.js +0 -1
  135. package/dist/planner/semantics/observation/classification.js +0 -1
  136. package/dist/planner/semantics/observation/operator-policy.js +0 -1
  137. package/dist/planner/semantics/observation/rule.js +0 -1
  138. package/dist/planner/semantics/registry-defaults.js +0 -1
  139. package/dist/planner/semantics/registry.js +0 -1
  140. package/dist/planner/types.js +0 -1
  141. package/dist/plugins/hierarchy/compatibility.js +0 -1
  142. package/dist/plugins/hierarchy/entity-identity.js +0 -1
  143. package/dist/plugins/hierarchy/index.js +0 -1
  144. package/dist/plugins/hierarchy/operator.js +0 -1
  145. package/dist/plugins/hierarchy/resolve-schema.js +0 -1
  146. package/dist/plugins/index.js +0 -1
  147. package/dist/schema/entity-identity.js +0 -1
  148. package/dist/schema/resolve-property-path.js +0 -1
  149. package/dist/schema/schema-registry.js +0 -1
  150. package/dist/schema-mappings/freshness.js +0 -1
  151. package/dist/schema-mappings/registry.js +0 -1
  152. package/dist/semantic-types/builtins/boolean.js +0 -1
  153. package/dist/semantic-types/builtins/category.js +0 -1
  154. package/dist/semantic-types/builtins/currency.js +0 -1
  155. package/dist/semantic-types/builtins/date.js +0 -1
  156. package/dist/semantic-types/builtins/duration.js +0 -1
  157. package/dist/semantic-types/builtins/end-date.js +0 -1
  158. package/dist/semantic-types/builtins/entity.js +0 -1
  159. package/dist/semantic-types/builtins/file.js +0 -1
  160. package/dist/semantic-types/builtins/human-name.js +0 -1
  161. package/dist/semantic-types/builtins/id.js +0 -1
  162. package/dist/semantic-types/builtins/image.js +0 -1
  163. package/dist/semantic-types/builtins/index.js +0 -1
  164. package/dist/semantic-types/builtins/int.js +0 -1
  165. package/dist/semantic-types/builtins/name.js +0 -1
  166. package/dist/semantic-types/builtins/number.js +0 -1
  167. package/dist/semantic-types/builtins/object.js +0 -1
  168. package/dist/semantic-types/builtins/order.js +0 -1
  169. package/dist/semantic-types/builtins/percentage.js +0 -1
  170. package/dist/semantic-types/builtins/start-date.js +0 -1
  171. package/dist/semantic-types/builtins/string.js +0 -1
  172. package/dist/semantic-types/builtins/timestamp.js +0 -1
  173. package/dist/semantic-types/index.js +0 -1
  174. package/dist/semantic-types/primal-types/date.js +0 -1
  175. package/dist/semantic-types/primal-types/index.js +0 -1
  176. package/dist/semantic-types/registry.js +0 -1
  177. package/dist/semantic-types/resolve-schema.js +0 -1
  178. package/dist/semantic-types/validate-resolved-schema.js +0 -1
  179. package/dist/utils/clone.js +0 -1
  180. /package/dist/operators/builtins/{period-boundary.d.ts → period-boundary-expression.d.ts} +0 -0
@@ -1 +0,0 @@
1
- const n={name:"$rank",defaultName:({operandName:t,locale:r})=>r.toLowerCase().startsWith("en")?`${t} rank`:`${t}\u6392\u540D`,kind:"window",windowFunction:"rank",getOutputProperty({name:t}){return{name:t,type:"int",primal_type:"number",isArray:!1}}};export{n as rankOperator};
@@ -1 +0,0 @@
1
- const e={name:"$rowNumber",defaultName:({locale:r})=>r.toLowerCase().startsWith("en")?"Row number":"\u884C\u53F7",kind:"window",windowFunction:"rowNumber",getOutputProperty({name:r}){return{name:r,type:"int",primal_type:"number",isArray:!1}}};export{e as rowNumberOperator};
@@ -1 +0,0 @@
1
- import{SemanticDBError as a}from"../../errors.js";import{clone as f}from"../../utils/clone.js";import{combineQueries as h,collectPredQueries as T}from"./period-shift.js";import{groupbyOutputName as _}from"../groupby.js";const l=t=>{const e=f(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},m=t=>{const e=f(t);return delete e.query,e.pred&&typeof e.pred=="object"&&(e.pred=m(e.pred)),e.components&&(e.components=e.components.map(m)),e},g={name:"$shareOfTotal",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} share of total`:`${t}\u5360\u6BD4`,kind:"component",createComponent({logicform:t,pred:e}){if(!e.pred||typeof e.pred!="object")throw new a("INVALID_SHARE_OF_TOTAL_INPUT","$shareOfTotal pred must be a nested metric");const r=e.args?.dimension;if(r!==void 0&&typeof r!="string")throw new a("INVALID_SHARE_OF_TOTAL_ARGS","$shareOfTotal args.dimension must be a groupby pred or output name");const n=t.groupby??[],p=r===void 0?n.length-1:n.findIndex(o=>typeof o.pred=="string"&&o.pred===r||_(o)===r);if(r!==void 0&&p<0)throw new a("SHARE_OF_TOTAL_DIMENSION_NOT_FOUND",`$shareOfTotal dimension is not grouped: ${r}`);const d=n.filter((o,O)=>O!==p),y=d.map(_),u=m(e.pred),s=l(t);s.preds=[{...u,name:"__share_numerator__"}];const c=h([t.query,...T(e)]);c&&(s.query=c);const i=l(t);return i.groupby=d,i.preds=[{...u,name:"__share_denominator__"}],{kind:"cte",components:[{name:"numerator",component:{kind:"query",logicform:s}},{name:"denominator",component:{kind:"query",logicform:i},joinKeys:y}],toSQL:({values:o})=>`${o.numerator} / NULLIF(${o.denominator}, 0)`}},getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}};export{g as shareOfTotalOperator};
@@ -1 +0,0 @@
1
- import{SemanticDBError as s}from"../../errors.js";import{bindTrustedSqlExpression as a}from"../sql-expression.js";const i=new Set(["boolean","date","number","object","string"]),p=r=>{if(r===void 0)return[];if(!Array.isArray(r))throw new s("INVALID_SQL_ARGS","$sql args.parameters must be an array");return r},l=(r,e)=>{const t=e.type,n=e.primal_type;if(typeof t!="string"||t.length===0||!i.has(n))throw new s("INVALID_SQL_OUTPUT","$sql requires args.type and a valid args.primal_type");if(e.isArray!==void 0&&typeof e.isArray!="boolean")throw new s("INVALID_SQL_OUTPUT","$sql args.isArray must be boolean");if(e.ref!==void 0&&typeof e.ref!="string")throw new s("INVALID_SQL_OUTPUT","$sql args.ref must be a Schema id");return{name:r,type:t,primal_type:n,isArray:e.isArray===!0,...typeof e.ref=="string"?{ref:e.ref}:{}}},f={name:"$sql",defaultName:({locale:r})=>r.toLowerCase().startsWith("en")?"Calculated value":"\u8BA1\u7B97\u503C",kind:"scalar",requiresProperty:!1,toSQL({args:r,expression:e,expressions:t,sql:n}){if(e||t&&t.length>0)throw new s("INVALID_SQL_INPUT","$sql does not accept pred or components; put the expression in args.sql");return a(r.sql,p(r.parameters),o=>n.value(o))},getOutputProperty({name:r,args:e,inputProperty:t,componentProperties:n}){if(t||n&&n.length>0)throw new s("INVALID_SQL_INPUT","$sql does not accept pred or components; put the expression in args.sql");return l(r,e)}};export{f as sqlOperator};
@@ -1 +0,0 @@
1
- import{SemanticDBError as n}from"../../errors.js";const u={name:"$substring",defaultName:({operandName:r,locale:t})=>t.toLowerCase().startsWith("en")?`${r} substring`:`${r}\u5B50\u4E32`,kind:"scalar",toSQL({expression:r,args:t,sql:i}){if(!r)throw new n("PRED_PROPERTY_REQUIRED","$substring requires a pred");const{start:e,length:s}=t;if(!Number.isInteger(e)||Number(e)<0||!Number.isInteger(s)||Number(s)<1)throw new n("INVALID_SUBSTRING_ARGS","$substring requires a non-negative integer start and a positive integer length");return i.substring(r,Number(e)+1,Number(s))},getOutputProperty({name:r}){return{name:r,type:"string",primal_type:"string",isArray:!1}}};export{u as substringOperator};
@@ -1 +0,0 @@
1
- import{numericResult as s,requireExpressions as u}from"./arithmetic.js";const i={name:"$subtract",defaultName:({operandName:t,componentNames:r,locale:e})=>e.toLowerCase().startsWith("en")?r.length>=2?`${r[0]} minus ${r[1]}`:`${t} difference`:r.length>=2?`${r[0]}\u51CF\u53BB${r[1]}`:`${t}\u5DEE\u503C`,kind:"scalar",requiresProperty:!1,toSQL(t){const[r,e]=u("$subtract",t,2);return`(${r} - ${e})`},getOutputProperty({name:t,componentProperties:r}){const e=r?.[0];return e?{...e,name:t,isArray:!1}:s(t)}};export{i as subtractOperator};
@@ -1 +0,0 @@
1
- const s={name:"$sum",defaultName:({operandName:r,locale:t})=>t.toLowerCase().startsWith("en")?`Total ${r}`:`${r}\u5408\u8BA1`,kind:"aggregate",toSQL(r){const{column:t,sql:e}=r;if(!t)throw new Error("$sum requires a column");return e.aggregateFunction("sum",t)},getOutputProperty({name:r,property:t,inputProperty:e}){const o=t??e;if(!o)throw new Error("$sum requires a property");return{name:r,type:o.type,primal_type:o.primal_type,isArray:!1}}};export{s as sumOperator};
@@ -1 +0,0 @@
1
- import{SemanticDBError as y}from"../../errors.js";import{resolvePropertyPath as R}from"../../schema/resolve-property-path.js";import{combineQueries as U,collectPredQueries as I}from"./period-shift.js";const _=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),h=t=>typeof t=="string"||typeof t=="number"||t instanceof Date,T=(t,e)=>{const r=t.properties.find(({type:s})=>s==="timestamp");if(!r)throw new y("TIMESTAMP_PROPERTY_REQUIRED",`${e} requires a timestamp property in the Schema`);return r},w=(t,e)=>{if(h(t)){e.start??=t,e.end??=t;return}if(!_(t))return;const r=t.$eq;h(r)&&(e.start??=r,e.end??=r);const s=t.$gte??t.$gt,i=t.$lte??t.$lt;h(s)&&(e.start??=s),h(i)&&(e.end??=i);for(const o of["$and","$or"]){const a=t[o];if(Array.isArray(a))for(const u of a)w(u,e)}},A=(t,e,r,s)=>{const i=T(e,s),o=new Set,a={},u=(E,c)=>{for(const[n,f]of Object.entries(E)){if((n==="$and"||n==="$or")&&Array.isArray(f)){for(const m of f)u(m,c||n==="$or");continue}if(n.startsWith("$"))continue;const p=R(e,n,r);if(p.property.type==="timestamp"){if(c)throw new y("AMBIGUOUS_TIME_QUERY",`${s} does not support timestamp conditions inside $or`);o.add(p.canonicalName),w(f,a)}}};if(u(t,!1),o.size!==1)throw new y(o.size===0?"TIME_QUERY_REQUIRED":"AMBIGUOUS_TIME_QUERY",`${s} requires a concrete condition on the Schema timestamp property`);const $=[...o][0];if(!$||$!==i.name)throw new y("AMBIGUOUS_TIME_QUERY",`${s} requires the Schema timestamp property: ${i.name}`);const l=E=>{const c=[];for(const[n,f]of Object.entries(E)){if((n==="$and"||n==="$or")&&Array.isArray(f)){const p=f.map(m=>l(m)).filter(m=>m!==void 0);p.length>0&&c.push([n,p]);continue}!n.startsWith("$")&&R(e,n,r).property.type==="timestamp"||c.push([n,f])}return c.length>0?Object.fromEntries(c):void 0},d=l(t);return{property:i,propertyName:$,...a.start!==void 0?{start:a.start}:{},...a.end!==void 0?{end:a.end}:{},...d?{queryWithoutTime:d}:{}}},M=(t,e,r,s,i)=>{const o=U([t,...I(e)]);if(!o)throw new y("TIME_QUERY_REQUIRED",`${i} requires a timestamp query`);return A(o,r,s,i)},Q=(t,e,r)=>U([t,{[e]:r}]);export{T as requireTimestampProperty,M as resolvePredTimeRange,A as resolveTimeRange,Q as withTimeCondition};
@@ -1 +0,0 @@
1
- import{SemanticDBError as r}from"../errors.js";const t=e=>{if(e.name)return e.name;throw new r("MISSING_PRED_NAME","A normalized groupby PredItem must have a name")},n=e=>typeof e.pred=="string"?e.pred:void 0;export{t as groupbyOutputName,n as groupbyPropertyReference};
@@ -1 +0,0 @@
1
- import{builtinOperators as t}from"./builtins/index.js";import{builtinPlugins as o,resolvePlugins as a}from"../plugins/index.js";import{OperatorRegistry as e}from"./registry.js";const p=Object.freeze([...t,...o.flatMap(({operators:r})=>r??[])]),s=(r=[])=>new e([...t,...a(r).flatMap(({operators:i})=>i??[])]);export{e as OperatorRegistry,p as builtinOperators,s as createOperatorRegistry};
@@ -1 +0,0 @@
1
- import{SemanticDBError as r}from"../errors.js";class n{#e=new Map;constructor(e=[]){for(const t of e)this.register(t)}register(e){if(!e.name)throw new r("INVALID_OPERATOR","Operator name must not be empty");if(typeof e.defaultName!="function")throw new r("INVALID_OPERATOR",`Operator must implement defaultName: ${e.name}`);if(this.#e.has(e.name))throw new r("OPERATOR_ALREADY_REGISTERED",`Operator is already registered: ${e.name}`,{operator:e.name});const t=e;if(!(t.kind==="scalar"&&(typeof t.toSQL=="function"||typeof t.evaluate=="function")||t.kind==="aggregate"&&typeof t.toSQL=="function"||t.kind==="component"&&typeof t.createComponent=="function"||t.kind==="window"&&typeof t.windowFunction=="string"||t.kind==="logical"&&typeof t.planExpression=="function"))throw new r("INVALID_OPERATOR",`Operator kind and implementation do not match: ${e.name}`);return this.#e.set(e.name,e),this}get(e){const t=this.#e.get(e);if(!t)throw new r("OPERATOR_NOT_FOUND",`Operator is not registered: ${e}`,{operator:e});return t}requiresPerPeriodEvaluation(e,t){return this.get(e).requiresPerPeriodEvaluation?.(t)??!1}has(e){return this.#e.has(e)}definitions(){return[...this.#e.values()]}}export{n as OperatorRegistry};
@@ -1 +0,0 @@
1
- import{SemanticDBError as a}from"../errors.js";const f=(o,s,c,i="$sql")=>{if(typeof o!="string"||o.trim().length===0)throw new a("INVALID_SQL_ARGS",`${i} requires a non-empty args.sql expression`);let r="",l=0,n;for(let t=0;t<o.length;t+=1){const e=o[t];if(!e)continue;if(n){r+=e,e===n&&(o[t+1]===n?(r+=n,t+=1):n=void 0);continue}if(e==="'"||e==='"'||e==="`"){n=e,r+=e;continue}const S=o.slice(t,t+2);if(e===";"||S==="--"||S==="/*")throw new a("INVALID_SQL_EXPRESSION",`${i} accepts one expression and does not allow statements or SQL comments`);if(e==="?"){if(l>=s.length)throw new a("INVALID_SQL_PARAMETERS",`${i} contains more placeholders than args.parameters values`);r+=c(s[l]),l+=1;continue}r+=e}if(n)throw new a("INVALID_SQL_EXPRESSION",`${i} contains an unterminated quote`);if(l!==s.length)throw new a("INVALID_SQL_PARAMETERS",`${i} args.parameters contains more values than SQL placeholders`);return r};export{f as bindTrustedSqlExpression};
@@ -1 +0,0 @@
1
- import{SemanticDBError as A}from"../errors.js";import{isLogicform as D}from"../logicform-types.js";import{resolvePropertyPath as _}from"../schema/resolve-property-path.js";import{isConcreteEntityId as L,resolveEntityFilterProperty as C}from"../schema/entity-identity.js";import{clone as E}from"../utils/clone.js";const q=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),u=(t,e)=>{if(t){if(!q(t,e))throw new A("TABLE_PERMISSION_DENIED",`Schema is not included in the table permissions: ${e}`,{schemaId:e});return t[e]}},M=(t,e,r)=>{const n=u(t,e)?.columnPermissions?.whitelist;return!n||n.includes(r.name)||n.includes(r.id)},p=(t,e,r)=>{if(!M(t,e.id,r))throw new A("COLUMN_PERMISSION_DENIED",`Property is not included in the column permissions: ${e.id}.${r.name}`,{schemaId:e.id,property:r.name,propertyId:r.id})},Q=(t,e,r,n)=>{const f=_(e,t,n);for(const o of f.relations)u(r,o.targetSchema.id),p(r,o.sourceSchema,o.property);p(r,f.schema,f.property)},U=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.schema=="string"&&typeof t.query=="object"&&t.query!==null&&!Array.isArray(t.query),F=(t,e,r,n)=>{if(typeof t!="object"||t===null||Array.isArray(t)||!q(t,"$recursive"))return;const f=t.$recursive,o=typeof f=="object"&&f!==null&&!Array.isArray(f)?f:{},s=typeof o.schema=="string"?o.schema:e.property.ref??e.schema.id,c=n(s);if(u(r,s)?.rowPermissions!==void 0)throw new A("RECURSIVE_ROW_PERMISSION_UNSUPPORTED",`$recursive cannot safely apply row permissions for Schema ${s}`,{schemaId:s});const i=o.idProperty??o.id_property,w=i===void 0?c.properties.find(({type:d})=>d==="ID"):c.properties.find(({id:d,name:b})=>d===i||b===i),a=o.parentProperty??o.parent_property??c.parentProperty??"pid",P=c.properties.find(({id:d,name:b})=>d===a||b===a);w&&p(r,c,w),P&&p(r,c,P)},N=(t,e,r,n)=>{if(D(t)){O(t,e,r,n);return}if(Array.isArray(t)){for(const f of t)N(f,e,r,n);return}if(!(typeof t!="object"||t===null||t instanceof Date))for(const f of Object.values(t))N(f,e,r,n)},m=(t,e,r,n,f)=>{if(t)for(const[o,s]of Object.entries(t)){if(o==="$and"||o==="$or"){if(Array.isArray(s))for(const y of s)m(y,e,r,n,f);continue}const c=_(e,o,n);if(Q(o,e,r,n),F(s,c,r,n),U(s)){if(c.property.ref!==s.schema)continue;const y=n(s.schema);u(r,y.id),L(s.entity_id)&&p(r,y,C(y,f)),m(s.query,y,r,n,f);continue}N(s,r,n,f)}},j=(t,e,r,n,f)=>{const o=t.schema?n(t.schema):e;t.schema&&u(r,t.schema),typeof t.pred=="string"?Q(t.pred,o,r,n):t.pred&&j(t.pred,o,r,n,f);for(const s of t.components??[])j(s,o,r,n,f);m(t.query,o,r,n,f)},O=(t,e,r,n=[])=>{if(t.logicforms){for(const o of t.logicforms)O(o,e,r,n);return}if(!t.schema){if(t.from){O(t.from,e,r,n);return}throw new A("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema")}const f=r(t.schema);if(u(e,f.id),L(t.entity_id)&&p(e,f,C(f,n)),t.from){O(t.from,e,r,n);return}m(t.query,f,e,r,n);for(const o of t.preds??[])j(o,f,e,r,n);for(const o of t.groupby??[])j(o,f,e,r,n)},R=(t,e)=>{if(Array.isArray(t))return t.map(f=>R(f,e));if(typeof t!="object"||t===null||t instanceof Date)return t;const r=Object.entries(t).map(([f,o])=>[f,R(o,e)]),n=Object.fromEntries(r);return U(t)&&!q(t,"version")&&(n.version=e),n},T=(t,e,r)=>{const n=[],f=c=>{n.push(_(e,c,r))},o=c=>{if(c)for(const[y,i]of Object.entries(c))if((y==="$and"||y==="$or")&&Array.isArray(i))for(const w of i)o(w);else y.startsWith("$")||f(y)},s=c=>{typeof c.pred=="string"?f(c.pred):c.pred&&s(c.pred);for(const y of c.components??[])s(y);o(c.query)};o(t.query);for(const c of t.preds??[])s(c);for(const c of t.groupby??[])s(c);return n},V=(t,e,r)=>{if(!t.schema)return[];const n=r(t.schema),f=new Set,o=[];for(const s of T(t,n,r)){if(s.relations.length===0)continue;let c=-1;if(s.relations.forEach(({targetSchema:a},P)=>{e[a.id]?.rowPermissions!==void 0&&(c=P)}),c<0)continue;const y=s.relations.slice(0,c+1),i=y.map(({property:a})=>a.name).join("_");if(f.has(i))continue;f.add(i);let w={};for(const a of[...y].reverse())w={[a.property.name]:{schema:a.targetSchema.id,query:w}};o.push(w)}return o},I=(t,e,r,n,f,o)=>D(t)?h(t,e,r,n,f,o):Array.isArray(t)?t.map(s=>I(s,e,r,n,f,o)):typeof t!="object"||t===null||t instanceof Date?t:Object.fromEntries(Object.entries(t).map(([s,c])=>[s,I(c,e,r,n,f,o)])),$=(t,e,r,n,f,o)=>({...t,...t.query?{query:I(t.query,e,r,n,f,o)}:{},...t.pred&&typeof t.pred=="object"?{pred:$(t.pred,e,r,n,f,o)}:{},...t.components?{components:t.components.map(s=>$(s,e,r,n,f,o))}:{}}),h=(t,e,r,n=!0,f=new Set,o=[])=>{if(!e)return E(t);if(t.logicforms){const d=E(t);return d.logicforms=t.logicforms.map(b=>h(b,e,r,n,new Set,o)),d}if(!t.schema){const d=E(t);return d.from&&(d.from=h(d.from,e,r,n,new Set,o)),d}n&&O(t,e,r,o);const s=u(e,t.schema),c=f.has(t.schema),y=new Set(f).add(t.schema),i=E(t);i.query&&(i.query=I(i.query,e,r,n,new Set,o)),i.preds&&(i.preds=i.preds.map(d=>$(d,e,r,n,new Set,o))),i.from&&(i.from=h(i.from,e,r,n,new Set,o));const w=c||t.from?void 0:s?.rowPermissions,a=(t.from?[]:V(t,e,r)).map(d=>I(R(d,t.version),e,r,!1,y,o));w&&a.push(I(R(E(w),t.version),e,r,!1,y,o));const P=[i.query,...a].filter(d=>d!==void 0&&Object.keys(d).length>0);return P.length===1?i.query=P[0]:P.length>1?i.query={$and:P}:delete i.query,i},k=(t,e)=>{if(t)for(const[r,n]of Object.entries(t)){const f=e(r),o=n.columnPermissions?.whitelist;if(o&&(!Array.isArray(o)||o.some(s=>typeof s!="string")))throw new A("INVALID_COLUMN_PERMISSIONS",`Column permissions whitelist must be an array of strings: ${r}`,{schemaId:r});for(const s of o??[])if(!f.properties.some(({id:c,name:y})=>c===s||y===s))throw new A("INVALID_COLUMN_PERMISSION",`Column permission property not found: ${r}.${s}`,{schemaId:r,property:s})}};export{h as applyPermissions,O as assertLogicformAllowed,u as getSchemaPermissions,M as isColumnAllowed,k as validatePermissions};
@@ -1 +0,0 @@
1
- import{createClient as i}from"@clickhouse/client";import{displayClickHouseQuery as s}from"./display-query.js";const u=a=>a===null?"Nullable(String)":typeof a=="boolean"?"Bool":typeof a=="number"?"Float64":a instanceof Date?"DateTime64(3)":"String",c=a=>a instanceof Date?a.toISOString().replace("T"," ").replace("Z",""):a;class l{kind="clickhouse";client;constructor(e={}){this.client=e.client??i({url:e.url??"http://localhost:8123",username:e.username??"default",password:e.password??"",database:e.database??"default"})}quoteIdentifier(e){return`\`${e.replaceAll("`","``")}\``}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,t){return`${e} LIMIT ${r}${t>0?` OFFSET ${t}`:""}`}parameter(e,r){return`{p${e}:${u(r)}}`}displayQuery(e,r){return s(e,r)}dateBucket(e,r){const n={hour:"toStartOfHour",day:"toStartOfDay",week:"toStartOfWeek",month:"toStartOfMonth",quarter:"toStartOfQuarter",year:"toStartOfYear"}[r];if(!n)throw new Error(`Unsupported ClickHouse date level: ${r}`);return`${n}(${e})`}dateShift(e,r,t){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(t))throw new Error(`Unsupported ClickHouse date shift: ${r}/${t}`);return`dateAdd('${r}', ${t}, ${e})`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported ClickHouse aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}concat(e){return`concat(${e.join(", ")})`}substring(e,r,t){return`substring(${e}, ${r}, ${t})`}regex(e,r,t){if(t&&t!=="i")throw new Error(`Unsupported ClickHouse regex options: ${t}`);const n=t==="i"?`concat('(?i)', ${r})`:r;return`match(${e}, ${n})`}arrayContains(e,r){return`has(${e}, ${r})`}expandArray(e,r,t){const n=this.quoteIdentifier(r);return{joinSql:`ARRAY JOIN ${e} AS ${n}`,valueExpression:n}}async execute(e){e.signal?.throwIfAborted();const r=Object.fromEntries(e.parameters.map((n,o)=>[`p${o}`,c(n)]));return(await this.client.query({query:e.sql,format:"JSONEachRow",query_params:r,...e.signal?{abort_signal:e.signal}:{}})).json()}async close(){await this.client.close()}}export{l as ClickHouseProvider};
@@ -1 +0,0 @@
1
- import{ClickHouseProvider as n}from"./clickhouse-provider.js";import{DorisProvider as s}from"./doris-provider.js";import{MySQLProvider as t}from"./mysql-provider.js";import{OracleProvider as d}from"./oracle-provider.js";import{PostgreSQLProvider as c}from"./postgresql-provider.js";import{SnowflakeProvider as p}from"./snowflake-provider.js";import{StarRocksProvider as m}from"./starrocks-provider.js";const a=o=>{switch(o.kind){case"mysql":{const{id:i,kind:e,...r}=o;return new t({connection:r})}case"doris":{const{id:i,kind:e,...r}=o;return new s({connection:r})}case"starrocks":{const{id:i,kind:e,...r}=o;return new m({connection:r})}case"postgresql":{const{id:i,kind:e,...r}=o;return new c({connection:r})}case"clickhouse":{const{id:i,kind:e,...r}=o;return new n(r)}case"snowflake":{const{id:i,kind:e,...r}=o;return new p({connection:r})}case"oracle":{const{id:i,kind:e,...r}=o;return new d({connection:r})}}};export{a as createProvider};
@@ -1 +0,0 @@
1
- const u=e=>`'${e.replaceAll("'","''")}'`,f=(e,r)=>{if(e==null)return"NULL";if(typeof e=="boolean")return e?"TRUE":"FALSE";if(typeof e=="number")return String(e);if(typeof e=="bigint")return u(e.toString());if(typeof e=="string")return u(e);if(e instanceof Date){const n=r==="clickhouse"?e.toISOString().replace("T"," ").replace("Z",""):e.toISOString();return u(n)}if(Buffer.isBuffer(e)){const n=e.toString("hex");return r==="oracle"?`HEXTORAW('${n}')`:r==="postgresql"?`decode('${n}', 'hex')`:r==="snowflake"?`TO_BINARY('${n}', 'HEX')`:`unhex('${n}')`}throw new TypeError(`Unsupported ${r} display parameter type: ${typeof e}`)},d=(e,r)=>e.replace(/\{p(\d+):[^}]+\}/g,(n,o)=>{const t=Number(o);return t in r?f(r[t],"clickhouse"):n}),l=(e,r)=>e.replace(/:([1-9]\d*)\b/g,(n,o)=>{const t=Number(o)-1;return t in r?f(r[t],"oracle"):n}),g=(e,r)=>{let n="",o;for(let t=0;t<e.length;t+=1){const i=e[t];if(i){if(o){n+=i,i===o&&(e[t+1]===o?(n+=o,t+=1):o=void 0);continue}if(i==="'"||i==='"'){o=i,n+=i;continue}if(i==="$"){const c=/^\$(\d+)/.exec(e.slice(t)),s=c?.[1];if(c&&s){const p=Number(s)-1;if(p in r){n+=f(r[p],"postgresql"),t+=c[0].length-1;continue}}}n+=i}}return n},y=(e,r)=>{let n="",o=0,t;for(let i=0;i<e.length;i+=1){const c=e[i];if(c){if(t){n+=c,c===t&&(e[i+1]===t?(n+=t,i+=1):t=void 0);continue}if(c==="'"||c==='"'||c==="`"){t=c,n+=c;continue}if(c==="?"&&o<r.length){n+=f(r[o],"snowflake"),o+=1;continue}n+=c}}return n};export{d as displayClickHouseQuery,l as displayOracleQuery,g as displayPostgreSQLQuery,y as displayQuestionMarkQuery};
@@ -1 +0,0 @@
1
- import{MySQLProtocolProvider as o}from"./mysql-protocol-provider.js";class s extends o{kind="doris";constructor(r={}){super(r)}}export{s as DorisProvider};
@@ -1 +0,0 @@
1
- import u from"mysql2";const o={quoteIdentifier(r){return`\`${r.replaceAll("`","``")}\``},tableAlias(r,t){return`${r} AS ${this.quoteIdentifier(t)}`},paginate(r,t,e){return`${r} LIMIT ${t}${e>0?` OFFSET ${e}`:""}`},parameter(r,t){return"?"},displayQuery(r,t){return u.format(r,[...t])},dateBucket(r,t){const e={hour:"%Y-%m-%d %H:00:00",day:"%Y-%m-%d",month:"%Y-%m-01",year:"%Y-01-01"};if(t==="week")return`DATE_SUB(DATE(${r}), INTERVAL WEEKDAY(${r}) DAY)`;if(t==="quarter")return`MAKEDATE(YEAR(${r}), 1) + INTERVAL (QUARTER(${r}) - 1) QUARTER`;const n=e[t];if(!n)throw new Error(`Unsupported MySQL-compatible date level: ${t}`);return`DATE_FORMAT(${r}, '${n}')`},dateShift(r,t,e){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(t)||!Number.isInteger(e))throw new Error(`Unsupported MySQL-compatible date shift: ${t}/${e}`);return`DATE_ADD(${r}, INTERVAL ${e} ${t.toUpperCase()})`},aggregateFunction(r,t="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(r))throw new Error(`Unsupported MySQL-compatible aggregate function: ${r}`);return`${r.toUpperCase()}(${t})`},concat(r){return`CONCAT(${r.join(", ")})`},substring(r,t,e){return`SUBSTRING(${r}, ${t}, ${e})`},regex(r,t,e){if(e&&e!=="i")throw new Error(`Unsupported MySQL-compatible regex options: ${e}`);return e==="i"?`LOWER(${r}) REGEXP LOWER(${t})`:`${r} REGEXP ${t}`},arrayContains(r,t){return`JSON_OVERLAPS(${r}, JSON_ARRAY(${t}))`},expandArray(r,t,e){const n=this.quoteIdentifier(t),$=this.quoteIdentifier(e);return{joinSql:`CROSS JOIN JSON_TABLE(CASE WHEN JSON_TYPE(${r}) = 'ARRAY' THEN ${r} ELSE JSON_ARRAY() END, '$[*]' COLUMNS (${$} JSON PATH '$')) AS ${n}`,valueExpression:`${n}.${$}`}}};export{o as mysqlCompatibleSql};
@@ -1 +0,0 @@
1
- import{createPool as o}from"mysql2/promise";import{mysqlCompatibleSql as t}from"./mysql-compatible-sql.js";class i{supportsRecursiveCte=!0;pool;constructor(r={}){this.pool=r.pool??o(r.connection??{})}quoteIdentifier(r){return t.quoteIdentifier(r)}tableAlias(r,e){return t.tableAlias(r,e)}paginate(r,e,a){return t.paginate(r,e,a)}parameter(r,e){return t.parameter(r,e)}displayQuery(r,e){return t.displayQuery(r,e)}dateBucket(r,e){return t.dateBucket(r,e)}dateShift(r,e,a){return t.dateShift(r,e,a)}aggregateFunction(r,e){return t.aggregateFunction(r,e)}concat(r){return t.concat(r)}substring(r,e,a){return t.substring(r,e,a)}regex(r,e,a){return t.regex(r,e,a)}arrayContains(r,e){const a=t.arrayContains?.bind(t);if(!a)throw new Error("MySQL-compatible array conditions are unavailable");return a(r,e)}expandArray(r,e,a){const n=t.expandArray?.bind(t);if(!n)throw new Error("MySQL-compatible array expansion is unavailable");return n(r,e,a)}async execute(r){r.signal?.throwIfAborted();const[e]=await this.pool.execute(r.sql,r.parameters);if(!Array.isArray(e))throw new Error(`${this.kind} provider expected an array result`);return e}async close(){await this.pool.end()}}export{i as MySQLProtocolProvider};
@@ -1 +0,0 @@
1
- import{MySQLProtocolProvider as o}from"./mysql-protocol-provider.js";class e extends o{kind="mysql";constructor(r={}){super(r)}}export{e as MySQLProvider};
@@ -1 +0,0 @@
1
- import c from"oracledb";import{displayOracleQuery as l}from"./display-query.js";const u=o=>{if(o==null)return null;if(typeof o=="bigint")return o.toString();if(typeof o=="string"||typeof o=="number"||typeof o=="boolean"||o instanceof Date||Buffer.isBuffer(o))return o;throw new TypeError(`Unsupported Oracle parameter type: ${typeof o}`)},d=o=>o.reason instanceof Error?o.reason:new DOMException("The operation was aborted","AbortError");class p{kind="oracle";supportsHavingAlias=!1;maxInListItems=1e3;#t;#e;#r;constructor(r={}){this.#t=r.connection??{},this.#e=r.driver??{createPool:t=>c.createPool(t)},this.#r=r.pool?Promise.resolve(r.pool):void 0}quoteIdentifier(r){return`"${r.replaceAll('"','""')}"`}tableAlias(r,t){return`${r} ${this.quoteIdentifier(t)}`}paginate(r,t,e){return e>0?`${r} OFFSET ${e} ROWS FETCH NEXT ${t} ROWS ONLY`:`${r} FETCH FIRST ${t} ROWS ONLY`}parameter(r,t){return`:${r+1}`}displayQuery(r,t){return l(r,t.map(u))}dateBucket(r,t){const e={hour:"HH24",day:void 0,week:"IW",month:"MM",quarter:"Q",year:"YYYY"};if(!(t in e))throw new Error(`Unsupported Oracle date level: ${t}`);const n=e[t];return n?`TRUNC(${r}, '${n}')`:`TRUNC(${r})`}dateShift(r,t,e){if(!Number.isInteger(e))throw new Error(`Unsupported Oracle date shift: ${t}/${e}`);const i={month:1,quarter:3,year:12}[t];if(i)return`ADD_MONTHS(${r}, ${e*i})`;const s={second:{unit:"SECOND",multiplier:1},minute:{unit:"MINUTE",multiplier:1},hour:{unit:"HOUR",multiplier:1},day:{unit:"DAY",multiplier:1},week:{unit:"DAY",multiplier:7}}[t];if(!s)throw new Error(`Unsupported Oracle date shift: ${t}/${e}`);return`(${r} + NUMTODSINTERVAL(${e*s.multiplier}, '${s.unit}'))`}aggregateFunction(r,t="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(r))throw new Error(`Unsupported Oracle aggregate function: ${r}`);return`${r.toUpperCase()}(${t})`}concat(r){return`(${r.join(" || ")})`}substring(r,t,e){return`SUBSTR(${r}, ${t}, ${e})`}regex(r,t,e){if(e&&e!=="i")throw new Error(`Unsupported Oracle regex options: ${e}`);return`REGEXP_LIKE(${r}, ${t}${e?", 'i'":""})`}arrayContains(r,t){return`JSON_EXISTS(${r}, '$?(@ == $value)' PASSING ${t} AS "value")`}expandArray(r,t,e){const n=this.quoteIdentifier(t),i=this.quoteIdentifier(e);return{joinSql:`CROSS APPLY JSON_TABLE(${r}, '$[*]' COLUMNS (${i} VARCHAR2(4000) PATH '$')) ${n}`,valueExpression:`${n}.${i}`}}async#o(){this.#r??=this.#e.createPool(this.#t);try{return await this.#r}catch(r){throw this.#r=void 0,r}}async execute(r){r.signal?.throwIfAborted();const t=await this.#o();r.signal?.throwIfAborted();const e=await t.getConnection(),n=r.signal,i=()=>{e.break().catch(()=>{})};n?.addEventListener("abort",i,{once:!0});try{const a=await e.execute(r.sql,r.parameters.map(u),{outFormat:c.OUT_FORMAT_OBJECT});if(n?.throwIfAborted(),!Array.isArray(a.rows))throw new Error("Oracle provider expected an array result");return a.rows}catch(a){throw n?.aborted?d(n):a}finally{n?.removeEventListener("abort",i),await e.close()}}async close(){const r=this.#r;if(!r)return;await(await r).close(0),this.#r=void 0}}export{p as OracleProvider};
@@ -1 +0,0 @@
1
- import{Pool as s}from"pg";import{displayPostgreSQLQuery as a}from"./display-query.js";class i{kind="postgresql";supportsHavingAlias=!1;supportsRecursiveCte=!0;pool;constructor(r={}){this.pool=r.pool??new s(r.connection)}quoteIdentifier(r){return`"${r.replaceAll('"','""')}"`}tableAlias(r,e){return`${r} AS ${this.quoteIdentifier(e)}`}paginate(r,e,t){return`${r} LIMIT ${e}${t>0?` OFFSET ${t}`:""}`}parameter(r,e){return`$${r+1}`}displayQuery(r,e){return a(r,e)}dateBucket(r,e){if(!new Set(["hour","day","week","month","quarter","year"]).has(e))throw new Error(`Unsupported PostgreSQL date level: ${e}`);return`DATE_TRUNC('${e}', ${r})`}dateShift(r,e,t){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(e)||!Number.isInteger(t))throw new Error(`Unsupported PostgreSQL date shift: ${e}/${t}`);return`(${r} + (${t} * INTERVAL '1 ${e}'))`}aggregateFunction(r,e="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(r))throw new Error(`Unsupported PostgreSQL aggregate function: ${r}`);return`${r.toUpperCase()}(${e})`}concat(r){return`CONCAT(${r.join(", ")})`}substring(r,e,t){return`SUBSTRING(${r} FROM ${e} FOR ${t})`}regex(r,e,t){if(t&&t!=="i")throw new Error(`Unsupported PostgreSQL regex options: ${t}`);return`${r} ${t==="i"?"~*":"~"} ${e}`}arrayContains(r,e){return`${e} = ANY(${r})`}expandArray(r,e,t){const o=this.quoteIdentifier(e),n=this.quoteIdentifier(t);return{joinSql:`CROSS JOIN LATERAL unnest(${r}) AS ${o}(${n})`,valueExpression:`${o}.${n}`}}async execute(r){r.signal?.throwIfAborted();const e=await this.pool.query(r.sql,[...r.parameters]);if(r.signal?.throwIfAborted(),!Array.isArray(e.rows))throw new Error("PostgreSQL provider expected an array result");return e.rows}async close(){await this.pool.end()}}export{i as PostgreSQLProvider};
@@ -1 +0,0 @@
1
- import $ from"snowflake-sdk";import{displayQuestionMarkQuery as h}from"./display-query.js";const p=n=>{if(n==null)return null;if(n instanceof Date)return n.toISOString();if(typeof n=="bigint")return n.toString();if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;throw new TypeError(`Unsupported Snowflake parameter type: ${typeof n}`)},w=n=>n.reason instanceof Error?n.reason:new DOMException("The operation was aborted","AbortError");class l{kind="snowflake";#e;#r=!1;#t;constructor(e={}){this.#e=e.client??$.createConnection(e.connection??{})}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,t){return`${e} LIMIT ${r}${t>0?` OFFSET ${t}`:""}`}parameter(e,r){return"?"}displayQuery(e,r){return h(e,r.map(p))}dateBucket(e,r){if(!new Set(["hour","day","week","month","quarter","year"]).has(r))throw new Error(`Unsupported Snowflake date level: ${r}`);return`DATE_TRUNC('${r.toUpperCase()}', ${e})`}dateShift(e,r,t){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(t))throw new Error(`Unsupported Snowflake date shift: ${r}/${t}`);return`DATEADD(${r.toUpperCase()}, ${t}, ${e})`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported Snowflake aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,t){return`SUBSTRING(${e}, ${r}, ${t})`}regex(e,r,t){if(t&&t!=="i")throw new Error(`Unsupported Snowflake regex options: ${t}`);return t?`REGEXP_INSTR(${e}, ${r}, 1, 1, 0, '${t}') > 0`:`REGEXP_INSTR(${e}, ${r}) > 0`}arrayContains(e,r){return`ARRAY_CONTAINS(${r}::VARIANT, ${e})`}expandArray(e,r,t){const o=this.quoteIdentifier(r);return{joinSql:`, LATERAL FLATTEN(INPUT => ${e}) ${o}`,valueExpression:`${o}.VALUE`}}async#n(){if(!this.#r){this.#t??=new Promise((e,r)=>{this.#e.connect(t=>{if(t){r(t);return}this.#r=!0,e()})});try{await this.#t}catch(e){throw this.#t=void 0,e}}}async execute(e){e.signal?.throwIfAborted(),await this.#n(),e.signal?.throwIfAborted();const r=e.parameters.map(p);return new Promise((t,o)=>{const i=e.signal,c={};let f=!1;const a=s=>{f||(f=!0,i?.removeEventListener("abort",u),s())},u=()=>{c.current?.cancel(),i&&a(()=>o(w(i)))};i?.addEventListener("abort",u,{once:!0}),c.current=this.#e.execute({sqlText:e.sql,binds:r,complete:(s,A,d)=>{if(s){a(()=>o(s));return}if(!Array.isArray(d)){a(()=>o(new Error("Snowflake provider expected an array result")));return}a(()=>t(d))}}),i?.aborted&&u()})}async close(){this.#r&&await new Promise((e,r)=>{this.#e.destroy(t=>{if(t){r(t);return}this.#r=!1,this.#t=void 0,e()})})}}export{l as SnowflakeProvider};
@@ -1 +0,0 @@
1
- import{MySQLProtocolProvider as o}from"./mysql-protocol-provider.js";class s extends o{kind="starrocks";constructor(r={}){super(r)}}export{s as StarRocksProvider};
@@ -1 +0,0 @@
1
- import{createOperatorRegistry as s}from"../operators/index.js";import{getProperty as I}from"../schema/schema-registry.js";const h=(t,r)=>{const o=I(t,r);return{schemaId:t.id,propertyId:o.id,propertyName:o.name,physicalColumn:o.udf?.sql??o.id}},f=(t,r,o)=>{const c=t.fieldReferences?.[o];return c?{schemaId:c.schemaId,propertyId:c.propertyId??c.column,propertyName:c.property,physicalColumn:c.sql??c.column}:h(r,o)},l=(t,r,o,c)=>{if(t.kind==="column")return{sources:[{schemaId:t.schemaId??o.id,propertyId:t.propertyId??t.column,propertyName:t.property,physicalColumn:t.column}],transformations:["projection"]};if(t.kind==="property-sql")return{sources:[{schemaId:t.schemaId,propertyId:t.propertyId,propertyName:t.property,physicalColumn:t.sql}],transformations:["property-sql"]};if(t.kind==="array-element")return{sources:[{schemaId:t.schemaId,propertyId:t.property,propertyName:t.property,physicalColumn:t.property}],transformations:["array-expand"]};if(t.kind==="window"){const a=[t.input,...t.partitionBy].map(n=>l(n,r,o,c));return{sources:a.flatMap(({sources:n})=>n),transformations:[...a.flatMap(({transformations:n})=>n).filter(n=>n!=="projection"),`window:${t.function}`]}}if(t.kind==="cumulative"){const a=[t.input,...t.partitionBy,...t.orderBy.map(({expression:n})=>n)].map(n=>l(n,r,o,c));return{sources:a.flatMap(({sources:n})=>n),transformations:[...a.flatMap(({transformations:n})=>n).filter(n=>n!=="projection"),`window:cumulative:${t.function}`]}}if(t.kind==="ordinal-encode"||t.kind==="ordinal-decode"){const a=l(t.input,r,o,c);return{sources:a.sources,transformations:[...a.transformations.filter(n=>n!=="projection"),`ordinal:${t.kind==="ordinal-encode"?"encode":"decode"}`]}}const i=[...t.input?[t.input]:[],...t.components??[]].map(a=>l(a,r,o,c)),d={sources:i.flatMap(({sources:a})=>a),transformations:i.flatMap(({transformations:a})=>a)},p=c.get(t.operator),u=new Set([...t.property?[t.property]:[],...p.dependencies??[],...m(t.query)]);return{sources:[...d.sources,...[...u].filter(a=>!d.sources.some(n=>n.propertyName===a)).map(a=>f(r,o,a))],transformations:[...d.transformations.filter(a=>a!=="projection"),`operator:${t.operator}`]}};function m(t){if(!t)return[];const r=[];for(const[o,c]of Object.entries(t))if((o==="$and"||o==="$or")&&Array.isArray(c))for(const i of c)typeof i=="object"&&i!==null&&!Array.isArray(i)&&r.push(...m(i));else o.startsWith("$")||r.push(o);return r}const e=t=>t.kind==="window"?[...e(t.input),...t.partitionBy.flatMap(e)]:t.kind==="cumulative"?[...e(t.input),...t.partitionBy.flatMap(e),...t.orderBy.flatMap(({expression:r})=>e(r))]:t.kind==="ordinal-encode"||t.kind==="ordinal-decode"?e(t.input):t.kind==="operator"?[...m(t.query),...t.input?e(t.input):[],...(t.components??[]).flatMap(e)]:[],y=(t,r,o,c=s())=>{if(t.composition){const i=t.composition.map(d=>y(d,r,o,c));return{source:{schemaId:r.id,schemaName:r.name,physicalTable:i.map(({source:d})=>d.physicalTable).join(", "),provider:o.kind},outputs:t.projections.map(({name:d})=>{const p=i.flatMap(({outputs:u})=>u.filter(a=>a.name===d));return{name:d,sources:p.flatMap(({sources:u})=>u),transformations:[...new Set([...p.flatMap(({transformations:u})=>u),"compose"])]}}),filters:i.flatMap(({filters:d})=>d)}}return{source:{schemaId:r.id,schemaName:r.name,physicalTable:t.source,provider:o.kind},outputs:t.projections.map(i=>({name:i.name,...l(i.expression,t,r,c)})),filters:[...new Set([...m(t.query),...t.projections.flatMap(({expression:i})=>e(i))])].map(i=>f(t,r,i))}};export{y as buildLineage};
@@ -1 +0,0 @@
1
- import{SemanticDBError as m}from"../errors.js";import{createOperatorRegistry as ce}from"../operators/index.js";import{isComposedLogicform as ue,isLogicform as te}from"../logicform-types.js";import{buildFieldMap as me}from"../schema/schema-registry.js";import{resolvePropertyPath as z}from"../schema/resolve-property-path.js";import{SchemaMappingRegistry as de}from"../schema-mappings/registry.js";import{createPlannerSemanticRegistry as ye}from"./semantics/registry-defaults.js";import{selectSchemaMapping as le,mappedPropertyColumn as ne}from"./select-schema-mapping.js";const fe=(e,o)=>`result:${e}:${o.map(({name:c,type:y,primal_type:d})=>`${c}:${y}:${d}`).join("|")}`,oe=(e,o)=>{const c=(e.columnProperties??[]).map(y=>({...y,id:y.name}));return{id:fe(e.schemaId,e.columnProperties??[]),name:`${o.name} result`,type:o.type,temporalSemantics:"normal",properties:c}},ie=(e,o)=>({...oe(e,o),id:o.id,name:o.name,type:o.type}),v=e=>{if(!e.name)throw new m("MISSING_PRED_NAME","Planner requires every normalized PredItem to have a name");return e.name},he=(e,o,c)=>{const y=new Set(c),d=(I,g)=>{if(!(te(I)||I===null)){if(Array.isArray(I)){I.forEach(l=>d(l,g));return}if(typeof I=="object"){Object.entries(I).forEach(([l,E])=>{["args","$exists","$regex","$contains"].includes(l)||d(E,l)});return}if(!(g&&["args","$exists","$regex","$contains"].includes(g))&&(typeof I!="string"||!y.has(I)))throw new m("COMPARABLE_VALUE_NOT_FOUND",`Comparable category ${o} does not contain value: ${JSON.stringify(I)}`,{property:o,value:I})}};d(e)},ge=(e,o)=>{if(!o.udf)return{};const c=e.properties.find(({type:y})=>y==="timestamp")?.id;return{sql:o.udf.sql,...c?{timestampColumn:c}:{}}},se=e=>e.sql?{kind:"property-sql",schemaId:e.schemaId,property:e.property,propertyId:e.column,sql:e.sql,qualifier:e.qualifier,...e.timestampColumn?{timestampColumn:e.timestampColumn}:{}}:{kind:"column",...e},ae=(e,o,c={})=>({name:e,type:o.type,primal_type:o.primal_type,isArray:o.isArray,...o.ref?{ref:o.ref}:{},...o.comparable?{comparable:o.comparable}:{},...c}),M=(e,o,c,y,d,I,g,l,E="projection")=>{const T=v(e);if(E==="groupby"&&e.query)throw new m("GROUPBY_QUERY_NOT_ALLOWED","A groupby expression cannot define pred.query");if(!e.operator){if(typeof e.pred!="string")throw new m("PRED_PROPERTY_REQUIRED","A projection must reference a property");const h=c(e.pred);return{expression:se(h.field),outputProperty:ae(h.reference,h.property),sourceProperty:h.property,sourceField:h.field}}const S=o.get(e.operator);if(E==="groupby"&&S.kind!=="scalar")throw new m("OPERATOR_NOT_ALLOWED_IN_GROUPBY",`Operator ${e.operator} cannot be used in groupby`,{operator:e.operator});if(E==="groupby"&&!S.toSQL)throw new m("JAVASCRIPT_OPERATOR_NOT_ALLOWED_IN_GROUPBY",`JavaScript-only operator ${e.operator} cannot be used in groupby`,{operator:e.operator});if(S.planInput&&typeof e.pred!="string")throw new m("OPERATOR_DIRECT_PROPERTY_REQUIRED",`${e.operator} requires a direct property pred`);const b=S.planInput&&typeof e.pred=="string"?S.planInput({reference:e.pred,args:e.args??{},schema:g,...l?{resolveSchema:l}:{}}):void 0,A=b?.reference??e.pred,_=b?.args??e.args??{},u=A&&typeof A=="object"&&!Array.isArray(A)?M(A,o,c,y,d,I,g,l,E):typeof A=="string"?M({pred:A,name:A},o,c,y,d,I,g,l,E):void 0,s=e.components?.map(h=>M(h,o,c,y,d,I,g,l,E))??[];if(S.requiresProperty!==!1&&!u&&s.length===0)throw new m("PRED_PROPERTY_REQUIRED",`${e.operator} requires a property`);const P=T,f=S.getOutputProperty?.({name:P,...u?.sourceProperty?{property:u.sourceProperty}:{},...u?{inputProperty:{...u.outputProperty,name:P}}:{},...s.length>0?{componentProperties:s.map(({outputProperty:h})=>h)}:{},args:_})??(u?ae(P,u.outputProperty,{isArray:!1}):{name:P,type:"number",primal_type:"number",isArray:!1});if(S.planExpression){const h=S.planExpression({pred:e,...u?{input:u.expression,inputProperty:u.outputProperty}:{},components:s.map(({expression:w})=>w),args:_,resolveKey:d,getOperator:w=>o.get(w),planQuery:I});if(h)return{expression:h,outputProperty:f,...u?.sourceProperty?{sourceProperty:u.sourceProperty}:{},...u?.sourceField?{sourceField:u.sourceField}:{}}}if(S.kind==="window"){if(!u||s.length>0||e.query)throw new m("INVALID_WINDOW_OPERATOR_INPUT",`${e.operator} requires exactly one nested pred and does not accept pred.query`);const h=e.args?.direction??"desc";if(h!=="asc"&&h!=="desc")throw new m("INVALID_WINDOW_ARGS",`${e.operator} direction must be asc or desc`);const w=e.args?.partitionBy??[];if(!Array.isArray(w)||w.some(D=>typeof D!="string"))throw new m("INVALID_WINDOW_ARGS",`${e.operator} partitionBy must be an array of groupby names`);return{expression:{kind:"window",function:S.windowFunction,input:u.expression,partitionBy:w.map(D=>y(String(D))),direction:h==="asc"?"ASC":"DESC"},outputProperty:f}}return{expression:{kind:"operator",operator:e.operator,args:_,...e.query?{query:I(e.query)}:{},...u?{input:u.expression}:{},...s.length>0?{components:s.map(({expression:h})=>h)}:{},...u?.sourceProperty?{property:u.sourceProperty.name,column:u.sourceProperty.id}:{},...u?.sourceField?{qualifier:u.sourceField.qualifier,schemaId:u.sourceField.schemaId}:{}},outputProperty:f,...u?.sourceProperty?{sourceProperty:u.sourceProperty}:{},...u?.sourceField?{sourceField:u.sourceField}:{}}},Ie=(e,o,c,y,d,I,g,l,E,T)=>{const S=v(e),b=typeof e.pred=="string"?e.pred:void 0,_=M(e,o,!T||!b?c:s=>{const P=c(s);return s===b?{...P,field:{...P.field,column:T}}:P},y,d,I,g,l),u=E?.resolveProjection({pred:e,schema:g,..._.sourceProperty?{sourceProperty:_.sourceProperty}:{},outputProperty:{..._.outputProperty,name:S},...e.operator?{operator:o.get(e.operator)}:{}})??{..._.outputProperty,name:S};return{name:S,expression:_.expression,outputProperty:u}},Se=e=>{const o=new Set;for(const c of e){if(o.has(c.name))throw new m("DUPLICATE_OUTPUT_NAME",`Duplicate output name: ${c.name}`);o.add(c.name)}},Pe=e=>{let o="__semanticdb_row_identity";for(;e.has(o);)o=`_${o}`;return o},X=(e,o,c)=>{if(!e.schema||e.schema===o.id)return o;const y=c.resolveSchema?.(e.schema);if(!y)throw new m("SCHEMA_RESOLVER_REQUIRED",`Cannot plan nested LogicForm schema without a schema resolver: ${e.schema}`,{schemaId:e.schema});return y},we=(e,o,c,y,d)=>{if(e.logicforms.length<2)throw new m("COMPOSITION_REQUIRES_MULTIPLE_LOGICFORMS","logicforms must contain at least two LogicForms");const I=["schema","from","query","preds","groupby","having","limit","page","entity_id"].filter(s=>e[s]!==void 0);if(I.length>0)throw new m("INVALID_COMPOSED_LOGICFORM",`A composed LogicForm cannot define: ${I.join(", ")}`,{fields:I});const g=e.logicforms.map(s=>F(s,X(s,o,d),c,y,d)),l=g[0]?.groupBy.map(({name:s})=>s)??[];for(const s of g){const P=s.groupBy.map(({name:f})=>f);if(P.length!==l.length||P.some((f,h)=>f!==l[h]))throw new m("INCOMPATIBLE_COMPOSITION_GROUPBY","All composed LogicForms must have the same groupby output names in the same order",{expected:l,received:P});if(s.rowIdentity.kind!==(l.length>0?"group":"singleton"))throw new m("UNSTABLE_COMPOSITION_IDENTITY","Composed LogicForms must be grouped or aggregate to a singleton row")}const E=[],T=[],S=new Map;g.forEach((s,P)=>{s.projections.forEach((f,h)=>{const w=l.includes(f.name),D=S.get(f.name);if(D!==void 0&&!w)throw new m("DUPLICATE_COMPOSITION_OUTPUT",`Composed LogicForms produce the same output: ${f.name}`,{name:f.name,childIndexes:[D,P]});if(D!==void 0)return;S.set(f.name,P),E.push({name:f.name,expression:{kind:"column",property:f.name,column:f.name}});const B=s.columnProperties?.[h];B&&T.push(B)})});const b=new Set(E.map(({name:s})=>s)),A=Object.entries(e.sort??{}).map(([s,P])=>{if(!b.has(s))throw new m("INVALID_SORT",`Sort field is not an output: ${s}`);const f=T.find(h=>h.name===s);return{name:s,direction:P===1?"ASC":"DESC",...f?.comparable?{comparable:f.comparable}:{},...f?.comparable?{expression:{kind:"column",property:s,column:s}}:{}}}),_=e.limitBy===void 0||l.length<2?void 0:{count:e.limitBy,partitionBy:l.slice(0,-1),orderBy:A.length>0?A:(()=>{const s=l.at(-1)??"",P=T.find(f=>f.name===s);return[{name:s,direction:"ASC",...P?.comparable?{comparable:P.comparable}:{}}]})()},u=e.limitBy!==void 0&&l.length<2?{kind:"rows",page:1,pageSize:e.limitBy}:void 0;return{schemaId:o.id,source:"",composition:g,fields:Object.fromEntries(E.map(({name:s})=>[s,s])),projections:E,columnProperties:T,groupBy:E.filter(({name:s})=>l.includes(s)),orderBy:A,rowIdentity:l.length>0?{kind:"group",names:l}:{kind:"singleton"},..._?{groupLimit:_}:{},...u?{pagination:u}:{}}},F=(e,o,c=ce(),y=new de,d={})=>{if(ue(e))return we(e,o,c,y,d);for(const r of e.preds??[]){if(!r.operator)continue;const t=c.get(r.operator).rewriteLogicform?.({logicform:e,schema:o});if(t)return F(t,o,c,y,d)}const I=d.semanticRegistry??ye();if(e.from){const r=X(e.from,o,d),t=F(e.from,r,c,y,d),n=ie(t,o),i={...e};delete i.from,i.schema??=n.id;const p=F(i,n,c,y,d),a=new Set(p.projections.map(({name:R})=>R)),N=t.rowIdentity.kind==="group"&&t.rowIdentity.names.every(R=>a.has(R))||t.rowIdentity.kind==="singleton"?t.rowIdentity:{kind:"generated"};return{...p,source:t.source,sourcePlan:t,rowIdentity:N}}if(!e.schema)throw new m("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema");const g=le(e,o,y);e=g.logicform;const l=new Map(g.predRewrites.map(({predIndex:r,column:t})=>[r,t])),E=I.resolveQuery({logicform:e,schema:o,...e.query?{query:e.query}:{}}),T=o.id,S=new Map,b=new Map,A=new Map,_=r=>{const t=z(o,r,d.resolveSchema);let n=T;const i=[];for(const a of t.relations){i.push(a.property.name);const N=i.join("_"),R=N;if(!S.has(N)){const q=a.targetSchema.properties.filter(({type:L})=>L==="ID"),[C]=q;if(q.length!==1||!C)throw new m(a.targetSchema.temporalSemantics==="snapshot"?"SNAPSHOT_JOIN_REQUIRES_ID_AND_TIMESTAMP":"RELATION_TARGET_ID_REQUIRED",a.targetSchema.temporalSemantics==="snapshot"?`Snapshot Schema ${a.targetSchema.id} requires an ID Property when joined`:`Relation target ${a.targetSchema.id} must contain exactly one ID property`,{schemaId:a.targetSchema.id,count:q.length});const $=a.sourceSchema.properties.find(({type:L})=>L==="timestamp"),U=a.targetSchema.properties.find(({type:L})=>L==="timestamp"),O=$?.id,Q=U?.id;if(a.targetSchema.temporalSemantics==="snapshot"){if(!U)throw new m("SNAPSHOT_JOIN_REQUIRES_ID_AND_TIMESTAMP",`Snapshot Schema ${a.targetSchema.id} requires an ID and timestamp Property when joined`,{schemaId:a.targetSchema.id});if(!$)throw new m("SNAPSHOT_JOIN_SOURCE_TIMESTAMP_REQUIRED",`Snapshot Schema ${a.targetSchema.id} cannot join from a Schema without a timestamp Property`,{schemaId:a.sourceSchema.id});const L=["second","minute","hour","day","week","month","quarter","year"],J=$.granularity??"day",k=U.granularity??"day";if(L.indexOf(J)>L.indexOf(k))throw new m("SNAPSHOT_JOIN_GRANULARITY_TOO_COARSE",`Cannot join ${a.targetSchema.id} snapshot granularity ${k} to coarser source granularity ${J}`,{sourceSchemaId:a.sourceSchema.id,targetSchemaId:a.targetSchema.id,sourceGranularity:J,targetGranularity:k})}const j=a.property.isArray?N:void 0;j&&!b.has(j)&&b.set(j,{path:j,sourceAlias:n,sourceColumn:a.property.id,...a.property.udf?{sourceSql:a.property.udf.sql,...O?{sourceTimestampColumn:O}:{}}:{},alias:`__array_${N}`});const H=y.get(a.targetSchema.id);S.set(N,{kind:"left",path:N,sourceAlias:n,sourceColumn:a.property.id,...a.property.udf?{sourceSql:a.property.udf.sql,...O?{sourceTimestampColumn:O}:{}}:{},targetSchemaId:a.targetSchema.id,targetSource:H.source,...H.sourceSql?{targetSourceSql:H.sourceSql}:{},targetAlias:R,targetColumn:C.id,...j?{sourceArrayExpansionPath:j}:{},...C.udf?{targetSql:C.udf.sql,...Q?{targetTimestampColumn:Q}:{}}:{},...a.targetSchema.temporalSemantics==="snapshot"&&O?{sourceTimestampColumn:O,sourceTimestampGranularity:$.granularity??"day"}:{},...a.targetSchema.temporalSemantics==="snapshot"&&Q?{targetTimestampColumn:Q,targetTimestampGranularity:U.granularity??"day"}:{}})}n=R}const p={schemaId:t.schema.id,property:t.property.name,propertyId:t.property.id,column:t.relations.length===0?ne(g.mapping,o,t.canonicalName)??t.property.id:t.property.id,qualifier:n,...t.property.isArray?{isArray:!0}:{},...t.property.comparable?{comparable:t.property.comparable}:{},...ge(t.schema,t.property)};return A.set(t.canonicalName,p),{reference:t.canonicalName,schema:t.schema,property:t.property,field:p}},u=r=>{if(r)for(const[t,n]of Object.entries(r))if((t==="$and"||t==="$or")&&Array.isArray(n))for(const i of n)typeof i=="object"&&i!==null&&!Array.isArray(i)&&u(i);else t.startsWith("$")||_(t)},s=r=>{if(te(r)){const t=X(r,o,d),n=F(r,t,c,y,d);if(n.projections.length!==1)throw new m("SUBQUERY_SINGLE_COLUMN_REQUIRED",`Query LogicForm must output exactly one column, received ${n.projections.length}`,{schemaId:r.schema,projectionCount:n.projections.length});return{kind:"logicform-subquery",plan:n}}return Array.isArray(r)?r.map(s):typeof r!="object"||r===null||r instanceof Date?r:Object.fromEntries(Object.entries(r).map(([t,n])=>[t,s(n)]))},P=(r,t)=>{if(typeof t!="object"||t===null||Array.isArray(t))throw new m("INVALID_RECURSIVE_QUERY","$recursive must be normalized before planning");const n=t,i=_(r),p=typeof n.schema=="string"?n.schema:i.property.ref??i.schema.id,a=p===o.id?o:d.resolveSchema?.(p);if(!a)throw new m("SCHEMA_RESOLVER_REQUIRED",`$recursive requires Schema ${p}`);const N=a.properties.find(({id:C,name:$})=>C===n.idProperty||$===n.idProperty),R=a.properties.find(({id:C,name:$})=>C===n.parentProperty||$===n.parentProperty);if(!N)throw new m("RECURSIVE_ID_PROPERTY_REQUIRED",`$recursive ID property not found: ${String(n.idProperty)}`);if(!R)throw new m("RECURSIVE_PARENT_PROPERTY_REQUIRED",`$recursive parent property not found: ${String(n.parentProperty)}`);if(!Array.isArray(n.roots)||typeof n.includeSelf!="boolean")throw new m("INVALID_RECURSIVE_QUERY","$recursive must be normalized before planning");const q=y.get(p);return{kind:"recursive-query",schemaId:p,source:q.source,...q.sourceSql?{sourceSql:q.sourceSql}:{},idColumn:N.id,parentColumn:R.id,roots:n.roots,includeSelf:n.includeSelf}},f=r=>Object.fromEntries(Object.entries(r).map(([t,n])=>{if((t==="$and"||t==="$or")&&Array.isArray(n))return[t,n.map(p=>f(p))];if(typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"$recursive"))return[t,{$recursive:P(t,n.$recursive)}];const i=t.startsWith("$")?void 0:_(t).property.comparable;return[t,i?{kind:"ordinal-query",comparable:i,condition:s(n)}:s(n)]})),h=r=>{const t=i=>{if(!i||typeof i!="object")return!1;if(Array.isArray(i))return i.some(t);const p=i;return Object.prototype.hasOwnProperty.call(p,"$and")||Object.values(p).some(t)};if(t(r))return r;const n=new Set(Object.keys(r).flatMap(i=>{if(i.startsWith("$"))return[];const p=z(o,i,d.resolveSchema);return p.relations.length===1&&p.property.type==="ID"?[p.relations[0]?.property.name]:[]}));return Object.fromEntries(Object.entries(r).map(([i,p])=>{if(i==="$and"||i==="$or")return Array.isArray(p)?[i,p.map(O=>typeof O=="object"&&O!==null&&!Array.isArray(O)?h(O):O)]:[i,p];if(i.startsWith("$"))return[i,p];const a=z(o,i,d.resolveSchema);if(a.relations.length===0)return[i,p];const N=a.relations.map(({property:O})=>O.name).join("_");if(S.has(N))return[i,p];const[R]=a.relations;if(!R)return[i,p];if(n.has(R.property.name))return[i,p];const q=R.property.name,C=a.canonicalName.slice(q.length+1),$=R.targetSchema.properties.find(({type:O})=>O==="ID");if(!$)throw new m("RELATION_TARGET_ID_REQUIRED",`Relation target ${R.targetSchema.id} must contain an ID property`,{schemaId:R.targetSchema.id});if(a.relations.length===1&&a.property.id===$.id)return[R.property.id,p];const U={version:e.version,schema:R.targetSchema.id,query:C?{[C]:p}:{},preds:[{pred:$.name,name:$.name}]};return[R.property.id,{$in:U}]}))},w=(e.groupby??[]).map(r=>{const t=v(r);if(r.operator==="$case"&&r.args?.mode==="auto"&&(r.args.min===void 0||r.args.max===void 0))throw new m("AUTO_CASE_GROUPBY_REQUIRES_BOUNDS","$case auto mode in groupby requires explicit args.min and args.max");const n=M(r,c,_,D,B,f,o,d.resolveSchema,"groupby");let i=n.expression;if(n.sourceProperty?.isArray&&n.sourceField){const p=`groupby:${t}`;b.set(p,{path:p,sourceAlias:n.sourceField.qualifier,sourceColumn:n.sourceField.column,...n.sourceField.sql?{sourceSql:n.sourceField.sql,...n.sourceField.timestampColumn?{sourceTimestampColumn:n.sourceField.timestampColumn}:{}}:{},alias:`__array_group_${b.size}`}),i={kind:"array-element",schemaId:n.sourceField.schemaId,property:n.sourceProperty.name,expansionPath:p}}return{name:t,expression:i,outputProperty:{...n.outputProperty,name:t,isArray:!1}}});function D(r){const t=(e.groupby??[]).findIndex(i=>typeof i.pred=="string"&&i.pred===r||i.name===r),n=t>=0?w[t]:void 0;if(!n)throw new m("WINDOW_PARTITION_NOT_GROUPED",`Window partition must reference a groupby item: ${r}`);return n.expression}function B(r){const t=(e.groupby??[]).findIndex(i=>typeof i.pred=="string"&&i.pred===r||i.name===r),n=t>=0?w[t]:void 0;return n?n.expression:se(_(r).field)}const G=r=>{r.operator&&c.get(r.operator).validatePlan?.({pred:r,groupByNames:w.map(({name:t})=>t),resolveGroupName:t=>{const n=(e.groupby??[]).findIndex(i=>i.name===t||typeof i.pred=="string"&&i.pred===t);return n>=0?w[n]?.name:void 0},getOperator:t=>c.get(t)}),r.pred&&typeof r.pred=="object"&&G(r.pred);for(const t of r.components??[])G(t)};for(const r of e.preds??[])G(r);const x=[...w,...(e.preds??[]).map((r,t)=>Ie(r,c,_,D,B,f,o,d.resolveSchema,I,l.get(t)))],Z=r=>Object.fromEntries(Object.entries(r).map(([t,n])=>{if((t==="$and"||t==="$or")&&Array.isArray(n))return[t,n.map(p=>Z(p))];const i=x.find(({name:p})=>p===t)?.outputProperty.comparable;return i&&he(n,t,i.values),[t,i?{kind:"ordinal-query",comparable:i,condition:s(n)}:s(n)]})),V=E?h(E):void 0;u(V);const Y=r=>{u(r.query),r.pred&&typeof r.pred=="object"&&Y(r.pred);for(const t of r.components??[])Y(t)};for(const r of e.preds??[])Y(r);if(x.length===0)throw new m("EMPTY_PROJECTION","LogicForm must contain preds or groupby");Se(x);const K=new Set(x.map(({name:r})=>r)),pe=w.length>0?{kind:"group",names:w.map(({name:r})=>r)}:x.every(({expression:r})=>r.kind==="column")?(()=>{const r=o.properties.find(({type:t})=>t==="ID");return r&&(d.canUsePropertyRowIdentity?.(o,r)??!0)?{kind:"property",column:r.id,internalName:Pe(K)}:{kind:"generated"}})():{kind:"singleton"},W=Object.entries(e.sort??{}).map(([r,t])=>{if(!K.has(r))throw new m("INVALID_SORT",`Sort field is not an output: ${r}`);const n=x.find(i=>i.name===r);return{name:r,direction:t===1?"ASC":"DESC",...n?.outputProperty.comparable?{comparable:n.outputProperty.comparable,expression:n.expression}:{}}}),ee=e.limit===void 0?void 0:e.limit>0&&e.limit<1?{kind:"ratio",page:e.page??1,ratio:e.limit}:{kind:"rows",page:e.page??1,pageSize:e.limit},re=e.limitBy===void 0?void 0:{count:e.limitBy,partitionBy:w.slice(0,-1).map(({name:r})=>r),orderBy:W.length>0?W:(()=>{const r=w.at(-1);return[{name:r?.name??"",direction:"ASC",...r?.outputProperty.comparable?{comparable:r.outputProperty.comparable,expression:r.expression}:{}}]})()};return{schemaId:o.id,source:g.mapping.source,...g.mapping.sourceSql?{sourceSql:g.mapping.sourceSql}:{},mappingId:g.mapping.id??g.mapping.source,sourceAlias:T,fields:{...me(o),...Object.fromEntries(o.properties.flatMap(r=>{const t=ne(g.mapping,o,r.name);return t?[[r.name,t],[r.id,t]]:[]}))},fieldReferences:Object.fromEntries(A),joins:[...S.values()],arrayExpansions:[...b.values()],projections:x.map(({name:r,expression:t})=>({name:r,expression:t})),columnProperties:x.map(({outputProperty:r})=>r),groupBy:w.map(({name:r,expression:t})=>({name:r,expression:t})),...V?{query:f(V)}:{},...e.having?{having:Z(e.having)}:{},orderBy:W,rowIdentity:pe,...ee?{pagination:ee}:{},...re?{groupLimit:re}:{}}};export{ie as createDerivedSourceSchema,F as createLogicalPlan,oe as createResultSchema};
@@ -1 +0,0 @@
1
- import{SemanticDBError as M}from"../errors.js";import{clone as v}from"../utils/clone.js";const C=e=>e.id??e.source,h=(e,r)=>{if(e===r)return!0;if(e instanceof Date||r instanceof Date)return e instanceof Date&&r instanceof Date&&e.getTime()===r.getTime();if(Array.isArray(e)||Array.isArray(r))return Array.isArray(e)&&Array.isArray(r)&&e.length===r.length&&e.every((o,s)=>h(o,r[s]));if(typeof e!="object"||e===null||typeof r!="object"||r===null)return!1;const t=Object.entries(e),n=r;return t.length===Object.keys(n).length&&t.every(([o,s])=>Object.prototype.hasOwnProperty.call(n,o)&&h(s,n[o]))},a=e=>{if(!e)return[];const r=[];for(const[t,n]of Object.entries(e))if(n!==void 0){if(t==="$or")return;if(t==="$and"){if(!Array.isArray(n))return;for(const o of n){const s=a(o);if(!s)return;r.push(...s)}continue}if(t.startsWith("$"))return;r.push({property:t,condition:n})}return r},$=(e,r)=>{if(!e)return;const t={};for(const[n,o]of Object.entries(e))if(o!==void 0){if(n==="$and"&&Array.isArray(o)){const s=o.map(d=>$(d,r)).filter(d=>d!==void 0);s.length>0&&(t[n]=s);continue}n!=="$or"&&r.some(s=>s.property===n&&h(s.condition,o))||(t[n]=o)}return Object.keys(t).length>0?t:void 0},b=(e,r)=>e.properties.find(({id:t,name:n})=>t===r||n===r),O=(e,r,t)=>{const n=b(r,t);if(n)return e.properties?e.properties[n.name]??e.properties[n.id]:n.id},I=(e,r,t)=>e.properties===void 0||O(e,r,t)!==void 0,R=(e,r,t)=>{if(!e||r.properties===void 0)return;const n=a(e);if(!n)return"query contains an unsupported logical expression";const o=n.find(({property:s})=>!I(r,t,s));return o?`query property is not available: ${o.property}`:void 0},q=e=>[...typeof e.pred=="string"?[e.pred]:e.pred&&typeof e.pred=="object"?q(e.pred):[],...e.components?.flatMap(q)??[]],w=(e,r,t,n,o)=>{if(e.match.schema!==void 0&&e.match.schema!==n)return!1;const s=typeof r.pred=="string"?b(t,r.pred):void 0,d=b(t,e.match.pred),i=r.pred===e.match.pred||!!(s&&d&&s.id===d.id);if(r.operator!==e.match.operator||!i||r.components||r.args&&Object.keys(r.args).length>0)return!1;const c=a(e.match.query);return c!==void 0&&c.every(u=>o.some(p=>p.property===u.property&&h(p.condition,u.condition)))},D=(e,r,t)=>{if(t.predMappings===void 0&&t.properties===void 0)return{mapping:t,logicform:e,predRewrites:[],priority:t.priority??0,specificity:0};const n=a(e.query);if(!n&&t.predMappings)return"query contains $or or another unsupported logical expression";const o=v(e),s=[],d=[];for(const[u,p]of(e.preds??[]).entries()){const f=a(p.query);if(!f&&t.predMappings)return`PredItem ${u} query contains an unsupported logical expression`;if(t.predMappings){const A=[...n??[],...f??[]],P=t.predMappings.filter(m=>w(m,p,r,p.schema??r.id,A));if(P.length===0)return`PredItem ${u} is not mapped`;if(P.length>1)return`PredItem ${u} matches multiple mapping rules`;const g=P[0],j=a(g.match.query)??[];d.push(...j);const l=o.preds?.[u];if(l){const m=$(l.query,j);m?l.query=m:delete l.query}s.push({predIndex:u,column:g.column});continue}const y=q(p).find(A=>!I(t,r,A));if(y)return`PredItem ${u} property is not available: ${y}`}const i=$(o.query,d);i?o.query=i:delete o.query;const c=R(o.query,t,r);if(c)return c;for(const[u,p]of(o.preds??[]).entries()){const f=R(p.query,t,r);if(f)return`PredItem ${u} ${f}`}for(const u of o.groupby??[]){const f=q(u).find(y=>!I(t,r,y));if(f)return`groupby property is not available: ${f}`}return{mapping:t,logicform:o,predRewrites:s,priority:t.priority??0,specificity:s.length}},E=(e,r,t)=>{const n=[],o=[];for(const i of t.list(r.id)){const c=D(e,r,i);typeof c=="string"?o.push({mappingId:C(i),reason:c}):n.push(c)}if(n.length===0)throw new M("QUERY_NOT_COVERED_BY_DATA_SOURCE","\u5F53\u524D\u63A5\u5165\u7684\u6570\u636E\u4E0D\u652F\u6301\u6B64\u95EE\u9898\u3002\u5982\u9700\u652F\u6301\uFF0C\u9700\u8981\u63A5\u5165\u660E\u7EC6\u5C42\u6570\u636E\uFF0C\u8BF7\u8054\u7CFB\u6570\u636E\u7BA1\u7406\u5458\u3002",{schemaId:r.id,requiredDataLayer:"detail",rejectedMappings:o});n.sort((i,c)=>c.priority-i.priority||c.specificity-i.specificity);const s=n[0],d=n.filter(({priority:i,specificity:c})=>i===s.priority&&c===s.specificity);if(d.length>1)throw new M("SCHEMA_MAPPING_AMBIGUOUS",`Multiple Schema mappings cover the LogicForm for ${r.id}`,{schemaId:r.id,mappingIds:d.map(({mapping:i})=>C(i))});return s};export{O as mappedPropertyColumn,E as selectSchemaMapping};
@@ -1 +0,0 @@
1
- const p=t=>{if(t.type!=="entity")return;const n=t.properties.find(e=>e.type==="timestamp"),r=t.properties.find(e=>e.type==="start_date"),i=t.properties.find(e=>e.type==="end_date");return n&&r&&i?{timestamp:n,start:r,end:i}:void 0};export{p as resolveLifecycleProperties};
@@ -1 +0,0 @@
1
- const s=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),c=t=>s(t)?t.$lte??t.$lt??t.$eq:t,f=(t,n)=>{if(!t)return t;const r=Object.entries(t).find(([i])=>i===n.timestamp.name);if(!r)return t;const[,m]=r,e=c(m);return e===void 0?t:{...Object.fromEntries(Object.entries(t).filter(([i])=>i!==n.timestamp.name)),[n.start.name]:t[n.start.name]??{$lte:e},[n.end.name]:t[n.end.name]??{$or:[{$exists:!1},{$gte:e}]}}};export{f as applyLifecycleQuery};
@@ -1 +0,0 @@
1
- import{resolveLifecycleProperties as p}from"./classification.js";import{applyLifecycleQuery as c}from"./query-policy.js";const l={name:"lifecycle",resolveQuery({logicform:e,schema:r,query:o}){const t=p(r);return!t||e.groupby?.some(i=>typeof i.pred=="string"&&i.pred===t.timestamp.name)?o:c(o,t)},resolveProjection({schema:e,outputProperty:r}){if(p(e))return{outputProperty:{...r,temporal:{kind:"lifecycle"}}}}};export{l as lifecycleSemanticRule};
@@ -1 +0,0 @@
1
- const o=(t,e)=>!!(t&&e?.temporalSemantics==="snapshot"&&t.type!=="timestamp");export{o as isObservationProperty};
@@ -1 +0,0 @@
1
- import{SemanticDBError as i}from"../../../errors.js";const e="$periodBoundary",n=(t,r)=>{const o=r?.observationPolicy?.({pred:t});if(o)return{operator:e,...o};if(r?.kind==="aggregate")throw new i("OBSERVATION_REQUIRES_PERIOD_BOUNDARY",`Observation metrics must use ${e}; ${r.name} describes a time range`,{operator:r.name});return{operator:e,boundary:"end",implicit:!0}};export{n as resolveObservationOperatorPolicy};
@@ -1 +0,0 @@
1
- import{isObservationProperty as p}from"./classification.js";import{resolveObservationOperatorPolicy as s}from"./operator-policy.js";const b={name:"observation",resolveProjection({pred:r,schema:e,sourceProperty:o,outputProperty:t,operator:n}){if(!o||!p(o,e))return;const i=o,a=s(r,n);return{outputProperty:{...t,temporal:{kind:"period-boundary",boundary:a.boundary,sourceProperty:i.name}}}}};export{b as observationSemanticRule};
@@ -1 +0,0 @@
1
- import{observationSemanticRule as e}from"./observation/rule.js";import{lifecycleSemanticRule as r}from"./lifecycle/rule.js";import{PlannerSemanticRegistry as t}from"./registry.js";const i=()=>new t([e,r]);export{i as createPlannerSemanticRegistry};
@@ -1 +0,0 @@
1
- import{SemanticDBError as s}from"../../errors.js";class o{#e=new Map;constructor(e=[]){for(const r of e)this.register(r)}register(e){if(!e.name)throw new s("INVALID_SEMANTIC_RULE","Semantic rule name must not be empty");if(this.#e.has(e.name))throw new s("SEMANTIC_RULE_ALREADY_REGISTERED",`Semantic rule is already registered: ${e.name}`,{rule:e.name});return this.#e.set(e.name,e),this}resolveProjection(e){return[...this.#e.values()].reduce((r,t)=>t.resolveProjection?.({...e,outputProperty:r})?.outputProperty??r,e.outputProperty)}resolveQuery(e){return[...this.#e.values()].reduce((r,t)=>t.resolveQuery?.({...e,...r?{query:r}:{}})??r,e.query)}rules(){return[...this.#e.values()]}}export{o as PlannerSemanticRegistry};
@@ -1 +0,0 @@
1
- const o=r=>typeof r=="object"&&r!==null&&!Array.isArray(r)&&r.kind==="logicform-subquery"&&typeof r.plan=="object"&&r.plan!==null,i=r=>typeof r=="object"&&r!==null&&!Array.isArray(r)&&r.kind==="recursive-query",y=r=>typeof r=="object"&&r!==null&&!Array.isArray(r)&&r.kind==="ordinal-query";export{y as isLogicalOrdinalQuery,o as isLogicalQuerySubquery,i as isLogicalRecursiveQuery};
@@ -1 +0,0 @@
1
- import{SemanticDBError as h}from"../../errors.js";const s=({source:o,properties:y})=>{const t=o.hierarchy;if(!Array.isArray(t))return t===void 0?{}:{hierarchy:t};let n=o.hierarchy_property;if(typeof n!="string"||n.length===0){const r=y.filter(({type:c})=>c==="ID");if(r.length!==1)throw new h("LEGACY_HIERARCHY_ID_PROPERTY_REQUIRED","Legacy Schema hierarchy without hierarchy_property must contain exactly one ID property",{idPropertyCount:r.length});const e=r[0];n=e?.id??e?.name}const i=t.map(r=>{if(typeof r!="object"||r===null||Array.isArray(r))return;const e=r;if(!(typeof e.name!="string"||!Number.isInteger(e.code_length)))return{name:e.name,...Array.isArray(e.syno)?{synonyms:e.syno}:{},codeLength:e.code_length}});if(i.some(r=>r===void 0))return{};const a=t[0];return{hierarchy:{property:n,storage:a?.use_full_length===!0?"zero-padded":"compact",levels:i}}};export{s as normalizeLegacyHierarchy};
@@ -1 +0,0 @@
1
- import{SemanticDBError as o}from"../../errors.js";const i=r=>{if(!r.hierarchy)return;const e=r.properties.find(({name:t})=>t===r.hierarchy?.property);if(!e)throw new o("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${r.hierarchy.property}`,{schemaId:r.id,property:r.hierarchy.property});return e};export{i as resolveHierarchyEntityFilterProperty};
@@ -1 +0,0 @@
1
- import{normalizeLegacyHierarchy as r}from"./compatibility.js";import{resolveHierarchyEntityFilterProperty as e}from"./entity-identity.js";import{hierarchyLevelOperator as a}from"./operator.js";import{hierarchySchemaMetadata as t}from"./resolve-schema.js";const o=Object.freeze({name:"hierarchy",schemaMetadata:t,legacySchemaKeys:["hierarchy_property"],normalizeLegacySchema:r,resolveEntityFilterProperty:e,operators:[a]});export{o as hierarchyPlugin};
@@ -1 +0,0 @@
1
- import{SemanticDBError as i}from"../../errors.js";import{resolvePropertyPath as y}from"../../schema/resolve-property-path.js";const d=(n,t,o)=>{const e=y(n,t,o);if(e.property.primal_type!=="object")return{schema:e.schema,reference:e.canonicalName,relation:!1};if(e.property.isArray)throw new i("ARRAY_HIERARCHY_RELATION_UNSUPPORTED",`$hierarchyLevel cannot group an array relation: ${e.canonicalName}`);if(!e.property.ref||!o)throw new i("SCHEMA_RESOLVER_REQUIRED",`$hierarchyLevel requires a Schema resolver for relation ${e.canonicalName}`);return{schema:o(e.property.ref),reference:e.canonicalName,relation:!0}},f={name:"$hierarchyLevel",defaultName:({operandName:n,args:t,locale:o})=>{const e=typeof t.level=="string"?t.level:"";return o.toLowerCase().startsWith("en")?`${n}${e?` ${e}`:""} level`:`${n}${e}\u5C42\u7EA7`},kind:"scalar",planInput({reference:n,args:t,schema:o,resolveSchema:e}){const h=Object.keys(t).filter(a=>a!=="level");if(h.length>0||typeof t.level!="string"||t.level.length===0)throw new i("INVALID_HIERARCHY_LEVEL_ARGS","$hierarchyLevel args must contain exactly one non-empty level string",{unsupportedArgs:h});const r=d(o,n,e),c=r.schema.hierarchy;if(!c)throw new i("SCHEMA_HIERARCHY_REQUIRED",`Schema ${r.schema.id} does not declare hierarchy`,{schemaId:r.schema.id});const l=r.schema.properties.find(({name:a})=>a===c.property);if(!l)throw new i("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${c.property}`);if(!r.relation&&l.name!==y(o,n,e).property.name)throw new i("HIERARCHY_PROPERTY_REQUIRED",`$hierarchyLevel pred must be an object relation or hierarchy property ${l.name}`);let s=0;const p=c.levels.find(a=>(s+=a.codeLength,a.name===t.level||a.synonyms?.includes(t.level)));if(!p)throw new i("HIERARCHY_LEVEL_NOT_FOUND",`Schema ${r.schema.id} does not declare hierarchy level: ${t.level}`,{schemaId:r.schema.id,level:t.level});const R=c.levels.reduce((a,u)=>a+u.codeLength,0),m=r.schema.properties.filter(({type:a})=>a==="ID");return{reference:r.relation&&m.length===1&&m[0]?.name===l.name?r.reference:r.relation?`${r.reference}_${l.name}`:r.reference,args:{level:p.name,codeLength:s,totalLength:R,storage:c.storage}}},toSQL({expression:n,args:t,sql:o}){if(!n)throw new Error("$hierarchyLevel requires a hierarchy pred");const e=t.codeLength,h=t.totalLength,r=t.storage;if(!Number.isInteger(e)||!Number.isInteger(h)||Number(e)<=0||Number(h)<Number(e)||r!=="compact"&&r!=="zero-padded")throw new i("INVALID_HIERARCHY_LEVEL_PLAN","$hierarchyLevel must be resolved by the planner before SQL compilation");const c=o.substring(n,1,Number(e)),l=Number(h)-Number(e);return r==="zero-padded"&&l>0?o.concat([c,o.value("0".repeat(l))]):c},getOutputProperty({name:n}){return{name:n,type:"string",primal_type:"string",isArray:!1}}};export{f as hierarchyLevelOperator};
@@ -1 +0,0 @@
1
- import{SemanticDBError as r}from"../../errors.js";const H={keys:["hierarchy"],resolve(m,R){if("hierarchy_property"in m)throw new r("LEGACY_HIERARCHY_PROPERTY_NOT_ALLOWED","Schema hierarchy must declare hierarchy.property instead of hierarchy_property");const s=m.hierarchy;if(s===void 0)return{};if(typeof s!="object"||s===null||Array.isArray(s))throw new r("INVALID_HIERARCHY","Schema hierarchy must be an object containing property, levels, and optional storage");const n=s,l=Object.keys(n).filter(o=>o!=="property"&&o!=="storage"&&o!=="levels");if(l.length>0)throw new r("UNSUPPORTED_HIERARCHY_FIELD","Schema hierarchy only supports property, storage, and levels",{unsupportedKeys:l});if(typeof n.property!="string"||n.property.length===0)throw new r("HIERARCHY_PROPERTY_REQUIRED","Schema hierarchy.property must be a non-empty property name or id");const a=R.find(o=>o.name===n.property||o.id===n.property);if(!a)throw new r("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${n.property}`,{property:n.property});if(a.primal_type!=="string")throw new r("INVALID_HIERARCHY_PROPERTY",`Hierarchy property ${a.name} must have primal_type string`,{property:a.name,primal_type:a.primal_type});const y=n.storage??"compact";if(y!=="compact"&&y!=="zero-padded")throw new r("INVALID_HIERARCHY_STORAGE","Schema hierarchy.storage must be compact or zero-padded");if(!Array.isArray(n.levels)||n.levels.length===0)throw new r("HIERARCHY_LEVELS_REQUIRED","Schema hierarchy.levels must be a non-empty array");const h=new Set,p=new Set,_=n.levels.map((o,i)=>{if(typeof o!="object"||o===null||Array.isArray(o))throw new r("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${i} must be an object`);const e=o,E=Object.keys(e).filter(t=>t!=="name"&&t!=="synonyms"&&t!=="codeLength");if(E.length>0)throw new r("UNSUPPORTED_HIERARCHY_LEVEL_FIELD",`Hierarchy level ${i} only supports name, synonyms, and codeLength`,{unsupportedKeys:E});if(typeof e.name!="string"||e.name.length===0)throw new r("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${i} name must not be empty`);if(h.has(e.name)||p.has(e.name))throw new r("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level name: ${e.name}`);if(!Number.isInteger(e.codeLength)||Number(e.codeLength)<=0)throw new r("INVALID_HIERARCHY_CODE_LENGTH",`Hierarchy level ${e.name} codeLength must be a positive integer`);if(e.synonyms!==void 0&&(!Array.isArray(e.synonyms)||e.synonyms.some(t=>typeof t!="string"||t.length===0)))throw new r("INVALID_HIERARCHY_SYNONYMS",`Hierarchy level ${e.name} synonyms must contain only non-empty strings`);const c=e.synonyms??[];for(const t of c){if(t===e.name||h.has(t)||p.has(t))throw new r("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level alias: ${t}`);p.add(t)}return h.add(e.name),{name:e.name,...c.length>0?{synonyms:[...c]}:{},codeLength:Number(e.codeLength)}});return{hierarchy:{property:a.name,storage:y,levels:_}}}};export{H as hierarchySchemaMetadata};
@@ -1 +0,0 @@
1
- import{hierarchyPlugin as l}from"./hierarchy/index.js";import{SemanticDBError as n}from"../errors.js";const i=Object.freeze([l]),E=(m=[])=>{const t=[...i,...m],r=new Set,o=new Set,s=new Set;for(const e of t){if(!e.name)throw new n("INVALID_PLUGIN","Plugin name must not be empty");if(r.has(e.name))throw new n("PLUGIN_ALREADY_REGISTERED",`Plugin is already registered: ${e.name}`,{plugin:e.name});r.add(e.name);for(const a of[...e.schemaMetadata?.keys??[],...e.legacySchemaKeys??[]]){if(!a)throw new n("INVALID_PLUGIN_METADATA_KEY","Plugin metadata key must not be empty");if(o.has(a))throw new n("PLUGIN_METADATA_KEY_ALREADY_REGISTERED",`Plugin Schema metadata key is already registered: ${a}`,{key:a,plugin:e.name});o.add(a)}for(const a of e.operators??[]){if(s.has(a.name))throw new n("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${a.name}`,{operator:a.name,plugin:e.name});s.add(a.name)}}return Object.freeze(t)};export{i as builtinPlugins,E as resolvePlugins};
@@ -1 +0,0 @@
1
- import{SemanticDBError as i}from"../errors.js";import{resolvePlugins as p}from"../plugins/index.js";const s=t=>typeof t=="string"&&t.length>0&&t!=="placeholder",n=t=>{const r=t.properties.filter(({type:e})=>e==="ID");if(r.length!==1)throw new i("ENTITY_ID_PROPERTY_REQUIRED",`Schema ${t.id} must contain exactly one ID property to use entity_id`,{schemaId:t.id,idPropertyCount:r.length});return r[0]},l=(t,r=[])=>{for(const e of p(r)){const o=e.resolveEntityFilterProperty?.(t);if(o)return o}return n(t)};export{s as isConcreteEntityId,l as resolveEntityFilterProperty,n as resolveEntityIdProperty};
@@ -1 +0,0 @@
1
- import{SemanticDBError as o}from"../errors.js";const p=(a,n)=>a.properties.some(i=>i!==n&&i.id===n.name)?n.id:n.name,l=(a,n)=>a.properties.flatMap(i=>[...n.startsWith(`${i.id}_`)?[{property:i,prefix:i.id}]:[],...i.name!==i.id&&n.startsWith(`${i.name}_`)?[{property:i,prefix:i.name}]:[]]).sort((i,s)=>s.prefix.length-i.prefix.length||(s.prefix===s.property.id?1:0)-(i.prefix===i.property.id?1:0)),c=(a,n,i)=>{const s=a.properties.find(t=>t.id===n)??a.properties.find(t=>t.name===n);if(s)return{canonicalName:p(a,s),canonicalId:s.id,schema:a,property:s,relations:[]};for(const{property:t,prefix:d}of l(a,n)){if(t.primal_type!=="object"||!t.ref)continue;if(!i)throw new o("SCHEMA_RESOLVER_REQUIRED",`Resolving property path ${n} requires a Schema resolver`);const e=i(t.ref),r=c(e,n.slice(d.length+1),i);return{canonicalName:`${p(a,t)}_${r.canonicalName}`,canonicalId:`${t.id}_${r.canonicalId}`,schema:r.schema,property:r.property,relations:[{sourceSchema:a,property:t,targetSchema:e},...r.relations]}}throw new o("PROPERTY_NOT_FOUND",`Property path not found in ${a.id}: ${n}`,{schemaId:a.id,property:n})};export{c as resolvePropertyPath};
@@ -1 +0,0 @@
1
- import{SemanticDBError as r}from"../errors.js";const o=(t,e)=>{const i=e[t];if(!i)throw new r("SCHEMA_NOT_FOUND",`Schema not found: ${t}`,{schemaId:t});if("_id"in i||"_sid"in i)throw new r("LEGACY_SCHEMA_ID_NOT_ALLOWED","Schema must use id instead of _id; _sid is not supported",{schemaId:t});if("sid"in i)throw new r("SCHEMA_SID_NOT_ALLOWED","Schema must not declare sid",{schemaId:t});if(i.id!==t)throw new r("SCHEMA_ID_MISMATCH",`Schema registry key ${t} does not match schema.id ${i.id}`,{registryKey:t,schemaId:i.id});return i},d=(t,e)=>{const i=t.properties.find(n=>n.id===e)??t.properties.find(n=>n.name===e);if(!i)throw new r("PROPERTY_NOT_FOUND",`Property not found in ${t.id}: ${e}`,{schemaId:t.id,property:e});return i},s=t=>{const e=t.properties.flatMap(i=>[[i.name,i.id],[i.id,i.id]]);return Object.freeze(Object.fromEntries(e))};export{s as buildFieldMap,d as getProperty,o as getSchema};
@@ -1 +0,0 @@
1
- import{SemanticDBError as n}from"../errors.js";const m=/^(\d{2}):(\d{2})(?::(\d{2}))?$/,o=t=>{const e=m.exec(t);if(!e)return;const r=Number(e[1]),s=Number(e[2]),i=Number(e[3]??0);if(!(r>23||s>59||i>59))return{hour:r,minute:s,second:i}},c=t=>{const e=t.freshness;if(e){if(e.mode==="ttl"){if(!Number.isInteger(e.ttlSeconds)||e.ttlSeconds<=0)throw new n("INVALID_SOURCE_FRESHNESS","TTL freshness requires a positive integer ttlSeconds");return}if(e.mode==="daily"){if(!o(e.expireAt))throw new n("INVALID_SOURCE_FRESHNESS","Daily freshness expireAt must use HH:mm or HH:mm:ss");if(e.timeZone)try{new Intl.DateTimeFormat("en-US",{timeZone:e.timeZone}).format()}catch{throw new n("INVALID_SOURCE_FRESHNESS",`Invalid freshness timeZone: ${e.timeZone}`)}}}};export{o as parseDailyExpireAt,c as validateSourceFreshness};
@@ -1 +0,0 @@
1
- import{SemanticDBError as s}from"../errors.js";import{validateSourceFreshness as m}from"./freshness.js";class o{#e=new Map;constructor(e=[]){for(const r of e)this.register(r)}register(e){if(!e.schemaId)throw new s("INVALID_SCHEMA_MAPPING","Schema mapping schemaId must not be empty");if(!e.source)throw new s("INVALID_SCHEMA_MAPPING","Schema mapping source must not be empty");if(e.sourceSql!==void 0&&e.sourceSql.trim().length===0)throw new s("INVALID_SCHEMA_MAPPING","Schema mapping sourceSql must not be empty");if(e.id!==void 0&&!e.id)throw new s("INVALID_SCHEMA_MAPPING","Schema mapping id must not be empty");if(e.connectionId.trim().length===0)throw new s("INVALID_SCHEMA_MAPPING","Schema mapping connectionId must not be empty");if(e.priority!==void 0&&!Number.isFinite(e.priority))throw new s("INVALID_SCHEMA_MAPPING","Schema mapping priority must be finite");for(const t of e.predMappings??[])if(!t.match.operator||!t.match.pred||!t.column)throw new s("INVALID_SCHEMA_MAPPING","Schema mapping PredItem matches require operator, pred, and column");m(e);const r=this.#e.get(e.schemaId)??[],p=e.id??e.source;if(r.some(t=>(t.id??t.source)===p||t.source===e.source))throw new s("SCHEMA_MAPPING_ALREADY_REGISTERED",`Schema mapping is already registered: ${e.schemaId}:${p}`,{schemaId:e.schemaId,mappingId:p});return this.#e.set(e.schemaId,[...r,e]),this}get(e){const r=this.list(e);if(r.length===1)return r[0];const p=r.filter(t=>t.predMappings===void 0&&t.properties===void 0);if(p.length===1)return p[0];throw new s("SCHEMA_MAPPING_AMBIGUOUS",`Schema ${e} has multiple mappings and requires LogicForm-based selection`,{schemaId:e,mappingIds:r.map(t=>t.id??t.source)})}list(e){const r=this.#e.get(e);if(!r||r.length===0)throw new s("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${e}`,{schemaId:e});return r}findSource(e,r){return this.#e.get(e)?.find(p=>p.source===r)}}export{o as SchemaMappingRegistry};
@@ -1 +0,0 @@
1
- const o={name:"boolean",primalType:"boolean",hydrateResult(e){return typeof e=="number"?e===1:e}};export{o as booleanSemanticType};
@@ -1 +0,0 @@
1
- const e={name:"category",primalType:"string"};export{e as categorySemanticType};
@@ -1 +0,0 @@
1
- const e={name:"currency",primalType:"number"};export{e as currencySemanticType};
@@ -1 +0,0 @@
1
- const e={name:"date",primalType:"date"};export{e as dateSemanticType};
@@ -1 +0,0 @@
1
- const e={name:"duration",primalType:"number"};export{e as durationSemanticType};
@@ -1 +0,0 @@
1
- const e={name:"end_date",primalType:"date"};export{e as endDateSemanticType};
@@ -1 +0,0 @@
1
- import{hydrateObjectResult as t}from"./object.js";const e={name:"entity",primalType:"object",hydrateResult:t};export{e as entitySemanticType};
@@ -1 +0,0 @@
1
- const e={name:"file",primalType:"string"};export{e as fileSemanticType};
@@ -1 +0,0 @@
1
- const a={name:"humanName",primalType:"string"};export{a as humanNameSemanticType};
@@ -1 +0,0 @@
1
- const e={name:"ID",primalType:"string"};export{e as idSemanticType};
@@ -1 +0,0 @@
1
- const e={name:"image",primalType:"string"};export{e as imageSemanticType};
@@ -1 +0,0 @@
1
- import{booleanSemanticType as m}from"./boolean.js";import{categorySemanticType as e}from"./category.js";import{currencySemanticType as t}from"./currency.js";import{dateSemanticType as r}from"./date.js";import{durationSemanticType as i}from"./duration.js";import{endDateSemanticType as o}from"./end-date.js";import{entitySemanticType as p}from"./entity.js";import{fileSemanticType as a}from"./file.js";import{humanNameSemanticType as n}from"./human-name.js";import{idSemanticType as c}from"./id.js";import{imageSemanticType as y}from"./image.js";import{intSemanticType as f}from"./int.js";import{nameSemanticType as S}from"./name.js";import{numberSemanticType as T}from"./number.js";import{objectSemanticType as b}from"./object.js";import{orderSemanticType as d}from"./order.js";import{percentageSemanticType as s}from"./percentage.js";import{startDateSemanticType as u}from"./start-date.js";import{stringSemanticType as g}from"./string.js";import{timestampSemanticType as l}from"./timestamp.js";const j=Object.freeze([c,g,S,n,e,y,a,T,f,t,s,i,d,m,l,r,u,o,p,b]);export{j as builtinSemanticTypes};
@@ -1 +0,0 @@
1
- const e={name:"int",primalType:"number"};export{e as intSemanticType};
@@ -1 +0,0 @@
1
- const e={name:"name",primalType:"string"};export{e as nameSemanticType};
@@ -1 +0,0 @@
1
- const e={name:"number",primalType:"number"};export{e as numberSemanticType};
@@ -1 +0,0 @@
1
- const r=(e,{property:t,requestEntity:n})=>!t.ref||e===void 0||e===null||typeof e=="object"&&!Array.isArray(e)?e:n(t.ref,e),c={name:"object",primalType:"object",hydrateResult:r};export{r as hydrateObjectResult,c as objectSemanticType};
@@ -1 +0,0 @@
1
- const e={name:"order",primalType:"number"};export{e as orderSemanticType};
@@ -1 +0,0 @@
1
- const e={name:"percentage",primalType:"number"};export{e as percentageSemanticType};
@@ -1 +0,0 @@
1
- const t={name:"start_date",primalType:"date"};export{t as startDateSemanticType};
@@ -1 +0,0 @@
1
- const n={name:"string",primalType:"string"};export{n as stringSemanticType};
@@ -1 +0,0 @@
1
- const e={name:"timestamp",primalType:"date"};export{e as timestampSemanticType};
@@ -1 +0,0 @@
1
- import{builtinSemanticTypes as e}from"./builtins/index.js";import{SemanticTypeRegistry as t}from"./registry.js";import"./primal-types/date.js";const i=()=>new t(e);export{t as SemanticTypeRegistry,e as builtinSemanticTypes,i as createSemanticTypeRegistry};
@@ -1 +0,0 @@
1
- import o from"dayjs";import b from"dayjs/plugin/customParseFormat.js";import A from"dayjs/plugin/isoWeek.js";import k from"dayjs/plugin/quarterOfYear.js";import{SemanticDBError as p}from"../../errors.js";import{isLogicform as O}from"../../logicform-types.js";o.extend(b),o.extend(A),o.extend(k);const U="YYYY-MM-DD HH:mm:ss",h=new Set(["YTD","QTD","MTD","WTD","DTD"]),q=new Set(["$eq","$gt","$gte","$lt","$lte","$in","$nin","$and","$or"]),$=["second","minute","hour","day","week","month","quarter","year"],a=t=>Object.prototype.toString.call(t)==="[object Object]",D=t=>!a(t)||"$gte"in t||"$gt"in t||"$lte"in t||"$lt"in t||"$or"in t||"$ne"in t?!1:typeof t.granularity=="string"&&$.includes(t.granularity)&&typeof t.offset=="number"||$.some(r=>r in t),c=t=>o(t).format(U),P=(t,r)=>$.find(n=>n in t||r!==void 0),E=(t,r,n)=>r==="month"?t.month(n-1):r==="day"?t.date(n):r==="week"?t.isoWeek(n):r==="quarter"?t.quarter(n):t.set(r,n),l=(t,r)=>{const n=typeof t.granularity=="string"?t.granularity:void 0,e=n?{[n]:t.offset}:void 0,i=n??P(t,void 0)??"day";let s=o(r).millisecond(0);for(const f of[...$].reverse()){const d=t[f];typeof d=="number"&&(s=E(s,f,d));const m=e?.[f];typeof m=="number"&&m!==0&&(s=s.add(m,f))}const y=i==="week"?"isoWeek":i;return{$gte:c(s.startOf(y)),$lte:c(s.endOf(y))}},R=(t,r)=>{const n=o(r),i={DTD:()=>n.startOf("day"),WTD:()=>n.startOf("isoWeek"),MTD:()=>n.startOf("month"),QTD:()=>n.startOf("quarter"),YTD:()=>n.startOf("year")}[t];return{$gte:c(i()),$lte:c(n.endOf("day"))}},w=async(t,r)=>{const n=o(String(t.$lte)),e=o(r.now).endOf("day");if(!n.isAfter(e))return t;const s=await r.requestLatestDataDate()??r.now,y=r.property.granularity??"day",f=y==="week"?"isoWeek":y,d=o(s).endOf(f),m=d.isBefore(n)?d:n;return{...t,$lte:c(m)}},u=async(t,r)=>O(t)?t:t instanceof Date||typeof t=="string"&&o(t).isValid()?c(t):typeof t=="string"&&h.has(t)?w(R(t,r.now),r):D(t)?w(l(t,r.now),r):t,T=async(t,r,n)=>{if(t==="$and"||t==="$or")return Array.isArray(r)?Promise.all(r.map(i=>g(i,n))):r;if(Array.isArray(r))return Promise.all(r.map(i=>u(i,n)));const e=await u(r,n);return t==="$eq"&&a(e)&&"$gte"in e&&"$lte"in e?e:t==="$gte"||t==="$gt"?a(e)&&"$gte"in e?e.$gte:e:(t==="$lte"||t==="$lt")&&a(e)&&"$lte"in e?e.$lte:e},g=async(t,r)=>{if(O(t))return t;if(Array.isArray(t))return Promise.all(t.map(i=>g(i,r)));if(!a(t))return u(t,r);if("$options"in t)throw new p("UNSUPPORTED_QUERY_OPERATOR","$options is a LogicForm 1.x field; use args.options in LogicForm 2.0");if("$offset"in t)throw new p("UNSUPPORTED_DATE_VALUE","The legacy {$offset: ...} date form is not supported; use { granularity, offset }");if(("granularity"in t||"offset"in t)&&(!D(t)||!Number.isInteger(t.offset)))throw new p("INVALID_DATE_VALUE","Relative date values require one granularity and an integer offset");if(D(t))return w(l(t,r.now),r);const n=Object.entries(t);if(n.length===1&&n[0]?.[0]==="$eq"){const i=await T("$eq",n[0][1],r);if(a(i)&&"$gte"in i&&"$lte"in i)return i}const e={};for(const[i,s]of n)e[i]=q.has(i)?await T(i,s,r):await g(s,r);return e};export{g as normalizeDateQuery};
@@ -1 +0,0 @@
1
- import{normalizeDateQuery as t}from"./date.js";const i=(r,e)=>e.property.primal_type==="date"?t(r,e):r;export{i as normalizePrimalQuery};
@@ -1 +0,0 @@
1
- import{SemanticDBError as t}from"../errors.js";class s{#e=new Map;constructor(e=[]){for(const r of e)this.register(r)}register(e){if(!e.name)throw new t("INVALID_SEMANTIC_TYPE","Semantic type name must not be empty");if(this.#e.has(e.name))throw new t("SEMANTIC_TYPE_ALREADY_REGISTERED",`Semantic type is already registered: ${e.name}`,{type:e.name});return this.#e.set(e.name,e),this}get(e){const r=this.#e.get(e);if(!r)throw new t("SEMANTIC_TYPE_NOT_FOUND",`Semantic type is not registered: ${e}`,{type:e});return r}requiresPerPeriodEvaluation(e){return e.property?this.get(e.property.type).requiresPerPeriodEvaluation?.({...e,property:e.property})??!1:!1}}export{s as SemanticTypeRegistry};
@@ -1 +0,0 @@
1
- import{SemanticDBError as i}from"../errors.js";import{resolvePlugins as f}from"../plugins/index.js";import{validateResolvedSchema as y}from"./validate-resolved-schema.js";const c=new Set(["hour","day","week","month","quarter","year"]),A=(e,l)=>{if("_id"in e||"_sid"in e)throw new i("LEGACY_PROPERTY_ID_NOT_ALLOWED",`Property ${e.name} must use id instead of _id; _sid is not supported`,{property:e.name});if("sid"in e)throw new i("PROPERTY_SID_NOT_ALLOWED",`Property ${e.name} must not declare sid`,{property:e.name});const m=e;if(m.is_comparable!==void 0||m.comparable_order!==void 0)throw new i("LEGACY_COMPARABLE_NOT_ALLOWED",`Property ${e.name} must use comparable instead of is_comparable/comparable_order`,{property:e.name});if(e.udf!==void 0){const r=e.udf;if(typeof r!="object"||r===null||Array.isArray(r))throw new i("INVALID_PROPERTY_UDF",`Property ${e.name} udf must be an object containing only sql`,{property:e.name});const n=r,o=Object.keys(n).filter(d=>d!=="sql");if(o.length>0)throw new i("UNSUPPORTED_PROPERTY_UDF",`Property ${e.name} udf only supports sql`,{property:e.name,unsupportedKeys:o});if(typeof n.sql!="string"||n.sql.trim().length===0)throw new i("INVALID_PROPERTY_UDF",`Property ${e.name} udf.sql must be a non-empty string`,{property:e.name})}const s=l.get(e.type);if(e.primal_type!==void 0&&e.primal_type!==s.primalType)throw new i("PRIMAL_TYPE_MISMATCH",`Property ${e.name} declares primal_type ${e.primal_type}, but ${e.type} requires ${s.primalType}`,{property:e.name,type:e.type,declared:e.primal_type,expected:s.primalType});if(e.isArray!==void 0&&typeof e.isArray!="boolean")throw new i("INVALID_IS_ARRAY",`Property ${e.name} isArray must be a boolean`,{property:e.name,isArray:e.isArray});if("is_observation"in e)throw new i("LEGACY_TEMPORAL_SEMANTICS_NOT_ALLOWED",`Property ${e.name} must use Schema temporalSemantics; is_observation is not supported`,{property:e.name});if(e.comparable!==void 0){const r=e.comparable;if(typeof r!="object"||r===null||Array.isArray(r))throw new i("INVALID_COMPARABLE_CATEGORY",`Property ${e.name} comparable must contain values and direction`);const n=r;if(Object.keys(n).some(o=>o!=="values"&&o!=="direction")||!Array.isArray(n.values)||n.values.length===0||n.values.some(o=>typeof o!="string")||new Set(n.values).size!==n.values.length||n.direction!==1&&n.direction!==-1)throw new i("INVALID_COMPARABLE_CATEGORY",`Property ${e.name} comparable requires unique string values and direction 1 or -1`,{property:e.name,comparable:r});if(e.type!=="category"||e.isArray===!0)throw new i("COMPARABLE_CATEGORY_REQUIRED",`Property ${e.name} comparable is only supported by scalar category properties`,{property:e.name,type:e.type})}const t={...e,id:e.id??e.name,primal_type:s.primalType,isArray:e.isArray??!1,is_dynamic:e.udf?.sql!==void 0,...s.primalType==="date"?{granularity:e.granularity??"day"}:{}};if(s.primalType==="object"){if(typeof t.ref!="string"||t.ref.length===0)throw new i("PROPERTY_REF_REQUIRED",`Object property ${t.name} must declare ref`,{property:t.name,type:t.type})}else if(t.ref!==void 0)throw new i("PROPERTY_REF_NOT_ALLOWED",`Property ${t.name} cannot declare ref unless its primal_type is object`,{property:t.name,type:t.type});if(s.primalType==="date"){if(t.granularity!==void 0&&!c.has(t.granularity))throw new i("INVALID_GRANULARITY",`Property ${t.name} has unsupported granularity: ${t.granularity}`,{property:t.name,granularity:t.granularity})}else if(t.granularity!==void 0)throw new i("GRANULARITY_NOT_ALLOWED",`Property ${t.name} cannot declare granularity unless its primal_type is date`,{property:t.name,type:t.type});return s.validateProperty?.(t),t},P=(e,l,m=[])=>{const s=f(m);if("_id"in e||"_sid"in e)throw new i("LEGACY_SCHEMA_ID_NOT_ALLOWED","Schema must use id instead of _id; _sid is not supported");if("sid"in e)throw new i("SCHEMA_SID_NOT_ALLOWED","Schema must not declare sid");if("is_snapshot"in e||"is_observation"in e)throw new i("LEGACY_TEMPORAL_SEMANTICS_NOT_ALLOWED","Schema must use temporalSemantics instead of is_snapshot/is_observation",{schemaId:e.id});const t=e.temporalSemantics??"normal";if(t!=="normal"&&t!=="snapshot")throw new i("INVALID_TEMPORAL_SEMANTICS","Schema temporalSemantics must be normal or snapshot",{schemaId:e.id,temporalSemantics:t});const r=t;if(!e.id)throw new i("INVALID_SCHEMA_ID","Schema id must not be empty");let n=e.properties.map(a=>A(a,l));if(e.type==="entity"&&!n.some(({type:a})=>a==="timestamp")&&n.some(({type:a})=>a==="start_date")&&n.some(({type:a})=>a==="end_date")&&!n.some(({name:a})=>a==="\u65E5\u671F")){const a=n.find(({type:u})=>u==="start_date");a&&(n=[...n,{id:"__chatbi__timestamp__placeholder__",name:"\u65E5\u671F",type:"timestamp",primal_type:"date",isArray:!1,is_dynamic:!0,is_supplementary:!0,udf:{sql:a.id}}])}y(n,{temporalSemantics:r,schemaId:e.id});const o=s.flatMap(a=>a.schemaMetadata?[a.schemaMetadata]:[]);let d={};for(const a of o)d={...d,...a.resolve(e,n)};const _=e.parentProperty===void 0?void 0:n.find(({id:a,name:u})=>a===e.parentProperty||u===e.parentProperty);if(e.parentProperty!==void 0&&!_)throw new i("RECURSIVE_PARENT_PROPERTY_REQUIRED",`Schema parentProperty does not exist: ${e.parentProperty}`,{schemaId:e.id,property:e.parentProperty});const p=new Set(s.flatMap(a=>[...a.schemaMetadata?.keys??[],...a.legacySchemaKeys??[]]));return{...Object.fromEntries(Object.entries(e).filter(([a])=>a!=="parentProperty"&&!p.has(a))),temporalSemantics:r,properties:n,...d,..._?{parentProperty:_.name}:{}}};export{P as resolveSchema};
@@ -1 +0,0 @@
1
- import{SemanticDBError as a}from"../errors.js";const m=o=>{const r=new Set,t=new Set;for(const e of o){if(!e.name)throw new a("INVALID_PROPERTY_NAME","Property name must not be empty");if(!e.id)throw new a("INVALID_PROPERTY_ID",`Property ${e.name} physical id must not be empty`);if(r.has(e.name))throw new a("DUPLICATE_PROPERTY_NAME",`Duplicate property name: ${e.name}`,{property:e.name});if(t.has(e.id))throw new a("DUPLICATE_PROPERTY_ID",`Duplicate property physical id: ${e.id}`,{propertyId:e.id});r.add(e.name),t.add(e.id)}},n=(o,r={})=>{m(o);const t=o.filter(({type:e})=>e==="timestamp");if(t.length>1)throw new a("MULTIPLE_TIMESTAMP_PROPERTIES","A Schema can declare at most one timestamp Property",{properties:t.map(({name:e})=>e)});if(r.temporalSemantics==="snapshot"&&t.length===0)throw new a("SNAPSHOT_TIMESTAMP_REQUIRED","A snapshot Schema must declare exactly one timestamp Property",{schemaId:r.schemaId})};export{n as validateResolvedSchema};
@@ -1 +0,0 @@
1
- const o=e=>structuredClone(e);export{o as clone};