ast.go 16 KB

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