analyzer.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557
  1. package analyzer
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/danfragoso/pizzasql-next/pkg/lexer"
  6. "github.com/danfragoso/pizzasql-next/pkg/parser"
  7. )
  8. // ErrorType categorizes analysis errors.
  9. type ErrorType int
  10. const (
  11. ErrUnknown ErrorType = iota
  12. ErrTableNotFound
  13. ErrTableExists
  14. ErrColumnNotFound
  15. ErrColumnAmbiguous
  16. ErrTypeMismatch
  17. ErrInvalidFunction
  18. ErrInvalidArgCount
  19. ErrAggregateInWhere
  20. ErrNonAggregateInSelect
  21. ErrInvalidGroupBy
  22. )
  23. // AnalysisError represents a semantic analysis error.
  24. type AnalysisError struct {
  25. Type ErrorType
  26. Message string
  27. Line int
  28. Column int
  29. Context string
  30. }
  31. func (e *AnalysisError) Error() string {
  32. if e.Line > 0 {
  33. return fmt.Sprintf("analysis error at line %d, column %d: %s", e.Line, e.Column, e.Message)
  34. }
  35. return fmt.Sprintf("analysis error: %s", e.Message)
  36. }
  37. // Analyzer performs semantic analysis on parsed SQL statements.
  38. type Analyzer struct {
  39. catalog *Catalog
  40. scope *Scope
  41. errors []*AnalysisError
  42. }
  43. // New creates a new Analyzer with the given catalog.
  44. func New(catalog *Catalog) *Analyzer {
  45. if catalog == nil {
  46. catalog = NewCatalog()
  47. }
  48. return &Analyzer{
  49. catalog: catalog,
  50. }
  51. }
  52. // Analyze performs semantic analysis on a statement.
  53. func (a *Analyzer) Analyze(stmt parser.Statement) error {
  54. a.errors = nil
  55. a.scope = NewScope(nil)
  56. switch s := stmt.(type) {
  57. case *parser.SelectStmt:
  58. return a.analyzeSelect(s)
  59. case *parser.InsertStmt:
  60. return a.analyzeInsert(s)
  61. case *parser.UpdateStmt:
  62. return a.analyzeUpdate(s)
  63. case *parser.DeleteStmt:
  64. return a.analyzeDelete(s)
  65. case *parser.CreateTableStmt:
  66. return a.analyzeCreateTable(s)
  67. case *parser.DropTableStmt:
  68. return a.analyzeDropTable(s)
  69. case *parser.AlterTableStmt:
  70. // ALTER TABLE is handled directly by executor, no semantic analysis needed
  71. return nil
  72. case *parser.AttachStmt:
  73. // ATTACH DATABASE is handled directly by executor
  74. return nil
  75. case *parser.DetachStmt:
  76. // DETACH DATABASE is handled directly by executor
  77. return nil
  78. case *parser.BeginStmt, *parser.CommitStmt, *parser.RollbackStmt,
  79. *parser.SavepointStmt, *parser.ReleaseStmt:
  80. // Transaction statements don't need semantic analysis
  81. return nil
  82. case *parser.AnalyzeStmt:
  83. // ANALYZE is a documented no-op; nothing to validate.
  84. return nil
  85. case *parser.CreateIndexStmt, *parser.DropIndexStmt:
  86. // Index statements don't need semantic analysis
  87. return nil
  88. case *parser.ListenStmt, *parser.UnlistenStmt, *parser.NotifyStmt:
  89. // Channel names and payloads are validated by the parser; there is no
  90. // schema or expression to analyze.
  91. return nil
  92. default:
  93. return &AnalysisError{
  94. Type: ErrUnknown,
  95. Message: fmt.Sprintf("unknown statement type: %T", stmt),
  96. }
  97. }
  98. }
  99. // GetCatalog returns the analyzer's catalog.
  100. func (a *Analyzer) GetCatalog() *Catalog {
  101. return a.catalog
  102. }
  103. // analyzeSelect analyzes a SELECT statement.
  104. func (a *Analyzer) analyzeSelect(stmt *parser.SelectStmt) error {
  105. // Register CTE names before resolving FROM so both the main query and the
  106. // recursive legs can reference them.
  107. for _, cte := range stmt.With {
  108. a.scope.DefineTable(cteTableInfo(cte))
  109. }
  110. // First, resolve tables in FROM clause
  111. if err := a.resolveFromClause(stmt.From); err != nil {
  112. return err
  113. }
  114. // Analyze WHERE clause
  115. if stmt.Where != nil {
  116. info, err := a.analyzeExpr(stmt.Where)
  117. if err != nil {
  118. return err
  119. }
  120. // WHERE clause cannot contain aggregates
  121. if info.IsAggregate {
  122. return &AnalysisError{
  123. Type: ErrAggregateInWhere,
  124. Message: "aggregate functions not allowed in WHERE clause",
  125. }
  126. }
  127. }
  128. // Determine if this is an aggregate query
  129. hasAggregate := false
  130. hasGroupBy := len(stmt.GroupBy) > 0
  131. // Analyze SELECT columns and collect aliases for GROUP BY/ORDER BY/HAVING
  132. // reference. SELECT aliases are registered before GROUP BY so a query may
  133. // group by an output alias, matching SQLite.
  134. selectAliases := make(map[string]*ExprInfo)
  135. for _, col := range stmt.Columns {
  136. if col.Star {
  137. // SELECT * - all columns from all tables
  138. continue
  139. }
  140. if col.TableStar != "" {
  141. // Qualified wildcard (table.*) - validate the qualifier names a
  142. // table or alias in scope; expansion happens at execution time.
  143. if err := a.validateTableStar(col.TableStar); err != nil {
  144. return err
  145. }
  146. continue
  147. }
  148. info, err := a.analyzeExpr(col.Expr)
  149. if err != nil {
  150. return err
  151. }
  152. if info.IsAggregate {
  153. hasAggregate = true
  154. }
  155. // Track column aliases so ORDER BY and HAVING can reference them
  156. if col.Alias != "" {
  157. selectAliases[strings.ToUpper(col.Alias)] = info
  158. }
  159. }
  160. // Register SELECT aliases as virtual columns for GROUP BY/ORDER BY/HAVING
  161. // reference
  162. for alias, info := range selectAliases {
  163. a.scope.DefineSelectAlias(alias, info.Type)
  164. }
  165. // Analyze GROUP BY expressions after aliases are in scope
  166. for _, expr := range stmt.GroupBy {
  167. if _, err := a.analyzeExpr(expr); err != nil {
  168. return err
  169. }
  170. }
  171. // Validate GROUP BY semantics
  172. if hasAggregate && !hasGroupBy {
  173. // Aggregate query without GROUP BY - all non-aggregate columns must be constants
  174. for _, col := range stmt.Columns {
  175. if col.Star {
  176. return &AnalysisError{
  177. Type: ErrNonAggregateInSelect,
  178. Message: "SELECT * not allowed with aggregate functions without GROUP BY",
  179. }
  180. }
  181. if col.TableStar != "" {
  182. return &AnalysisError{
  183. Type: ErrNonAggregateInSelect,
  184. Message: fmt.Sprintf("SELECT %s.* not allowed with aggregate functions without GROUP BY", col.TableStar),
  185. }
  186. }
  187. info, exprErr := a.analyzeExpr(col.Expr)
  188. if exprErr != nil || info == nil {
  189. continue
  190. }
  191. if !info.IsAggregate && !info.IsConstant {
  192. // Check if it's a simple column reference
  193. if ref, ok := col.Expr.(*parser.ColumnRef); ok {
  194. return &AnalysisError{
  195. Type: ErrNonAggregateInSelect,
  196. Message: fmt.Sprintf("column %q must appear in GROUP BY clause or be in an aggregate function", ref.Column),
  197. }
  198. }
  199. }
  200. }
  201. }
  202. // Analyze HAVING clause
  203. if stmt.Having != nil {
  204. info, err := a.analyzeExpr(stmt.Having)
  205. if err != nil {
  206. return err
  207. }
  208. // HAVING without GROUP BY requires aggregates
  209. if !hasGroupBy && !info.IsAggregate {
  210. return &AnalysisError{
  211. Type: ErrInvalidGroupBy,
  212. Message: "HAVING clause requires GROUP BY or aggregate function",
  213. }
  214. }
  215. }
  216. // Analyze ORDER BY
  217. for _, item := range stmt.OrderBy {
  218. if _, err := a.analyzeExpr(item.Expr); err != nil {
  219. return err
  220. }
  221. }
  222. // Analyze LIMIT/OFFSET
  223. if stmt.Limit != nil {
  224. info, err := a.analyzeExpr(stmt.Limit)
  225. if err != nil {
  226. return err
  227. }
  228. if !info.Type.IsNumeric() && info.Type != TypeNull {
  229. return &AnalysisError{
  230. Type: ErrTypeMismatch,
  231. Message: "LIMIT must be numeric",
  232. }
  233. }
  234. }
  235. if stmt.Offset != nil {
  236. info, err := a.analyzeExpr(stmt.Offset)
  237. if err != nil {
  238. return err
  239. }
  240. if !info.Type.IsNumeric() && info.Type != TypeNull {
  241. return &AnalysisError{
  242. Type: ErrTypeMismatch,
  243. Message: "OFFSET must be numeric",
  244. }
  245. }
  246. }
  247. return nil
  248. }
  249. // resolveFromClause adds tables from FROM clause to scope.
  250. func (a *Analyzer) resolveFromClause(tables []parser.TableRef) error {
  251. for _, ref := range tables {
  252. if err := a.defineTableRef(ref); err != nil {
  253. return err
  254. }
  255. // Handle JOINs
  256. if ref.Join != nil {
  257. if err := a.resolveJoin(ref.Join); err != nil {
  258. return err
  259. }
  260. }
  261. }
  262. return nil
  263. }
  264. // defineTableRef adds a single FROM/JOIN table to scope. The reference may be a
  265. // derived table (subquery), a CTE, or a real catalog table.
  266. func (a *Analyzer) defineTableRef(ref parser.TableRef) error {
  267. if ref.Function != nil {
  268. for _, arg := range ref.Function.Args {
  269. if _, err := a.analyzeExpr(arg); err != nil {
  270. return err
  271. }
  272. }
  273. a.scope.DefineTable(&TableInfo{
  274. Name: ref.Name,
  275. Alias: ref.Alias,
  276. Columns: tableFunctionColumns(ref.Function.Name),
  277. })
  278. return nil
  279. }
  280. if ref.Subquery != nil {
  281. if err := a.analyzeSelect(ref.Subquery); err != nil {
  282. return err
  283. }
  284. a.scope.DefineTable(a.derivedTableInfo(ref))
  285. return nil
  286. }
  287. if cte, ok := a.scope.LookupTable(ref.Name); ok {
  288. a.scope.DefineTable(&TableInfo{
  289. Name: cte.Name,
  290. Columns: cte.Columns,
  291. Alias: ref.Alias,
  292. IsView: cte.IsView,
  293. })
  294. return nil
  295. }
  296. table, ok := a.catalog.GetTable(ref.Name)
  297. if !ok {
  298. return &AnalysisError{
  299. Type: ErrTableNotFound,
  300. Message: fmt.Sprintf("table not found: %s", ref.Name),
  301. }
  302. }
  303. a.scope.DefineTable(&TableInfo{
  304. Name: table.Name,
  305. Columns: table.Columns,
  306. Alias: ref.Alias,
  307. IsView: table.IsView,
  308. })
  309. return nil
  310. }
  311. // derivedTableInfo builds the scope entry for a derived table. A compound
  312. // subquery (UNION/…) keeps its projection on the first leg. A wildcard expands
  313. // the columns of the subquery's source tables so callers can reference them.
  314. func (a *Analyzer) derivedTableInfo(ref parser.TableRef) *TableInfo {
  315. info := &TableInfo{Name: ref.Alias, Alias: ref.Alias}
  316. leg := firstSelectLeg(ref.Subquery)
  317. if leg == nil {
  318. return info
  319. }
  320. for _, col := range leg.Columns {
  321. if col.Star {
  322. for _, tref := range collectAllTableRefs(leg.From) {
  323. if t, ok := a.scope.LookupTable(tref.Name); ok {
  324. for _, c := range t.Columns {
  325. info.Columns = append(info.Columns, ColumnInfo{Name: c.Name, TableName: ref.Alias, Type: c.Type, Array: c.Array})
  326. }
  327. } else if t, ok := a.catalog.GetTable(tref.Name); ok {
  328. for _, c := range t.Columns {
  329. info.Columns = append(info.Columns, ColumnInfo{Name: c.Name, TableName: ref.Alias, Type: c.Type, Array: c.Array})
  330. }
  331. }
  332. }
  333. continue
  334. }
  335. name := ""
  336. switch {
  337. case col.Alias != "":
  338. name = col.Alias
  339. case col.Expr != nil:
  340. if colRef, ok := col.Expr.(*parser.ColumnRef); ok {
  341. name = colRef.Column
  342. }
  343. }
  344. if name == "" {
  345. name = fmt.Sprintf("col_%d", len(info.Columns))
  346. }
  347. info.Columns = append(info.Columns, ColumnInfo{Name: name, TableName: ref.Alias, Type: TypeAny})
  348. }
  349. return info
  350. }
  351. // collectAllTableRefs flattens a FROM list and its join chains.
  352. func collectAllTableRefs(from []parser.TableRef) []parser.TableRef {
  353. var refs []parser.TableRef
  354. var add func(parser.TableRef)
  355. add = func(ref parser.TableRef) {
  356. if ref.Subquery != nil {
  357. return
  358. }
  359. refs = append(refs, ref)
  360. if ref.Join != nil && ref.Join.Table != nil {
  361. add(*ref.Join.Table)
  362. }
  363. }
  364. for _, ref := range from {
  365. add(ref)
  366. }
  367. return refs
  368. }
  369. // cteTableInfo describes the columns a CTE exposes. The declared column list
  370. // wins; otherwise the anchor/first-leg projection names are used.
  371. func cteTableInfo(cte *parser.CTE) *TableInfo {
  372. leg := firstSelectLeg(cte.Query)
  373. info := &TableInfo{Name: cte.Name}
  374. if leg == nil {
  375. return info
  376. }
  377. for i, col := range leg.Columns {
  378. name := ""
  379. switch {
  380. case i < len(cte.Columns):
  381. name = cte.Columns[i]
  382. case col.Alias != "":
  383. name = col.Alias
  384. case col.Expr != nil:
  385. if ref, ok := col.Expr.(*parser.ColumnRef); ok {
  386. name = ref.Column
  387. }
  388. }
  389. if name == "" {
  390. name = fmt.Sprintf("col_%d", i)
  391. }
  392. info.Columns = append(info.Columns, ColumnInfo{
  393. Name: name,
  394. TableName: cte.Name,
  395. Type: TypeAny,
  396. })
  397. }
  398. return info
  399. }
  400. // firstSelectLeg returns the SELECT whose projection describes a (possibly
  401. // compound) subquery's output columns. A UNION/INTERSECT/EXCEPT keeps the
  402. // projection on its first leg.
  403. func firstSelectLeg(sel *parser.SelectStmt) *parser.SelectStmt {
  404. for sel != nil && sel.Compound != nil {
  405. sel = sel.Compound.Left
  406. }
  407. return sel
  408. }
  409. // validateTableStar checks that a qualified wildcard qualifier names a table or
  410. // alias present in scope, returning an error for unknown qualifiers instead of
  411. // silently falling back to a plain column expansion.
  412. func (a *Analyzer) validateTableStar(qualifier string) error {
  413. if _, ok := a.scope.LookupTable(qualifier); !ok {
  414. return &AnalysisError{
  415. Type: ErrTableNotFound,
  416. Message: fmt.Sprintf("no such table or alias: %s", qualifier),
  417. }
  418. }
  419. return nil
  420. }
  421. // resolveJoin resolves a JOIN clause.
  422. func (a *Analyzer) resolveJoin(join *parser.JoinClause) error {
  423. if join.Table == nil {
  424. return nil
  425. }
  426. if err := a.defineTableRef(*join.Table); err != nil {
  427. return err
  428. }
  429. // Analyze ON condition
  430. if join.Condition != nil {
  431. if _, err := a.analyzeExpr(join.Condition); err != nil {
  432. return err
  433. }
  434. }
  435. // Handle USING clause
  436. for _, colName := range join.Using {
  437. _, _, ok := a.scope.LookupColumn("", colName)
  438. if !ok {
  439. return &AnalysisError{
  440. Type: ErrColumnNotFound,
  441. Message: fmt.Sprintf("column not found in USING clause: %s", colName),
  442. }
  443. }
  444. }
  445. // Recursively handle chained JOINs
  446. if join.Table.Join != nil {
  447. if err := a.resolveJoin(join.Table.Join); err != nil {
  448. return err
  449. }
  450. }
  451. return nil
  452. }
  453. // analyzeInsert analyzes an INSERT statement.
  454. func (a *Analyzer) analyzeInsert(stmt *parser.InsertStmt) error {
  455. table, ok := a.catalog.GetTable(stmt.Table.Name)
  456. if !ok {
  457. return &AnalysisError{
  458. Type: ErrTableNotFound,
  459. Message: fmt.Sprintf("table not found: %s", stmt.Table.Name),
  460. }
  461. }
  462. a.scope.DefineTable(&TableInfo{Name: table.Name, Columns: table.Columns, IsView: table.IsView})
  463. // Validate column list if specified. Generated columns may never be written
  464. // explicitly.
  465. var targetCols []ColumnInfo
  466. if len(stmt.Columns) > 0 {
  467. for _, colName := range stmt.Columns {
  468. col, ok := table.GetColumn(colName)
  469. if !ok {
  470. return &AnalysisError{
  471. Type: ErrColumnNotFound,
  472. Message: fmt.Sprintf("column not found: %s", colName),
  473. }
  474. }
  475. if col.Generated {
  476. return &AnalysisError{
  477. Type: ErrTypeMismatch,
  478. Message: fmt.Sprintf("cannot INSERT into generated column %s", colName),
  479. }
  480. }
  481. targetCols = append(targetCols, *col)
  482. }
  483. } else {
  484. // Positional values map to the table's non-generated columns.
  485. for _, col := range table.Columns {
  486. if !col.Generated {
  487. targetCols = append(targetCols, col)
  488. }
  489. }
  490. }
  491. // An ON CONFLICT target names columns of the target table. An unknown name
  492. // must fail the statement rather than silently degrading to a scan. The
  493. // hidden rowid aliases are valid targets unless a real column shadows them.
  494. for _, colName := range stmt.ConflictTarget {
  495. if _, ok := table.GetColumn(colName); ok || isRowIDAlias(colName) {
  496. continue
  497. }
  498. return &AnalysisError{
  499. Type: ErrColumnNotFound,
  500. Message: fmt.Sprintf("column not found: %s", colName),
  501. }
  502. }
  503. // Validate VALUES. INSERT ... DEFAULT VALUES supplies no values at all, so
  504. // the placeholder empty row intentionally does not match the column count.
  505. // SQLite rejects the column-list form (INSERT INTO t (n) DEFAULT VALUES with
  506. // "0 values for 1 columns"); PizzaSQL accepts it and fills every column from
  507. // the schema defaults. This is a documented compatibility deviation.
  508. for _, row := range stmt.Values {
  509. if stmt.DefaultValues {
  510. continue
  511. }
  512. if len(row) != len(targetCols) {
  513. return &AnalysisError{
  514. Type: ErrTypeMismatch,
  515. Message: fmt.Sprintf("INSERT has %d columns but %d values", len(targetCols), len(row)),
  516. }
  517. }
  518. for _, expr := range row {
  519. _, err := a.analyzeExpr(expr)
  520. if err != nil {
  521. return err
  522. }
  523. }
  524. }
  525. // Analyze INSERT ... SELECT
  526. if stmt.Select != nil {
  527. if err := a.analyzeSelect(stmt.Select); err != nil {
  528. return err
  529. }
  530. }
  531. // Analyze RETURNING in the target table's scope.
  532. if err := a.analyzeReturning(stmt.Returning); err != nil {
  533. return err
  534. }
  535. return nil
  536. }
  537. // analyzeReturning validates a RETURNING projection. Wildcards are accepted; a
  538. // projection may not contain aggregates.
  539. func (a *Analyzer) analyzeReturning(cols []parser.SelectColumn) error {
  540. for _, col := range cols {
  541. if col.Star || col.TableStar != "" || col.Expr == nil {
  542. continue
  543. }
  544. info, err := a.analyzeExpr(col.Expr)
  545. if err != nil {
  546. return err
  547. }
  548. if info.IsAggregate {
  549. return &AnalysisError{
  550. Type: ErrAggregateInWhere,
  551. Message: "aggregate functions are not allowed in RETURNING",
  552. }
  553. }
  554. }
  555. return nil
  556. }
  557. // analyzeUpdate analyzes an UPDATE statement.
  558. func (a *Analyzer) analyzeUpdate(stmt *parser.UpdateStmt) error {
  559. table, ok := a.catalog.GetTable(stmt.Table.Name)
  560. if !ok {
  561. return &AnalysisError{
  562. Type: ErrTableNotFound,
  563. Message: fmt.Sprintf("table not found: %s", stmt.Table.Name),
  564. }
  565. }
  566. a.scope.DefineTable(&TableInfo{Name: table.Name, Columns: table.Columns, Alias: stmt.Table.Alias, IsView: table.IsView})
  567. // UPDATE ... FROM: source tables/derived tables join the target in scope so
  568. // SET and WHERE may reference their columns.
  569. if len(stmt.From) > 0 {
  570. if err := a.resolveFromClause(stmt.From); err != nil {
  571. return err
  572. }
  573. }
  574. // Validate SET assignments
  575. for _, assign := range stmt.Set {
  576. col, ok := table.GetColumn(assign.Column)
  577. if !ok {
  578. return &AnalysisError{
  579. Type: ErrColumnNotFound,
  580. Message: fmt.Sprintf("column not found: %s", assign.Column),
  581. }
  582. }
  583. if col.Generated {
  584. return &AnalysisError{
  585. Type: ErrTypeMismatch,
  586. Message: fmt.Sprintf("cannot UPDATE generated column %s", assign.Column),
  587. }
  588. }
  589. _, err := a.analyzeExpr(assign.Value)
  590. if err != nil {
  591. return err
  592. }
  593. }
  594. // Analyze WHERE clause
  595. if stmt.Where != nil {
  596. info, err := a.analyzeExpr(stmt.Where)
  597. if err != nil {
  598. return err
  599. }
  600. if info.IsAggregate {
  601. return &AnalysisError{
  602. Type: ErrAggregateInWhere,
  603. Message: "aggregate functions not allowed in WHERE clause",
  604. }
  605. }
  606. }
  607. if err := a.analyzeReturning(stmt.Returning); err != nil {
  608. return err
  609. }
  610. return nil
  611. }
  612. // analyzeDelete analyzes a DELETE statement.
  613. func (a *Analyzer) analyzeDelete(stmt *parser.DeleteStmt) error {
  614. table, ok := a.catalog.GetTable(stmt.Table.Name)
  615. if !ok {
  616. return &AnalysisError{
  617. Type: ErrTableNotFound,
  618. Message: fmt.Sprintf("table not found: %s", stmt.Table.Name),
  619. }
  620. }
  621. a.scope.DefineTable(&TableInfo{Name: table.Name, Columns: table.Columns, IsView: table.IsView})
  622. // Analyze WHERE clause
  623. if stmt.Where != nil {
  624. info, err := a.analyzeExpr(stmt.Where)
  625. if err != nil {
  626. return err
  627. }
  628. if info.IsAggregate {
  629. return &AnalysisError{
  630. Type: ErrAggregateInWhere,
  631. Message: "aggregate functions not allowed in WHERE clause",
  632. }
  633. }
  634. }
  635. if err := a.analyzeReturning(stmt.Returning); err != nil {
  636. return err
  637. }
  638. return nil
  639. }
  640. // analyzeCreateTable analyzes a CREATE TABLE statement.
  641. func (a *Analyzer) analyzeCreateTable(stmt *parser.CreateTableStmt) error {
  642. // Check if table already exists
  643. if a.catalog.TableExists(stmt.Table.Name) {
  644. if stmt.IfNotExists {
  645. return nil // Silently succeed
  646. }
  647. return &AnalysisError{
  648. Type: ErrTableExists,
  649. Message: fmt.Sprintf("table already exists: %s", stmt.Table.Name),
  650. }
  651. }
  652. // Build table info
  653. tableInfo := &TableInfo{
  654. Name: stmt.Table.Name,
  655. }
  656. columnNames := make(map[string]bool)
  657. for _, colDef := range stmt.Columns {
  658. upperName := strings.ToUpper(colDef.Name)
  659. if columnNames[upperName] {
  660. return &AnalysisError{
  661. Type: ErrColumnAmbiguous,
  662. Message: fmt.Sprintf("duplicate column name: %s", colDef.Name),
  663. }
  664. }
  665. columnNames[upperName] = true
  666. colInfo := ColumnInfo{
  667. Name: colDef.Name,
  668. Type: TypeFromName(colDef.Type.Name),
  669. Nullable: true,
  670. TableName: stmt.Table.Name,
  671. Generated: colDef.GeneratedExpr != nil,
  672. Array: colDef.Type.Array,
  673. }
  674. // Process constraints
  675. for _, constraint := range colDef.Constraints {
  676. switch constraint.Type {
  677. case parser.ConstraintPrimaryKey:
  678. colInfo.PrimaryKey = true
  679. colInfo.Nullable = false
  680. case parser.ConstraintNotNull:
  681. colInfo.Nullable = false
  682. case parser.ConstraintDefault:
  683. // Store default value (not evaluated here)
  684. colInfo.Default = constraint.Default
  685. }
  686. }
  687. tableInfo.Columns = append(tableInfo.Columns, colInfo)
  688. }
  689. // Process table-level constraints
  690. for _, constraint := range stmt.Constraints {
  691. switch constraint.Type {
  692. case parser.ConstraintPrimaryKey:
  693. for _, colName := range constraint.Columns {
  694. for i := range tableInfo.Columns {
  695. if strings.EqualFold(tableInfo.Columns[i].Name, colName) {
  696. tableInfo.Columns[i].PrimaryKey = true
  697. tableInfo.Columns[i].Nullable = false
  698. }
  699. }
  700. }
  701. }
  702. }
  703. // Validate generated-column expressions against the new table's columns.
  704. // Column references resolve within the table being created.
  705. for _, colDef := range stmt.Columns {
  706. if colDef.GeneratedExpr == nil {
  707. continue
  708. }
  709. genScope := NewScope(nil)
  710. genScope.DefineTable(tableInfo)
  711. oldScope := a.scope
  712. a.scope = genScope
  713. _, err := a.analyzeExpr(colDef.GeneratedExpr)
  714. a.scope = oldScope
  715. if err != nil {
  716. return err
  717. }
  718. }
  719. // Analysis is validation-only. Publishing the table before the durable
  720. // schema write can leave a phantom catalog entry when that write fails.
  721. return nil
  722. }
  723. // analyzeDropTable analyzes a DROP TABLE statement.
  724. func (a *Analyzer) analyzeDropTable(stmt *parser.DropTableStmt) error {
  725. for _, tableRef := range stmt.Tables {
  726. if !a.catalog.TableExists(tableRef.Name) {
  727. if stmt.IfExists {
  728. continue // Silently succeed
  729. }
  730. return &AnalysisError{
  731. Type: ErrTableNotFound,
  732. Message: fmt.Sprintf("table not found: %s", tableRef.Name),
  733. }
  734. }
  735. if err := a.catalog.DropTable(tableRef.Name); err != nil {
  736. return err
  737. }
  738. }
  739. return nil
  740. }
  741. // analyzeExpr analyzes an expression and returns type information.
  742. func (a *Analyzer) analyzeExpr(expr parser.Expr) (*ExprInfo, error) {
  743. switch e := expr.(type) {
  744. case *parser.LiteralExpr:
  745. return a.analyzeLiteral(e)
  746. case *parser.ColumnRef:
  747. return a.analyzeColumnRef(e)
  748. case *parser.BinaryExpr:
  749. return a.analyzeBinaryExpr(e)
  750. case *parser.UnaryExpr:
  751. return a.analyzeUnaryExpr(e)
  752. case *parser.FunctionCall:
  753. return a.analyzeFunctionCall(e)
  754. case *parser.ParenExpr:
  755. return a.analyzeExpr(e.Expr)
  756. case *parser.CaseExpr:
  757. return a.analyzeCaseExpr(e)
  758. case *parser.CastExpr:
  759. return a.analyzeCastExpr(e)
  760. case *parser.InExpr:
  761. return a.analyzeInExpr(e)
  762. case *parser.BetweenExpr:
  763. return a.analyzeBetweenExpr(e)
  764. case *parser.LikeExpr:
  765. return a.analyzeLikeExpr(e)
  766. case *parser.IsNullExpr:
  767. return a.analyzeIsNullExpr(e)
  768. case *parser.IsDistinctExpr:
  769. left, err := a.analyzeExpr(e.Left)
  770. if err != nil {
  771. return nil, err
  772. }
  773. right, err := a.analyzeExpr(e.Right)
  774. if err != nil {
  775. return nil, err
  776. }
  777. return &ExprInfo{
  778. Type: TypeBoolean,
  779. IsAggregate: left.IsAggregate || right.IsAggregate,
  780. Nullable: false,
  781. }, nil
  782. case *parser.ExistsExpr:
  783. return a.analyzeExistsExpr(e)
  784. case *parser.ArrayExpr:
  785. return a.analyzeArrayExpr(e)
  786. case *parser.SubscriptExpr:
  787. return a.analyzeSubscriptExpr(e)
  788. case *parser.AnyAllExpr:
  789. return a.analyzeAnyAllExpr(e)
  790. case *parser.SubqueryExpr:
  791. return a.analyzeSubqueryExpr(e)
  792. case *parser.WindowExpr:
  793. return a.analyzeWindowExpr(e)
  794. default:
  795. return &ExprInfo{Type: TypeUnknown}, nil
  796. }
  797. }
  798. // analyzeArrayExpr validates every element of an ARRAY[...] constructor.
  799. func (a *Analyzer) analyzeArrayExpr(e *parser.ArrayExpr) (*ExprInfo, error) {
  800. info := &ExprInfo{Type: TypeUnknown, Array: true}
  801. for _, element := range e.Elements {
  802. elementInfo, err := a.analyzeExpr(element)
  803. if err != nil {
  804. return nil, err
  805. }
  806. if elementInfo.IsAggregate {
  807. info.IsAggregate = true
  808. }
  809. if elementInfo.Nullable || element == nil {
  810. info.Nullable = true
  811. }
  812. if elementInfo.Type != TypeNull {
  813. info.Type = elementInfo.Type
  814. }
  815. }
  816. return info, nil
  817. }
  818. // analyzeSubscriptExpr validates the array expression and the index of arr[idx].
  819. func (a *Analyzer) analyzeSubscriptExpr(e *parser.SubscriptExpr) (*ExprInfo, error) {
  820. arrayInfo, err := a.analyzeExpr(e.Expr)
  821. if err != nil {
  822. return nil, err
  823. }
  824. indexInfo, err := a.analyzeExpr(e.Index)
  825. if err != nil {
  826. return nil, err
  827. }
  828. if indexInfo.Type != TypeUnknown && indexInfo.Type != TypeNull && !indexInfo.Type.IsNumeric() {
  829. return nil, &AnalysisError{
  830. Type: ErrTypeMismatch,
  831. Message: "array subscript must be an integer expression",
  832. }
  833. }
  834. return &ExprInfo{
  835. Type: arrayInfo.Type,
  836. IsAggregate: arrayInfo.IsAggregate || indexInfo.IsAggregate,
  837. Nullable: true,
  838. }, nil
  839. }
  840. // analyzeAnyAllExpr validates both sides of a quantified comparison.
  841. func (a *Analyzer) analyzeAnyAllExpr(e *parser.AnyAllExpr) (*ExprInfo, error) {
  842. leftInfo, err := a.analyzeExpr(e.Left)
  843. if err != nil {
  844. return nil, err
  845. }
  846. arrayInfo, err := a.analyzeExpr(e.Array)
  847. if err != nil {
  848. return nil, err
  849. }
  850. return &ExprInfo{
  851. Type: TypeBoolean,
  852. IsAggregate: leftInfo.IsAggregate || arrayInfo.IsAggregate,
  853. Nullable: true,
  854. }, nil
  855. }
  856. // analyzeWindowExpr analyzes a window function. Window functions are not
  857. // aggregates for the purpose of GROUP BY handling.
  858. func (a *Analyzer) analyzeWindowExpr(e *parser.WindowExpr) (*ExprInfo, error) {
  859. if e.Func != nil {
  860. for _, arg := range e.Func.Args {
  861. if _, err := a.analyzeExpr(arg); err != nil {
  862. return nil, err
  863. }
  864. }
  865. }
  866. for _, p := range e.PartitionBy {
  867. if _, err := a.analyzeExpr(p); err != nil {
  868. return nil, err
  869. }
  870. }
  871. for _, o := range e.OrderBy {
  872. if _, err := a.analyzeExpr(o.Expr); err != nil {
  873. return nil, err
  874. }
  875. }
  876. ret := TypeInteger
  877. if e.Func != nil {
  878. if sig, ok := builtinFunctions[e.Func.Name]; ok {
  879. ret = sig.ReturnType
  880. }
  881. }
  882. return &ExprInfo{Type: ret}, nil
  883. }
  884. func (a *Analyzer) analyzeLiteral(e *parser.LiteralExpr) (*ExprInfo, error) {
  885. info := &ExprInfo{IsConstant: true}
  886. switch e.Type {
  887. case lexer.TokenNumber:
  888. if strings.Contains(e.Value, ".") || strings.Contains(strings.ToLower(e.Value), "e") {
  889. info.Type = TypeReal
  890. } else {
  891. info.Type = TypeInteger
  892. }
  893. case lexer.TokenString:
  894. info.Type = TypeText
  895. case lexer.TokenBlob:
  896. info.Type = TypeBlob
  897. case lexer.TokenNULL:
  898. info.Type = TypeNull
  899. info.Nullable = true
  900. case lexer.TokenTRUE, lexer.TokenFALSE:
  901. info.Type = TypeBoolean
  902. case lexer.TokenStar:
  903. info.Type = TypeAny
  904. default:
  905. info.Type = TypeUnknown
  906. }
  907. return info, nil
  908. }
  909. func (a *Analyzer) analyzeColumnRef(e *parser.ColumnRef) (*ExprInfo, error) {
  910. col, _, ok := a.scope.LookupColumn(e.Table, e.Column)
  911. if !ok {
  912. // If no tables are in scope, treat as unknown (for standalone expressions)
  913. if len(a.scope.GetTables()) == 0 {
  914. return &ExprInfo{Type: TypeUnknown}, nil
  915. }
  916. // Hidden rowid alias (rowid/oid/_rowid_) when the table has no real column
  917. // of that name. LookupColumn already resolved a real column, so this only
  918. // fires for the alias (SQLite gives explicit columns precedence).
  919. if isRowIDAlias(e.Column) {
  920. if e.Table != "" {
  921. if _, found := a.scope.LookupTable(e.Table); !found {
  922. return nil, &AnalysisError{
  923. Type: ErrColumnNotFound,
  924. Message: fmt.Sprintf("column not found: %s", formatColumnRef(e)),
  925. }
  926. }
  927. }
  928. return &ExprInfo{Type: TypeInteger}, nil
  929. }
  930. return nil, &AnalysisError{
  931. Type: ErrColumnNotFound,
  932. Message: fmt.Sprintf("column not found: %s", formatColumnRef(e)),
  933. }
  934. }
  935. return &ExprInfo{
  936. Type: col.Type,
  937. Nullable: col.Nullable,
  938. Array: col.Array,
  939. }, nil
  940. }
  941. // isRowIDAlias reports whether a column name is a hidden rowid alias (rowid, oid,
  942. // or _rowid_), matching the storage layer's IsRowIDColumn.
  943. func isRowIDAlias(name string) bool {
  944. switch strings.ToLower(name) {
  945. case "rowid", "oid", "_rowid_":
  946. return true
  947. }
  948. return false
  949. }
  950. func formatColumnRef(e *parser.ColumnRef) string {
  951. if e.Table != "" {
  952. return e.Table + "." + e.Column
  953. }
  954. return e.Column
  955. }
  956. func (a *Analyzer) analyzeBinaryExpr(e *parser.BinaryExpr) (*ExprInfo, error) {
  957. left, err := a.analyzeExpr(e.Left)
  958. if err != nil {
  959. return nil, err
  960. }
  961. right, err := a.analyzeExpr(e.Right)
  962. if err != nil {
  963. return nil, err
  964. }
  965. info := &ExprInfo{
  966. IsAggregate: left.IsAggregate || right.IsAggregate,
  967. IsConstant: left.IsConstant && right.IsConstant,
  968. Nullable: left.Nullable || right.Nullable,
  969. }
  970. switch e.Op {
  971. case lexer.TokenMinus:
  972. // `jsonb - text`, `jsonb - integer`, and `jsonb - text[]` delete a key or
  973. // array element instead of subtracting. A jsonb right operand with any
  974. // other arithmetic operator stays a type error.
  975. if left.Type == TypeJSONB {
  976. if right.Type == TypeJSONB {
  977. return nil, &AnalysisError{
  978. Type: ErrTypeMismatch,
  979. Message: "jsonb deletion requires a text key, integer index, or text[] path, not a jsonb operand",
  980. }
  981. }
  982. info.Type = TypeJSONB
  983. return info, nil
  984. }
  985. if right.Type == TypeJSONB {
  986. return nil, &AnalysisError{
  987. Type: ErrTypeMismatch,
  988. Message: "cannot subtract JSONB from a non-jsonb value",
  989. }
  990. }
  991. fallthrough
  992. case lexer.TokenPlus, lexer.TokenStar, lexer.TokenSlash, lexer.TokenPercent:
  993. // Arithmetic operators. TypeAny comes from derived tables and CTEs whose
  994. // column types are not tracked, so it is allowed rather than rejected.
  995. info.Type = CommonType(left.Type, right.Type)
  996. if !left.Type.IsNumeric() && left.Type != TypeNull && left.Type != TypeUnknown && left.Type != TypeAny {
  997. return nil, &AnalysisError{
  998. Type: ErrTypeMismatch,
  999. Message: fmt.Sprintf("arithmetic operator requires numeric type, got %s", left.Type),
  1000. }
  1001. }
  1002. case lexer.TokenEq, lexer.TokenNeq, lexer.TokenLt, lexer.TokenLte, lexer.TokenGt, lexer.TokenGte:
  1003. // Comparison operators. A text literal is accepted against an array
  1004. // column: the runtime coerces and canonicalizes the literal to the
  1005. // column's array type, so `nums = '{3,4}'` compares arrays rather than
  1006. // INTEGER with TEXT.
  1007. info.Type = TypeBoolean
  1008. if !comparisonTypesCompatible(left, right) {
  1009. return nil, &AnalysisError{
  1010. Type: ErrTypeMismatch,
  1011. Message: fmt.Sprintf("cannot compare %s with %s", left.Type, right.Type),
  1012. }
  1013. }
  1014. case lexer.TokenBitAnd, lexer.TokenBitOr, lexer.TokenShiftLeft, lexer.TokenShiftRight:
  1015. // Bitwise operators coerce operands to integers.
  1016. info.Type = TypeInteger
  1017. for _, operand := range []Type{left.Type, right.Type} {
  1018. if !operand.IsNumeric() && operand != TypeNull && operand != TypeUnknown && operand != TypeAny {
  1019. return nil, &AnalysisError{
  1020. Type: ErrTypeMismatch,
  1021. Message: fmt.Sprintf("bitwise operator requires numeric type, got %s", operand),
  1022. }
  1023. }
  1024. }
  1025. case lexer.TokenAND, lexer.TokenOR:
  1026. // Logical operators
  1027. info.Type = TypeBoolean
  1028. case lexer.TokenConcat:
  1029. // String concatenation, or jsonb merge when either side is jsonb.
  1030. if left.Type == TypeJSONB || right.Type == TypeJSONB {
  1031. other := left.Type
  1032. if left.Type == TypeJSONB {
  1033. other = right.Type
  1034. }
  1035. if !jsonbTextOperand(other) {
  1036. return nil, &AnalysisError{
  1037. Type: ErrTypeMismatch,
  1038. Message: fmt.Sprintf("jsonb concatenation requires a jsonb or text operand, got %s", other),
  1039. }
  1040. }
  1041. info.Type = TypeJSONB
  1042. return info, nil
  1043. }
  1044. info.Type = TypeText
  1045. case lexer.TokenArrow:
  1046. // JSON extraction. A jsonb document extracts as jsonb, so a later
  1047. // comparison cannot silently reinterpret the result as SQL text.
  1048. info.Type = TypeAny
  1049. if left.Type == TypeJSONB {
  1050. info.Type = TypeJSONB
  1051. }
  1052. case lexer.TokenArrowText:
  1053. // ->> returns the SQL value or text; it is not jsonb.
  1054. info.Type = TypeAny
  1055. case lexer.TokenHashArrow:
  1056. // JSONB path extraction returns a JSONB value.
  1057. info.Type = TypeAny
  1058. if left.Type == TypeJSONB {
  1059. info.Type = TypeJSONB
  1060. }
  1061. case lexer.TokenHashArrowText:
  1062. info.Type = TypeText
  1063. case lexer.TokenHashMinus:
  1064. info.Type = TypeAny
  1065. if left.Type == TypeJSONB {
  1066. info.Type = TypeJSONB
  1067. }
  1068. case lexer.TokenAtArrow, lexer.TokenLtAt:
  1069. // Containment needs a jsonb operand (or text read as a jsonb document)
  1070. // on both sides; a number is not silently reinterpreted as JSON.
  1071. if !jsonbTextOperand(left.Type) || !jsonbTextOperand(right.Type) {
  1072. return nil, &AnalysisError{
  1073. Type: ErrTypeMismatch,
  1074. Message: fmt.Sprintf("jsonb containment requires jsonb or text operands, got %s and %s", left.Type, right.Type),
  1075. }
  1076. }
  1077. info.Type = TypeBoolean
  1078. case lexer.TokenQuestion, lexer.TokenQuestionPipe, lexer.TokenQuestionAmp:
  1079. info.Type = TypeBoolean
  1080. default:
  1081. info.Type = TypeUnknown
  1082. }
  1083. return info, nil
  1084. }
  1085. // comparisonTypesCompatible reports whether two comparison operands can be
  1086. // compared. Arrays only compare with arrays or with text that can be read as
  1087. // array text, so `nums = '{3,4}'` is accepted while `nums = 5` is not.
  1088. func comparisonTypesCompatible(left, right *ExprInfo) bool {
  1089. if left.Array || right.Array {
  1090. return (left.Array && right.Array) || arrayLiteralComparison(left, right)
  1091. }
  1092. return left.Type.IsComparable(right.Type)
  1093. }
  1094. // arrayLiteralComparison reports whether one side is an array expression and the
  1095. // other is a text expression that can be read as array text.
  1096. func arrayLiteralComparison(left, right *ExprInfo) bool {
  1097. textCoercible := func(info *ExprInfo) bool {
  1098. switch info.Type {
  1099. case TypeText, TypeUnknown, TypeNull, TypeAny:
  1100. return true
  1101. default:
  1102. return false
  1103. }
  1104. }
  1105. return (left.Array && textCoercible(right)) || (right.Array && textCoercible(left))
  1106. }
  1107. // jsonbTextOperand reports whether a type can stand on the other side of a
  1108. // jsonb operator: a jsonb value or text that is read as a jsonb document.
  1109. func jsonbTextOperand(t Type) bool {
  1110. switch t {
  1111. case TypeJSONB, TypeText, TypeBlob, TypeNull, TypeUnknown, TypeAny:
  1112. return true
  1113. default:
  1114. return false
  1115. }
  1116. }
  1117. func (a *Analyzer) analyzeUnaryExpr(e *parser.UnaryExpr) (*ExprInfo, error) {
  1118. operand, err := a.analyzeExpr(e.Operand)
  1119. if err != nil {
  1120. return nil, err
  1121. }
  1122. info := &ExprInfo{
  1123. IsAggregate: operand.IsAggregate,
  1124. IsConstant: operand.IsConstant,
  1125. Nullable: operand.Nullable,
  1126. }
  1127. switch e.Op {
  1128. case lexer.TokenPlus:
  1129. // Unary + is a no-op in SQLite — passes any type through unchanged.
  1130. info.Type = operand.Type
  1131. case lexer.TokenMinus:
  1132. info.Type = operand.Type
  1133. if !operand.Type.IsNumeric() && operand.Type != TypeNull && operand.Type != TypeUnknown {
  1134. return nil, &AnalysisError{
  1135. Type: ErrTypeMismatch,
  1136. Message: fmt.Sprintf("unary - requires numeric type, got %s", operand.Type),
  1137. }
  1138. }
  1139. case lexer.TokenNOT:
  1140. info.Type = TypeBoolean
  1141. case lexer.TokenBitNot:
  1142. info.Type = TypeInteger
  1143. default:
  1144. info.Type = operand.Type
  1145. }
  1146. return info, nil
  1147. }
  1148. // tableFunctionColumns reports the output columns of a set-returning function
  1149. // used as the single FROM item, using PostgreSQL's column names.
  1150. func tableFunctionColumns(name string) []ColumnInfo {
  1151. switch strings.ToLower(name) {
  1152. case "jsonb_each", "jsonb_each_text":
  1153. valueType := TypeJSONB
  1154. if strings.EqualFold(name, "jsonb_each_text") {
  1155. valueType = TypeText
  1156. }
  1157. return []ColumnInfo{
  1158. {Name: "key", Type: TypeText, Nullable: true, TableName: name},
  1159. {Name: "value", Type: valueType, Nullable: true, TableName: name},
  1160. }
  1161. case "jsonb_array_elements":
  1162. return []ColumnInfo{{Name: "value", Type: TypeJSONB, Nullable: true, TableName: name}}
  1163. case "jsonb_array_elements_text":
  1164. return []ColumnInfo{{Name: "value", Type: TypeText, Nullable: true, TableName: name}}
  1165. case "jsonb_object_keys":
  1166. return []ColumnInfo{{Name: "jsonb_object_keys", Type: TypeText, Nullable: true, TableName: name}}
  1167. default:
  1168. // unnest() produces one column with the function's name, matching
  1169. // PostgreSQL's output column name.
  1170. return []ColumnInfo{{Name: strings.ToLower(name), Type: TypeAny, Nullable: true, TableName: name}}
  1171. }
  1172. }
  1173. func (a *Analyzer) analyzeFunctionCall(e *parser.FunctionCall) (*ExprInfo, error) {
  1174. sig, ok := LookupFunction(e.Name)
  1175. if !ok {
  1176. return nil, &AnalysisError{
  1177. Type: ErrInvalidFunction,
  1178. Message: fmt.Sprintf("unknown function: %s", e.Name),
  1179. }
  1180. }
  1181. // Handle COUNT(*)
  1182. argCount := len(e.Args)
  1183. if e.Star {
  1184. argCount = 0 // COUNT(*) has 0 real args
  1185. }
  1186. // Check argument count
  1187. if argCount < sig.MinArgs {
  1188. return nil, &AnalysisError{
  1189. Type: ErrInvalidArgCount,
  1190. Message: fmt.Sprintf("function %s requires at least %d arguments, got %d", e.Name, sig.MinArgs, argCount),
  1191. }
  1192. }
  1193. if sig.MaxArgs >= 0 && argCount > sig.MaxArgs {
  1194. return nil, &AnalysisError{
  1195. Type: ErrInvalidArgCount,
  1196. Message: fmt.Sprintf("function %s accepts at most %d arguments, got %d", e.Name, sig.MaxArgs, argCount),
  1197. }
  1198. }
  1199. // Analyze arguments
  1200. info := &ExprInfo{
  1201. Type: sig.ReturnType,
  1202. IsAggregate: sig.IsAggregate,
  1203. }
  1204. for _, arg := range e.Args {
  1205. argInfo, err := a.analyzeExpr(arg)
  1206. if err != nil {
  1207. return nil, err
  1208. }
  1209. if argInfo.Nullable {
  1210. info.Nullable = true
  1211. }
  1212. // Propagate aggregate status from arguments
  1213. if argInfo.IsAggregate && !sig.IsAggregate {
  1214. info.IsAggregate = true
  1215. }
  1216. }
  1217. // Special case: polymorphic functions (MIN/MAX/COALESCE/...) return a value
  1218. // whose type follows their first argument.
  1219. if sig.ReturnType == TypeAny && len(e.Args) > 0 && isPolymorphicFunction(e.Name) {
  1220. argInfo, _ := a.analyzeExpr(e.Args[0])
  1221. if argInfo != nil {
  1222. info.Type = argInfo.Type
  1223. }
  1224. }
  1225. return info, nil
  1226. }
  1227. // isPolymorphicFunction reports whether a function's result type follows its
  1228. // first argument rather than a fixed signature type.
  1229. func isPolymorphicFunction(name string) bool {
  1230. switch strings.ToUpper(name) {
  1231. case "MIN", "MAX", "COALESCE", "IFNULL", "NVL", "NULLIF", "IIF":
  1232. return true
  1233. }
  1234. return false
  1235. }
  1236. func (a *Analyzer) analyzeCaseExpr(e *parser.CaseExpr) (*ExprInfo, error) {
  1237. info := &ExprInfo{
  1238. Nullable: true, // CASE can return NULL
  1239. }
  1240. // Analyze operand if present (simple CASE)
  1241. if e.Operand != nil {
  1242. opInfo, err := a.analyzeExpr(e.Operand)
  1243. if err != nil {
  1244. return nil, err
  1245. }
  1246. if opInfo.IsAggregate {
  1247. info.IsAggregate = true
  1248. }
  1249. }
  1250. // Analyze WHEN clauses
  1251. var resultType Type
  1252. for _, when := range e.Whens {
  1253. condInfo, err := a.analyzeExpr(when.Condition)
  1254. if err != nil {
  1255. return nil, err
  1256. }
  1257. if condInfo.IsAggregate {
  1258. info.IsAggregate = true
  1259. }
  1260. resInfo, err := a.analyzeExpr(when.Result)
  1261. if err != nil {
  1262. return nil, err
  1263. }
  1264. if resInfo.IsAggregate {
  1265. info.IsAggregate = true
  1266. }
  1267. if resultType == TypeUnknown {
  1268. resultType = resInfo.Type
  1269. } else {
  1270. resultType = CommonType(resultType, resInfo.Type)
  1271. }
  1272. }
  1273. // Analyze ELSE clause
  1274. if e.Else != nil {
  1275. elseInfo, err := a.analyzeExpr(e.Else)
  1276. if err != nil {
  1277. return nil, err
  1278. }
  1279. if elseInfo.IsAggregate {
  1280. info.IsAggregate = true
  1281. }
  1282. resultType = CommonType(resultType, elseInfo.Type)
  1283. }
  1284. info.Type = resultType
  1285. return info, nil
  1286. }
  1287. func (a *Analyzer) analyzeCastExpr(e *parser.CastExpr) (*ExprInfo, error) {
  1288. exprInfo, err := a.analyzeExpr(e.Expr)
  1289. if err != nil {
  1290. return nil, err
  1291. }
  1292. return &ExprInfo{
  1293. Type: TypeFromName(e.Type.Name),
  1294. IsAggregate: exprInfo.IsAggregate,
  1295. IsConstant: exprInfo.IsConstant,
  1296. Nullable: exprInfo.Nullable,
  1297. Array: e.Type.Array,
  1298. }, nil
  1299. }
  1300. func (a *Analyzer) analyzeInExpr(e *parser.InExpr) (*ExprInfo, error) {
  1301. leftInfo, err := a.analyzeExpr(e.Left)
  1302. if err != nil {
  1303. return nil, err
  1304. }
  1305. info := &ExprInfo{
  1306. Type: TypeBoolean,
  1307. IsAggregate: leftInfo.IsAggregate,
  1308. }
  1309. // Analyze value list
  1310. for _, val := range e.Values {
  1311. valInfo, err := a.analyzeExpr(val)
  1312. if err != nil {
  1313. return nil, err
  1314. }
  1315. if valInfo.IsAggregate {
  1316. info.IsAggregate = true
  1317. }
  1318. }
  1319. // Analyze subquery
  1320. if e.Subquery != nil {
  1321. subScope := NewScope(a.scope)
  1322. oldScope := a.scope
  1323. a.scope = subScope
  1324. err := a.analyzeSelect(e.Subquery)
  1325. a.scope = oldScope
  1326. if err != nil {
  1327. return nil, err
  1328. }
  1329. }
  1330. return info, nil
  1331. }
  1332. func (a *Analyzer) analyzeBetweenExpr(e *parser.BetweenExpr) (*ExprInfo, error) {
  1333. leftInfo, err := a.analyzeExpr(e.Left)
  1334. if err != nil {
  1335. return nil, err
  1336. }
  1337. lowInfo, err := a.analyzeExpr(e.Low)
  1338. if err != nil {
  1339. return nil, err
  1340. }
  1341. highInfo, err := a.analyzeExpr(e.High)
  1342. if err != nil {
  1343. return nil, err
  1344. }
  1345. return &ExprInfo{
  1346. Type: TypeBoolean,
  1347. IsAggregate: leftInfo.IsAggregate || lowInfo.IsAggregate || highInfo.IsAggregate,
  1348. Nullable: leftInfo.Nullable || lowInfo.Nullable || highInfo.Nullable,
  1349. }, nil
  1350. }
  1351. func (a *Analyzer) analyzeLikeExpr(e *parser.LikeExpr) (*ExprInfo, error) {
  1352. leftInfo, err := a.analyzeExpr(e.Left)
  1353. if err != nil {
  1354. return nil, err
  1355. }
  1356. patternInfo, err := a.analyzeExpr(e.Pattern)
  1357. if err != nil {
  1358. return nil, err
  1359. }
  1360. info := &ExprInfo{
  1361. Type: TypeBoolean,
  1362. IsAggregate: leftInfo.IsAggregate || patternInfo.IsAggregate,
  1363. Nullable: leftInfo.Nullable || patternInfo.Nullable,
  1364. }
  1365. if e.Escape != nil {
  1366. escInfo, err := a.analyzeExpr(e.Escape)
  1367. if err != nil {
  1368. return nil, err
  1369. }
  1370. if escInfo.IsAggregate {
  1371. info.IsAggregate = true
  1372. }
  1373. }
  1374. return info, nil
  1375. }
  1376. func (a *Analyzer) analyzeIsNullExpr(e *parser.IsNullExpr) (*ExprInfo, error) {
  1377. leftInfo, err := a.analyzeExpr(e.Left)
  1378. if err != nil {
  1379. return nil, err
  1380. }
  1381. return &ExprInfo{
  1382. Type: TypeBoolean,
  1383. IsAggregate: leftInfo.IsAggregate,
  1384. IsConstant: leftInfo.IsConstant,
  1385. }, nil
  1386. }
  1387. func (a *Analyzer) analyzeExistsExpr(e *parser.ExistsExpr) (*ExprInfo, error) {
  1388. // Analyze subquery in its own scope
  1389. subScope := NewScope(a.scope)
  1390. oldScope := a.scope
  1391. a.scope = subScope
  1392. err := a.analyzeSelect(e.Subquery)
  1393. a.scope = oldScope
  1394. if err != nil {
  1395. return nil, err
  1396. }
  1397. return &ExprInfo{
  1398. Type: TypeBoolean,
  1399. }, nil
  1400. }
  1401. func (a *Analyzer) analyzeSubqueryExpr(e *parser.SubqueryExpr) (*ExprInfo, error) {
  1402. // Analyze subquery in its own scope
  1403. subScope := NewScope(a.scope)
  1404. oldScope := a.scope
  1405. a.scope = subScope
  1406. err := a.analyzeSelect(e.Query)
  1407. a.scope = oldScope
  1408. if err != nil {
  1409. return nil, err
  1410. }
  1411. // Scalar subquery - return type of first column
  1412. // For simplicity, return TypeAny
  1413. return &ExprInfo{
  1414. Type: TypeAny,
  1415. }, nil
  1416. }