ast.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. package parser
  2. import "github.com/danfragoso/pizzasql-next/pkg/lexer"
  3. // Node is the base interface for all AST nodes.
  4. type Node interface {
  5. node()
  6. }
  7. // Statement represents a SQL statement.
  8. type Statement interface {
  9. Node
  10. stmtNode()
  11. }
  12. // Expr represents an expression.
  13. type Expr interface {
  14. Node
  15. exprNode()
  16. }
  17. // SetOpType represents a set operation type.
  18. type SetOpType int
  19. const (
  20. SetOpUnion SetOpType = iota
  21. SetOpUnionAll
  22. SetOpIntersect
  23. SetOpExcept
  24. )
  25. // CompoundSelect chains two SELECT statements with a set operation.
  26. type CompoundSelect struct {
  27. Left *SelectStmt
  28. Op SetOpType
  29. Right *SelectStmt // may itself have Compound set for chained ops
  30. OrderBy []OrderByItem
  31. Limit Expr
  32. Offset Expr
  33. }
  34. func (c *CompoundSelect) node() {}
  35. func (c *CompoundSelect) stmtNode() {}
  36. // SelectStmt represents a SELECT statement.
  37. type SelectStmt struct {
  38. Distinct bool
  39. Columns []SelectColumn
  40. From []TableRef
  41. Where Expr
  42. GroupBy []Expr
  43. Having Expr
  44. OrderBy []OrderByItem
  45. Limit Expr
  46. Offset Expr
  47. // Compound chains a set operation onto this SELECT (UNION/INTERSECT/EXCEPT).
  48. Compound *CompoundSelect
  49. // With holds common table expressions that must be materialized before this
  50. // SELECT runs. Non-recursive CTEs are desugared by the parser instead; this
  51. // list carries recursive CTEs (and the CTEs that depend on them).
  52. With []*CTE
  53. }
  54. // CTE is a common table expression from a WITH clause.
  55. type CTE struct {
  56. Name string
  57. Columns []string
  58. Recursive bool
  59. Query *SelectStmt
  60. }
  61. func (s *SelectStmt) node() {}
  62. func (s *SelectStmt) stmtNode() {}
  63. // SelectColumn represents a column in SELECT.
  64. type SelectColumn struct {
  65. Expr Expr
  66. Alias string
  67. Star bool // true if this is *
  68. TableStar string // table name/alias if this is a qualified wildcard (table.*)
  69. }
  70. // TableRef represents a table reference.
  71. type TableRef struct {
  72. Schema string
  73. Name string
  74. Alias string
  75. Subquery *SelectStmt // for derived tables (SELECT ... FROM (SELECT ...) AS alias)
  76. Join *JoinClause // for joined tables
  77. // Function is set for a table function in FROM (currently only unnest()).
  78. // Name holds the function name so ordinary table dispatch ignores it.
  79. Function *FunctionCall
  80. }
  81. // JoinClause represents a JOIN clause.
  82. type JoinClause struct {
  83. Type JoinType
  84. Table *TableRef
  85. Condition Expr // ON condition
  86. Using []string // USING columns
  87. }
  88. // JoinType represents the type of JOIN.
  89. type JoinType int
  90. const (
  91. JoinInner JoinType = iota
  92. JoinLeft
  93. JoinRight
  94. JoinFull
  95. JoinCross
  96. )
  97. // NullsOrder selects where NULLs sort in an ORDER BY item.
  98. type NullsOrder int
  99. const (
  100. NullsDefault NullsOrder = iota // SQLite default: NULLs are smallest
  101. NullsFirst
  102. NullsLast
  103. )
  104. // OrderByItem represents an ORDER BY item.
  105. type OrderByItem struct {
  106. Expr Expr
  107. Desc bool
  108. NullsOrder NullsOrder
  109. }
  110. // ConflictAction represents the action to take on conflict.
  111. type ConflictAction int
  112. const (
  113. ConflictAbort ConflictAction = iota // Default
  114. ConflictReplace // INSERT OR REPLACE
  115. ConflictIgnore // INSERT OR IGNORE
  116. ConflictFail // INSERT OR FAIL
  117. ConflictRollback // INSERT OR ROLLBACK
  118. )
  119. // InsertStmt represents an INSERT statement.
  120. type InsertStmt struct {
  121. Table *TableRef
  122. Columns []string
  123. Values [][]Expr
  124. // DefaultValues is true for SQLite's INSERT ... DEFAULT VALUES, which
  125. // supplies no values. Values then holds one empty row so the executor
  126. // follows the normal single-row insert path.
  127. DefaultValues bool
  128. Select *SelectStmt // INSERT ... SELECT
  129. OnConflict ConflictAction // OR REPLACE/IGNORE/etc.
  130. ConflictTarget []string
  131. ConflictUpdate []Assignment
  132. ConflictDoNothing bool
  133. Returning []SelectColumn
  134. }
  135. func (s *InsertStmt) node() {}
  136. func (s *InsertStmt) stmtNode() {}
  137. // UpdateStmt represents an UPDATE statement.
  138. type UpdateStmt struct {
  139. Table *TableRef
  140. Set []Assignment
  141. From []TableRef
  142. Where Expr
  143. Returning []SelectColumn
  144. }
  145. func (s *UpdateStmt) node() {}
  146. func (s *UpdateStmt) stmtNode() {}
  147. // Assignment represents a SET assignment.
  148. type Assignment struct {
  149. Column string
  150. Value Expr
  151. }
  152. // DeleteStmt represents a DELETE statement.
  153. type DeleteStmt struct {
  154. Table *TableRef
  155. Where Expr
  156. Returning []SelectColumn
  157. }
  158. func (s *DeleteStmt) node() {}
  159. func (s *DeleteStmt) stmtNode() {}
  160. // CreateTableStmt represents a CREATE TABLE statement.
  161. type CreateTableStmt struct {
  162. IfNotExists bool
  163. Table *TableRef
  164. Columns []ColumnDef
  165. Constraints []TableConstraint
  166. }
  167. func (s *CreateTableStmt) node() {}
  168. func (s *CreateTableStmt) stmtNode() {}
  169. // ColumnDef represents a column definition.
  170. type ColumnDef struct {
  171. Name string
  172. Type DataType
  173. Constraints []ColumnConstraint
  174. // GeneratedExpr is non-nil for a GENERATED ALWAYS AS (expr) column. A
  175. // generated column's value is computed rather than supplied by the user.
  176. GeneratedExpr Expr
  177. GeneratedStored bool // true for STORED, false for VIRTUAL
  178. }
  179. // DataType represents a SQL data type.
  180. type DataType struct {
  181. Name string
  182. Precision int // for VARCHAR(n), NUMERIC(p,s)
  183. Scale int // for NUMERIC(p,s)
  184. Array bool // trailing [] declares a one-dimensional array
  185. }
  186. // SQLTypeName returns the type name as it is persisted in the catalog: the
  187. // base name plus a [] suffix for arrays. Precision and scale are not part of
  188. // the catalog shape because the engine does not enforce them.
  189. func (d DataType) SQLTypeName() string {
  190. if d.Array {
  191. return d.Name + "[]"
  192. }
  193. return d.Name
  194. }
  195. // ColumnConstraint represents a column-level constraint.
  196. type ColumnConstraint struct {
  197. Type ConstraintType
  198. Name string // optional constraint name
  199. Default Expr // for DEFAULT
  200. RefTable string // for REFERENCES
  201. RefColumns []string // for REFERENCES (empty means the parent's primary key)
  202. Check Expr // for CHECK
  203. // OnDelete and OnUpdate record the foreign-key referential actions. The
  204. // engine enforces foreign keys immediately and implements no cascades, so
  205. // only NO ACTION and RESTRICT are accepted; the rest are rejected at DDL.
  206. OnDelete ReferentialAction
  207. OnUpdate ReferentialAction
  208. // Deferrable is set for a DEFERRABLE clause. Deferred enforcement is not
  209. // implemented, so DDL rejects it instead of accepting a weaker guarantee.
  210. Deferrable bool
  211. // OnConflict is the conflict resolution algorithm declared with
  212. // ON CONFLICT REPLACE/etc. (ConflictAbort is the zero value/default).
  213. OnConflict ConflictAction
  214. HasOnConflict bool
  215. }
  216. // ConstraintType represents the type of constraint.
  217. type ConstraintType int
  218. const (
  219. ConstraintPrimaryKey ConstraintType = iota
  220. ConstraintNotNull
  221. ConstraintUnique
  222. ConstraintDefault
  223. ConstraintCheck
  224. ConstraintForeignKey
  225. ConstraintAutoIncrement
  226. )
  227. // ReferentialAction is a parsed foreign-key ON DELETE/ON UPDATE action.
  228. type ReferentialAction int
  229. const (
  230. // RefActionUnspecified is the default (no clause, equivalent to NO ACTION).
  231. RefActionUnspecified ReferentialAction = iota
  232. RefActionNoAction
  233. RefActionRestrict
  234. RefActionCascade
  235. RefActionSetNull
  236. RefActionSetDefault
  237. )
  238. // String returns the SQL spelling of the action.
  239. func (a ReferentialAction) String() string {
  240. switch a {
  241. case RefActionNoAction:
  242. return "NO ACTION"
  243. case RefActionRestrict:
  244. return "RESTRICT"
  245. case RefActionCascade:
  246. return "CASCADE"
  247. case RefActionSetNull:
  248. return "SET NULL"
  249. case RefActionSetDefault:
  250. return "SET DEFAULT"
  251. default:
  252. return ""
  253. }
  254. }
  255. // TableConstraint represents a table-level constraint.
  256. type TableConstraint struct {
  257. Type ConstraintType
  258. Name string // optional constraint name
  259. Columns []string // columns involved
  260. RefTable string // for FOREIGN KEY
  261. RefColumns []string // for FOREIGN KEY
  262. Check Expr // for CHECK
  263. // OnDelete and OnUpdate record the foreign-key referential actions.
  264. OnDelete ReferentialAction
  265. OnUpdate ReferentialAction
  266. // Deferrable is set for a DEFERRABLE clause.
  267. Deferrable bool
  268. // OnConflict is the conflict resolution declared with ON CONFLICT
  269. // REPLACE/etc.; HasOnConflict distinguishes it from the default ABORT.
  270. OnConflict ConflictAction
  271. HasOnConflict bool
  272. }
  273. // DropTableStmt represents a DROP TABLE statement.
  274. type DropTableStmt struct {
  275. IfExists bool
  276. Tables []*TableRef
  277. }
  278. func (s *DropTableStmt) node() {}
  279. func (s *DropTableStmt) stmtNode() {}
  280. // CreateIndexStmt represents a CREATE INDEX statement.
  281. type CreateIndexStmt struct {
  282. IfNotExists bool
  283. Unique bool
  284. Name string
  285. Table string
  286. Columns []IndexColumn
  287. }
  288. func (s *CreateIndexStmt) node() {}
  289. func (s *CreateIndexStmt) stmtNode() {}
  290. // IndexColumn represents a column in an index. Expr is set for expression
  291. // indexes (e.g. an index on lower(email)); a plain column index leaves it nil
  292. // and uses Name.
  293. type IndexColumn struct {
  294. Name string
  295. Desc bool // true for DESC ordering
  296. Expr Expr
  297. }
  298. // DropIndexStmt represents a DROP INDEX statement.
  299. type DropIndexStmt struct {
  300. IfExists bool
  301. Name string
  302. }
  303. func (s *DropIndexStmt) node() {}
  304. func (s *DropIndexStmt) stmtNode() {}
  305. // CreateViewStmt represents a CREATE VIEW statement.
  306. type CreateViewStmt struct {
  307. IfNotExists bool
  308. View *TableRef
  309. Select *SelectStmt
  310. }
  311. func (s *CreateViewStmt) node() {}
  312. func (s *CreateViewStmt) stmtNode() {}
  313. // DropViewStmt represents a DROP VIEW statement.
  314. type DropViewStmt struct {
  315. IfExists bool
  316. Views []*TableRef
  317. }
  318. func (s *DropViewStmt) node() {}
  319. func (s *DropViewStmt) stmtNode() {}
  320. // AlterTableStmt represents an ALTER TABLE statement.
  321. type AlterTableStmt struct {
  322. Table string
  323. Action AlterAction
  324. }
  325. func (s *AlterTableStmt) node() {}
  326. func (s *AlterTableStmt) stmtNode() {}
  327. // AlterAction represents an ALTER TABLE action.
  328. type AlterAction interface {
  329. Node
  330. alterAction()
  331. }
  332. // AddColumnAction represents ADD COLUMN action.
  333. type AddColumnAction struct {
  334. Column *ColumnDef
  335. IfNotExists bool
  336. }
  337. func (a *AddColumnAction) node() {}
  338. func (a *AddColumnAction) alterAction() {}
  339. // DropColumnAction represents DROP COLUMN action.
  340. type DropColumnAction struct {
  341. Column string
  342. }
  343. func (a *DropColumnAction) node() {}
  344. func (a *DropColumnAction) alterAction() {}
  345. // RenameTableAction represents RENAME TO action.
  346. type RenameTableAction struct {
  347. NewName string
  348. }
  349. func (a *RenameTableAction) node() {}
  350. func (a *RenameTableAction) alterAction() {}
  351. // RenameColumnAction represents RENAME COLUMN action.
  352. type RenameColumnAction struct {
  353. OldName string
  354. NewName string
  355. }
  356. func (a *RenameColumnAction) node() {}
  357. func (a *RenameColumnAction) alterAction() {}
  358. // AttachStmt represents an ATTACH DATABASE statement.
  359. type AttachStmt struct {
  360. FilePath string // Database file path or identifier
  361. Alias string // Database alias name
  362. }
  363. func (s *AttachStmt) node() {}
  364. func (s *AttachStmt) stmtNode() {}
  365. // DetachStmt represents a DETACH DATABASE statement.
  366. type DetachStmt struct {
  367. Alias string // Database alias to detach
  368. }
  369. func (s *DetachStmt) node() {}
  370. func (s *DetachStmt) stmtNode() {}
  371. // PragmaStmt represents a PRAGMA statement.
  372. type PragmaStmt struct {
  373. Name string // pragma name (e.g., "table_info")
  374. Arg string // optional argument (e.g., table name)
  375. Value Expr // optional value for SET pragmas
  376. }
  377. func (s *PragmaStmt) node() {}
  378. func (s *PragmaStmt) stmtNode() {}
  379. // AnalyzeStmt represents an ANALYZE statement. PizzaSQL does not maintain
  380. // optimizer statistics, so it is accepted and executed as a documented no-op.
  381. type AnalyzeStmt struct {
  382. Name string // optional table name
  383. }
  384. func (s *AnalyzeStmt) node() {}
  385. func (s *AnalyzeStmt) stmtNode() {}
  386. // ExplainStmt represents an EXPLAIN statement.
  387. type ExplainStmt struct {
  388. QueryPlan bool // true for EXPLAIN QUERY PLAN
  389. Statement Statement // the statement being explained
  390. }
  391. func (s *ExplainStmt) node() {}
  392. func (s *ExplainStmt) stmtNode() {}
  393. // Transaction statements
  394. // BeginStmt represents a BEGIN TRANSACTION statement.
  395. type BeginStmt struct {
  396. // Transaction mode (DEFERRED, IMMEDIATE, EXCLUSIVE) - for future use
  397. Mode string
  398. }
  399. func (s *BeginStmt) node() {}
  400. func (s *BeginStmt) stmtNode() {}
  401. // CommitStmt represents a COMMIT statement.
  402. type CommitStmt struct{}
  403. func (s *CommitStmt) node() {}
  404. func (s *CommitStmt) stmtNode() {}
  405. // RollbackStmt represents a ROLLBACK statement.
  406. type RollbackStmt struct {
  407. Savepoint string // for ROLLBACK TO SAVEPOINT
  408. }
  409. func (s *RollbackStmt) node() {}
  410. func (s *RollbackStmt) stmtNode() {}
  411. // SavepointStmt represents a SAVEPOINT statement.
  412. type SavepointStmt struct {
  413. Name string
  414. }
  415. func (s *SavepointStmt) node() {}
  416. func (s *SavepointStmt) stmtNode() {}
  417. // ReleaseStmt represents a RELEASE SAVEPOINT statement.
  418. type ReleaseStmt struct {
  419. Name string
  420. }
  421. func (s *ReleaseStmt) node() {}
  422. func (s *ReleaseStmt) stmtNode() {}
  423. // Notification statements
  424. // ListenStmt represents LISTEN channel.
  425. type ListenStmt struct {
  426. Channel string
  427. }
  428. func (s *ListenStmt) node() {}
  429. func (s *ListenStmt) stmtNode() {}
  430. // UnlistenStmt represents UNLISTEN channel or UNLISTEN *.
  431. type UnlistenStmt struct {
  432. Channel string
  433. All bool
  434. }
  435. func (s *UnlistenStmt) node() {}
  436. func (s *UnlistenStmt) stmtNode() {}
  437. // NotifyStmt represents NOTIFY channel [, payload].
  438. type NotifyStmt struct {
  439. Channel string
  440. Payload string
  441. }
  442. func (s *NotifyStmt) node() {}
  443. func (s *NotifyStmt) stmtNode() {}
  444. // Expression types
  445. // BinaryExpr represents a binary expression.
  446. type BinaryExpr struct {
  447. Left Expr
  448. Op lexer.TokenType
  449. Right Expr
  450. }
  451. func (e *BinaryExpr) node() {}
  452. func (e *BinaryExpr) exprNode() {}
  453. // UnaryExpr represents a unary expression.
  454. type UnaryExpr struct {
  455. Op lexer.TokenType
  456. Operand Expr
  457. }
  458. func (e *UnaryExpr) node() {}
  459. func (e *UnaryExpr) exprNode() {}
  460. // LiteralExpr represents a literal value.
  461. type LiteralExpr struct {
  462. Type lexer.TokenType // TokenNumber, TokenString, TokenNULL, TokenTRUE, TokenFALSE
  463. Value string
  464. }
  465. func (e *LiteralExpr) node() {}
  466. func (e *LiteralExpr) exprNode() {}
  467. // ColumnRef represents a column reference.
  468. type ColumnRef struct {
  469. Table string
  470. Column string
  471. }
  472. func (e *ColumnRef) node() {}
  473. func (e *ColumnRef) exprNode() {}
  474. // FunctionCall represents a function call.
  475. type FunctionCall struct {
  476. Name string
  477. Args []Expr
  478. Distinct bool // for COUNT(DISTINCT x)
  479. Star bool // for COUNT(*)
  480. }
  481. func (e *FunctionCall) node() {}
  482. func (e *FunctionCall) exprNode() {}
  483. // WindowExpr represents a function call with an OVER clause.
  484. type WindowExpr struct {
  485. Func *FunctionCall
  486. PartitionBy []Expr
  487. OrderBy []OrderByItem
  488. }
  489. func (e *WindowExpr) node() {}
  490. func (e *WindowExpr) exprNode() {}
  491. // SubqueryExpr represents a subquery expression.
  492. type SubqueryExpr struct {
  493. Query *SelectStmt
  494. }
  495. func (e *SubqueryExpr) node() {}
  496. func (e *SubqueryExpr) exprNode() {}
  497. // CaseExpr represents a CASE expression.
  498. type CaseExpr struct {
  499. Operand Expr // for CASE operand WHEN...
  500. Whens []WhenClause
  501. Else Expr
  502. }
  503. func (e *CaseExpr) node() {}
  504. func (e *CaseExpr) exprNode() {}
  505. // WhenClause represents a WHEN clause in CASE.
  506. type WhenClause struct {
  507. Condition Expr
  508. Result Expr
  509. }
  510. // InExpr represents an IN expression.
  511. type InExpr struct {
  512. Left Expr
  513. Not bool
  514. Values []Expr // IN (1, 2, 3)
  515. Subquery *SelectStmt // IN (SELECT ...)
  516. }
  517. func (e *InExpr) node() {}
  518. func (e *InExpr) exprNode() {}
  519. // BetweenExpr represents a BETWEEN expression.
  520. type BetweenExpr struct {
  521. Left Expr
  522. Not bool
  523. Low Expr
  524. High Expr
  525. }
  526. func (e *BetweenExpr) node() {}
  527. func (e *BetweenExpr) exprNode() {}
  528. // LikeExpr represents a LIKE expression.
  529. type LikeExpr struct {
  530. Left Expr
  531. Not bool
  532. Pattern Expr
  533. Escape Expr
  534. }
  535. func (e *LikeExpr) node() {}
  536. func (e *LikeExpr) exprNode() {}
  537. // IsNullExpr represents an IS NULL expression.
  538. type IsNullExpr struct {
  539. Left Expr
  540. Not bool
  541. }
  542. func (e *IsNullExpr) node() {}
  543. func (e *IsNullExpr) exprNode() {}
  544. // IsDistinctExpr represents `left IS DISTINCT FROM right` (Not=false) or
  545. // `left IS NOT DISTINCT FROM right` (Not=true). Unlike `=`, NULLs compare
  546. // equal to each other and distinct from non-NULLs.
  547. type IsDistinctExpr struct {
  548. Left Expr
  549. Right Expr
  550. Not bool
  551. }
  552. func (e *IsDistinctExpr) node() {}
  553. func (e *IsDistinctExpr) exprNode() {}
  554. // CastExpr represents a CAST expression.
  555. type CastExpr struct {
  556. Expr Expr
  557. Type DataType
  558. }
  559. func (e *CastExpr) node() {}
  560. func (e *CastExpr) exprNode() {}
  561. // ExistsExpr represents an EXISTS expression.
  562. type ExistsExpr struct {
  563. Subquery *SelectStmt
  564. }
  565. func (e *ExistsExpr) node() {}
  566. func (e *ExistsExpr) exprNode() {}
  567. // ArrayExpr represents the ARRAY[...] constructor. Elements are evaluated as
  568. // ordinary expressions; NULL elements survive as NULL array elements.
  569. type ArrayExpr struct {
  570. Elements []Expr
  571. }
  572. func (e *ArrayExpr) node() {}
  573. func (e *ArrayExpr) exprNode() {}
  574. // SubscriptExpr represents a 1-based array element access, arr[index].
  575. type SubscriptExpr struct {
  576. Expr Expr
  577. Index Expr
  578. }
  579. func (e *SubscriptExpr) node() {}
  580. func (e *SubscriptExpr) exprNode() {}
  581. // AnyAllExpr represents `left op ANY(array)` (All=false) or
  582. // `left op ALL(array)` (All=true). It evaluates with SQL three-valued logic.
  583. type AnyAllExpr struct {
  584. Left Expr
  585. Op lexer.TokenType
  586. All bool
  587. Array Expr
  588. }
  589. func (e *AnyAllExpr) node() {}
  590. func (e *AnyAllExpr) exprNode() {}
  591. // ParenExpr represents a parenthesized expression.
  592. type ParenExpr struct {
  593. Expr Expr
  594. }
  595. func (e *ParenExpr) node() {}
  596. func (e *ParenExpr) exprNode() {}