/* COPYRIGHT Esri - https://js.arcgis.com/5.0/LICENSE.txt */
import e from"../../../core/Error.js";import{WhereClauseCache as i}from"../../../core/sql/WhereClauseCache.js";import{kebabDict as r}from"../../support/fieldType.js";const s=new i(50,500),t="unsupported-query",n=" as ",o=new Set(["esriFieldTypeOID","esriFieldTypeSmallInteger","esriFieldTypeBigInteger","esriFieldTypeInteger","esriFieldTypeSingle","esriFieldTypeDouble","esriFieldTypeLong"]),a=new Set(["esriFieldTypeDate","esriFieldTypeDateOnly","esriFieldTypeTimeOnly","esriFieldTypeTimestampOffset"]),l=new Set(["esriFieldTypeString","esriFieldTypeGUID","esriFieldTypeGlobalID",...o,...a]);function d(i,r,n={}){const o=c(r,i);if(!o){const n=s.getError(r,i);throw new e(t,"invalid SQL expression",{expression:r,error:n})}const a=n.expressionName||"expression";if(n.validateStandardized&&!o.isStandardized)throw new e(t,`${a} is not standard`,{expression:r});if(n.validateAggregate&&!o.isAggregate)throw new e(t,`${a} does not contain a valid aggregate function`,{expression:r});return o.fieldNames}function p(e,i,r,s){if(!r)return!0;const t="where clause";return g(e,i,d(e,r,{validateStandardized:!0,expressionName:t}),{expressionName:t,query:s}),!0}function f(i,r,s,n,o){if(!s)return!0;const a="having clause",l=d(i,s,{validateAggregate:!0,expressionName:a});g(i,r,l,{expressionName:a,query:o});const p=c(s,i),f=p?.getExpressions().every(e=>{const{aggregateType:r,field:s}=e,t=i.get(s)?.name;return n.some(e=>{const{onStatisticField:s,statisticType:n}=e,o=i.get(s)?.name;return o===t&&n.toLowerCase().trim()===r})});if(!f)throw new e(t,"expressions in having clause should also exist in outStatistics",{having:s});return!0}function c(e,i){return e?s.get(e,i):null}function u(e){return/\((.*?)\)/.test(e)?e:e.split(n)[0]}function y(e){return e.split(n)[1]}function g(i,r,s,n={}){const o=new Map;if(m(o,i,r,n.allowedFieldTypes??l,s),o.size){const i=n.expressionName??"expression";throw new e(t,`${i} contains invalid or missing fields`,{errors:Array.from(o.values()),query:n.query})}}function m(e,i,r,s,t){const n=t.includes("*")?[...r,...t.filter(e=>"*"!==e)]:t;for(const a of n){if(i.get(a))T(e,i,r,s,a);else try{const t=d(i,u(a),{validateStandardized:!0});for(const n of t)T(e,i,r,s,n)}catch(o){e.set(a,{type:"expression-error",expression:a,error:o})}}}function T(e,i,s,t,n){const o=i.get(n);o?s.has(o.name)?"all"!==t&&!1===t?.has(o.type)&&e.set(n,{type:"invalid-type",fieldName:o.name,fieldType:r.fromJSON(o.type),allowedFieldTypes:Array.from(t,e=>r.fromJSON(e))}):e.set(n,{type:"missing-field",fieldName:o.name}):e.set(n,{type:"invalid-field",fieldName:n})}export{a as allDateAndTimeFieldTypes,y as getAliasFromFieldName,u as getExpressionFromFieldName,c as getWhereClause,o as numericFieldTypes,g as validateFields,f as validateHaving,p as validateWhere};
