parser_test.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  1. package parser
  2. import (
  3. "testing"
  4. "github.com/danfragoso/pizzasql-next/pkg/lexer"
  5. )
  6. func parse(t *testing.T, input string) Statement {
  7. t.Helper()
  8. l := lexer.New(input)
  9. p := New(l)
  10. stmt, err := p.Parse()
  11. if err != nil {
  12. t.Fatalf("parse error: %v", err)
  13. }
  14. return stmt
  15. }
  16. func parseExpr(t *testing.T, input string) Expr {
  17. t.Helper()
  18. // Wrap in SELECT to parse as expression
  19. l := lexer.New("SELECT " + input)
  20. p := New(l)
  21. stmt, err := p.Parse()
  22. if err != nil {
  23. t.Fatalf("parse error: %v", err)
  24. }
  25. sel := stmt.(*SelectStmt)
  26. return sel.Columns[0].Expr
  27. }
  28. // SELECT statement tests
  29. func TestParseSelectStar(t *testing.T) {
  30. stmt := parse(t, "SELECT * FROM users")
  31. sel, ok := stmt.(*SelectStmt)
  32. if !ok {
  33. t.Fatalf("expected SelectStmt, got %T", stmt)
  34. }
  35. if len(sel.Columns) != 1 || !sel.Columns[0].Star {
  36. t.Error("expected SELECT *")
  37. }
  38. if len(sel.From) != 1 || sel.From[0].Name != "users" {
  39. t.Error("expected FROM users")
  40. }
  41. }
  42. func TestParseSelectColumns(t *testing.T) {
  43. stmt := parse(t, "SELECT id, name, email FROM users")
  44. sel := stmt.(*SelectStmt)
  45. if len(sel.Columns) != 3 {
  46. t.Fatalf("expected 3 columns, got %d", len(sel.Columns))
  47. }
  48. cols := []string{"id", "name", "email"}
  49. for i, col := range sel.Columns {
  50. ref, ok := col.Expr.(*ColumnRef)
  51. if !ok {
  52. t.Errorf("column %d: expected ColumnRef", i)
  53. continue
  54. }
  55. if ref.Column != cols[i] {
  56. t.Errorf("column %d: expected %s, got %s", i, cols[i], ref.Column)
  57. }
  58. }
  59. }
  60. func TestParseSelectWithAlias(t *testing.T) {
  61. stmt := parse(t, "SELECT id AS user_id, name AS full_name FROM users u")
  62. sel := stmt.(*SelectStmt)
  63. if sel.Columns[0].Alias != "user_id" {
  64. t.Errorf("expected alias user_id, got %s", sel.Columns[0].Alias)
  65. }
  66. if sel.Columns[1].Alias != "full_name" {
  67. t.Errorf("expected alias full_name, got %s", sel.Columns[1].Alias)
  68. }
  69. if sel.From[0].Alias != "u" {
  70. t.Errorf("expected table alias u, got %s", sel.From[0].Alias)
  71. }
  72. }
  73. func TestParseSelectDistinct(t *testing.T) {
  74. stmt := parse(t, "SELECT DISTINCT name FROM users")
  75. sel := stmt.(*SelectStmt)
  76. if !sel.Distinct {
  77. t.Error("expected DISTINCT")
  78. }
  79. }
  80. func TestParseSelectWhere(t *testing.T) {
  81. stmt := parse(t, "SELECT * FROM users WHERE id = 1")
  82. sel := stmt.(*SelectStmt)
  83. if sel.Where == nil {
  84. t.Fatal("expected WHERE clause")
  85. }
  86. binary, ok := sel.Where.(*BinaryExpr)
  87. if !ok {
  88. t.Fatalf("expected BinaryExpr, got %T", sel.Where)
  89. }
  90. if binary.Op != lexer.TokenEq {
  91. t.Errorf("expected =, got %v", binary.Op)
  92. }
  93. }
  94. func TestParseSelectWhereComplex(t *testing.T) {
  95. stmt := parse(t, "SELECT * FROM users WHERE id = 1 AND name = 'John' OR active = TRUE")
  96. sel := stmt.(*SelectStmt)
  97. if sel.Where == nil {
  98. t.Fatal("expected WHERE clause")
  99. }
  100. // Should be: (id = 1 AND name = 'John') OR active = TRUE
  101. or, ok := sel.Where.(*BinaryExpr)
  102. if !ok || or.Op != lexer.TokenOR {
  103. t.Fatal("expected OR at top level")
  104. }
  105. }
  106. func TestParseSelectOrderBy(t *testing.T) {
  107. stmt := parse(t, "SELECT * FROM users ORDER BY name ASC, id DESC")
  108. sel := stmt.(*SelectStmt)
  109. if len(sel.OrderBy) != 2 {
  110. t.Fatalf("expected 2 ORDER BY items, got %d", len(sel.OrderBy))
  111. }
  112. if sel.OrderBy[0].Desc {
  113. t.Error("first item should be ASC")
  114. }
  115. if !sel.OrderBy[1].Desc {
  116. t.Error("second item should be DESC")
  117. }
  118. }
  119. func TestParseSelectLimitOffset(t *testing.T) {
  120. stmt := parse(t, "SELECT * FROM users LIMIT 10 OFFSET 20")
  121. sel := stmt.(*SelectStmt)
  122. if sel.Limit == nil {
  123. t.Error("expected LIMIT")
  124. }
  125. if sel.Offset == nil {
  126. t.Error("expected OFFSET")
  127. }
  128. limit := sel.Limit.(*LiteralExpr)
  129. if limit.Value != "10" {
  130. t.Errorf("expected LIMIT 10, got %s", limit.Value)
  131. }
  132. offset := sel.Offset.(*LiteralExpr)
  133. if offset.Value != "20" {
  134. t.Errorf("expected OFFSET 20, got %s", offset.Value)
  135. }
  136. }
  137. func TestParseSelectGroupBy(t *testing.T) {
  138. stmt := parse(t, "SELECT name, COUNT(*) FROM users GROUP BY name")
  139. sel := stmt.(*SelectStmt)
  140. if len(sel.GroupBy) != 1 {
  141. t.Fatalf("expected 1 GROUP BY column, got %d", len(sel.GroupBy))
  142. }
  143. }
  144. func TestParseSelectHaving(t *testing.T) {
  145. stmt := parse(t, "SELECT name, COUNT(*) as cnt FROM users GROUP BY name HAVING COUNT(*) > 5")
  146. sel := stmt.(*SelectStmt)
  147. if sel.Having == nil {
  148. t.Fatal("expected HAVING clause")
  149. }
  150. }
  151. func TestParseSelectJoin(t *testing.T) {
  152. tests := []struct {
  153. input string
  154. joinType JoinType
  155. }{
  156. {"SELECT * FROM a JOIN b ON a.id = b.id", JoinInner},
  157. {"SELECT * FROM a INNER JOIN b ON a.id = b.id", JoinInner},
  158. {"SELECT * FROM a LEFT JOIN b ON a.id = b.id", JoinLeft},
  159. {"SELECT * FROM a LEFT OUTER JOIN b ON a.id = b.id", JoinLeft},
  160. {"SELECT * FROM a RIGHT JOIN b ON a.id = b.id", JoinRight},
  161. {"SELECT * FROM a CROSS JOIN b", JoinCross},
  162. }
  163. for _, tt := range tests {
  164. t.Run(tt.input, func(t *testing.T) {
  165. stmt := parse(t, tt.input)
  166. sel := stmt.(*SelectStmt)
  167. if sel.From[0].Join == nil {
  168. t.Fatal("expected JOIN")
  169. }
  170. if sel.From[0].Join.Type != tt.joinType {
  171. t.Errorf("expected join type %v, got %v", tt.joinType, sel.From[0].Join.Type)
  172. }
  173. })
  174. }
  175. }
  176. // INSERT statement tests
  177. func TestParseInsertValues(t *testing.T) {
  178. stmt := parse(t, "INSERT INTO users (name, age) VALUES ('John', 30)")
  179. ins, ok := stmt.(*InsertStmt)
  180. if !ok {
  181. t.Fatalf("expected InsertStmt, got %T", stmt)
  182. }
  183. if ins.Table.Name != "users" {
  184. t.Errorf("expected table users, got %s", ins.Table.Name)
  185. }
  186. if len(ins.Columns) != 2 {
  187. t.Fatalf("expected 2 columns, got %d", len(ins.Columns))
  188. }
  189. if len(ins.Values) != 1 || len(ins.Values[0]) != 2 {
  190. t.Error("expected 1 row with 2 values")
  191. }
  192. }
  193. func TestParseInsertMultipleRows(t *testing.T) {
  194. stmt := parse(t, "INSERT INTO users VALUES (1, 'John'), (2, 'Jane')")
  195. ins := stmt.(*InsertStmt)
  196. if len(ins.Values) != 2 {
  197. t.Fatalf("expected 2 rows, got %d", len(ins.Values))
  198. }
  199. }
  200. func TestParseInsertOrReplace(t *testing.T) {
  201. stmt := parse(t, "INSERT OR REPLACE INTO users (id, name) VALUES (1, 'John')")
  202. ins := stmt.(*InsertStmt)
  203. if ins.OnConflict != ConflictReplace {
  204. t.Errorf("expected ConflictReplace, got %v", ins.OnConflict)
  205. }
  206. if ins.Table.Name != "users" {
  207. t.Errorf("expected table users, got %s", ins.Table.Name)
  208. }
  209. }
  210. func TestParseInsertOrIgnore(t *testing.T) {
  211. stmt := parse(t, "INSERT OR IGNORE INTO users (id, name) VALUES (1, 'John')")
  212. ins := stmt.(*InsertStmt)
  213. if ins.OnConflict != ConflictIgnore {
  214. t.Errorf("expected ConflictIgnore, got %v", ins.OnConflict)
  215. }
  216. }
  217. func TestParseInsertOrFail(t *testing.T) {
  218. stmt := parse(t, "INSERT OR FAIL INTO users (id, name) VALUES (1, 'John')")
  219. ins := stmt.(*InsertStmt)
  220. if ins.OnConflict != ConflictFail {
  221. t.Errorf("expected ConflictFail, got %v", ins.OnConflict)
  222. }
  223. }
  224. func TestParseInsertOrAbort(t *testing.T) {
  225. stmt := parse(t, "INSERT OR ABORT INTO users (id, name) VALUES (1, 'John')")
  226. ins := stmt.(*InsertStmt)
  227. if ins.OnConflict != ConflictAbort {
  228. t.Errorf("expected ConflictAbort, got %v", ins.OnConflict)
  229. }
  230. }
  231. // UPDATE statement tests
  232. func TestParseUpdate(t *testing.T) {
  233. stmt := parse(t, "UPDATE users SET name = 'John', age = 30 WHERE id = 1")
  234. upd, ok := stmt.(*UpdateStmt)
  235. if !ok {
  236. t.Fatalf("expected UpdateStmt, got %T", stmt)
  237. }
  238. if upd.Table.Name != "users" {
  239. t.Errorf("expected table users, got %s", upd.Table.Name)
  240. }
  241. if len(upd.Set) != 2 {
  242. t.Fatalf("expected 2 assignments, got %d", len(upd.Set))
  243. }
  244. if upd.Where == nil {
  245. t.Error("expected WHERE clause")
  246. }
  247. }
  248. // DELETE statement tests
  249. func TestParseDelete(t *testing.T) {
  250. stmt := parse(t, "DELETE FROM users WHERE id = 1")
  251. del, ok := stmt.(*DeleteStmt)
  252. if !ok {
  253. t.Fatalf("expected DeleteStmt, got %T", stmt)
  254. }
  255. if del.Table.Name != "users" {
  256. t.Errorf("expected table users, got %s", del.Table.Name)
  257. }
  258. if del.Where == nil {
  259. t.Error("expected WHERE clause")
  260. }
  261. }
  262. func TestParseDeleteAll(t *testing.T) {
  263. stmt := parse(t, "DELETE FROM users")
  264. del := stmt.(*DeleteStmt)
  265. if del.Where != nil {
  266. t.Error("expected no WHERE clause")
  267. }
  268. }
  269. // CREATE TABLE tests
  270. func TestParseCreateTable(t *testing.T) {
  271. stmt := parse(t, `CREATE TABLE users (
  272. id INTEGER PRIMARY KEY,
  273. name TEXT NOT NULL,
  274. email VARCHAR(255) UNIQUE,
  275. age INTEGER DEFAULT 0
  276. )`)
  277. create, ok := stmt.(*CreateTableStmt)
  278. if !ok {
  279. t.Fatalf("expected CreateTableStmt, got %T", stmt)
  280. }
  281. if create.Table.Name != "users" {
  282. t.Errorf("expected table users, got %s", create.Table.Name)
  283. }
  284. if len(create.Columns) != 4 {
  285. t.Fatalf("expected 4 columns, got %d", len(create.Columns))
  286. }
  287. // Check id column
  288. if create.Columns[0].Name != "id" {
  289. t.Error("expected first column to be id")
  290. }
  291. if create.Columns[0].Type.Name != "INTEGER" {
  292. t.Error("expected INTEGER type")
  293. }
  294. // Check name column has NOT NULL
  295. found := false
  296. for _, c := range create.Columns[1].Constraints {
  297. if c.Type == ConstraintNotNull {
  298. found = true
  299. }
  300. }
  301. if !found {
  302. t.Error("expected NOT NULL constraint on name")
  303. }
  304. // Check email has VARCHAR(255)
  305. if create.Columns[2].Type.Name != "VARCHAR" || create.Columns[2].Type.Precision != 255 {
  306. t.Error("expected VARCHAR(255) for email")
  307. }
  308. }
  309. func TestParseCreateTableIfNotExists(t *testing.T) {
  310. stmt := parse(t, "CREATE TABLE IF NOT EXISTS users (id INTEGER)")
  311. create := stmt.(*CreateTableStmt)
  312. if !create.IfNotExists {
  313. t.Error("expected IF NOT EXISTS")
  314. }
  315. }
  316. func TestParseCreateTableWithConstraints(t *testing.T) {
  317. stmt := parse(t, `CREATE TABLE orders (
  318. id INTEGER,
  319. user_id INTEGER,
  320. PRIMARY KEY (id),
  321. FOREIGN KEY (user_id) REFERENCES users(id)
  322. )`)
  323. create := stmt.(*CreateTableStmt)
  324. if len(create.Constraints) != 2 {
  325. t.Fatalf("expected 2 table constraints, got %d", len(create.Constraints))
  326. }
  327. // Check PRIMARY KEY
  328. if create.Constraints[0].Type != ConstraintPrimaryKey {
  329. t.Error("expected PRIMARY KEY constraint")
  330. }
  331. // Check FOREIGN KEY
  332. if create.Constraints[1].Type != ConstraintForeignKey {
  333. t.Error("expected FOREIGN KEY constraint")
  334. }
  335. if create.Constraints[1].RefTable != "users" {
  336. t.Errorf("expected reference to users, got %s", create.Constraints[1].RefTable)
  337. }
  338. }
  339. // DROP TABLE tests
  340. func TestParseDropTable(t *testing.T) {
  341. stmt := parse(t, "DROP TABLE users")
  342. drop, ok := stmt.(*DropTableStmt)
  343. if !ok {
  344. t.Fatalf("expected DropTableStmt, got %T", stmt)
  345. }
  346. if len(drop.Tables) != 1 || drop.Tables[0].Name != "users" {
  347. t.Error("expected DROP TABLE users")
  348. }
  349. }
  350. func TestParseDropTableIfExists(t *testing.T) {
  351. stmt := parse(t, "DROP TABLE IF EXISTS users")
  352. drop := stmt.(*DropTableStmt)
  353. if !drop.IfExists {
  354. t.Error("expected IF EXISTS")
  355. }
  356. }
  357. // Expression tests
  358. func TestParseExprArithmetic(t *testing.T) {
  359. expr := parseExpr(t, "1 + 2 * 3")
  360. // Should be: 1 + (2 * 3) due to precedence
  361. add, ok := expr.(*BinaryExpr)
  362. if !ok || add.Op != lexer.TokenPlus {
  363. t.Fatal("expected + at top level")
  364. }
  365. mul, ok := add.Right.(*BinaryExpr)
  366. if !ok || mul.Op != lexer.TokenStar {
  367. t.Fatal("expected * on right side")
  368. }
  369. }
  370. func TestParseExprParens(t *testing.T) {
  371. expr := parseExpr(t, "(1 + 2) * 3")
  372. // Should be: (1 + 2) * 3
  373. mul, ok := expr.(*BinaryExpr)
  374. if !ok || mul.Op != lexer.TokenStar {
  375. t.Fatal("expected * at top level")
  376. }
  377. paren, ok := mul.Left.(*ParenExpr)
  378. if !ok {
  379. t.Fatal("expected ParenExpr on left")
  380. }
  381. add, ok := paren.Expr.(*BinaryExpr)
  382. if !ok || add.Op != lexer.TokenPlus {
  383. t.Fatal("expected + inside parens")
  384. }
  385. }
  386. func TestParseExprComparison(t *testing.T) {
  387. tests := []struct {
  388. input string
  389. op lexer.TokenType
  390. }{
  391. {"a = b", lexer.TokenEq},
  392. {"a <> b", lexer.TokenNeq},
  393. {"a != b", lexer.TokenNeq},
  394. {"a < b", lexer.TokenLt},
  395. {"a <= b", lexer.TokenLte},
  396. {"a > b", lexer.TokenGt},
  397. {"a >= b", lexer.TokenGte},
  398. }
  399. for _, tt := range tests {
  400. t.Run(tt.input, func(t *testing.T) {
  401. expr := parseExpr(t, tt.input)
  402. binary, ok := expr.(*BinaryExpr)
  403. if !ok {
  404. t.Fatalf("expected BinaryExpr, got %T", expr)
  405. }
  406. if binary.Op != tt.op {
  407. t.Errorf("expected %v, got %v", tt.op, binary.Op)
  408. }
  409. })
  410. }
  411. }
  412. func TestParseExprIsNull(t *testing.T) {
  413. tests := []struct {
  414. input string
  415. not bool
  416. }{
  417. {"a IS NULL", false},
  418. {"a IS NOT NULL", true},
  419. }
  420. for _, tt := range tests {
  421. t.Run(tt.input, func(t *testing.T) {
  422. expr := parseExpr(t, tt.input)
  423. isNull, ok := expr.(*IsNullExpr)
  424. if !ok {
  425. t.Fatalf("expected IsNullExpr, got %T", expr)
  426. }
  427. if isNull.Not != tt.not {
  428. t.Errorf("expected Not=%v, got %v", tt.not, isNull.Not)
  429. }
  430. })
  431. }
  432. }
  433. func TestParseExprIn(t *testing.T) {
  434. tests := []struct {
  435. input string
  436. not bool
  437. }{
  438. {"a IN (1, 2, 3)", false},
  439. {"a NOT IN (1, 2, 3)", true},
  440. }
  441. for _, tt := range tests {
  442. t.Run(tt.input, func(t *testing.T) {
  443. expr := parseExpr(t, tt.input)
  444. in, ok := expr.(*InExpr)
  445. if !ok {
  446. t.Fatalf("expected InExpr, got %T", expr)
  447. }
  448. if in.Not != tt.not {
  449. t.Errorf("expected Not=%v, got %v", tt.not, in.Not)
  450. }
  451. if len(in.Values) != 3 {
  452. t.Errorf("expected 3 values, got %d", len(in.Values))
  453. }
  454. })
  455. }
  456. }
  457. func TestParseExprBetween(t *testing.T) {
  458. tests := []struct {
  459. input string
  460. not bool
  461. }{
  462. {"a BETWEEN 1 AND 10", false},
  463. {"a NOT BETWEEN 1 AND 10", true},
  464. }
  465. for _, tt := range tests {
  466. t.Run(tt.input, func(t *testing.T) {
  467. expr := parseExpr(t, tt.input)
  468. between, ok := expr.(*BetweenExpr)
  469. if !ok {
  470. t.Fatalf("expected BetweenExpr, got %T", expr)
  471. }
  472. if between.Not != tt.not {
  473. t.Errorf("expected Not=%v, got %v", tt.not, between.Not)
  474. }
  475. })
  476. }
  477. }
  478. func TestParseExprLike(t *testing.T) {
  479. tests := []struct {
  480. input string
  481. not bool
  482. }{
  483. {"name LIKE '%test%'", false},
  484. {"name NOT LIKE '%test%'", true},
  485. }
  486. for _, tt := range tests {
  487. t.Run(tt.input, func(t *testing.T) {
  488. expr := parseExpr(t, tt.input)
  489. like, ok := expr.(*LikeExpr)
  490. if !ok {
  491. t.Fatalf("expected LikeExpr, got %T", expr)
  492. }
  493. if like.Not != tt.not {
  494. t.Errorf("expected Not=%v, got %v", tt.not, like.Not)
  495. }
  496. })
  497. }
  498. }
  499. func TestParseExprCase(t *testing.T) {
  500. expr := parseExpr(t, "CASE WHEN x = 1 THEN 'one' WHEN x = 2 THEN 'two' ELSE 'other' END")
  501. caseExpr, ok := expr.(*CaseExpr)
  502. if !ok {
  503. t.Fatalf("expected CaseExpr, got %T", expr)
  504. }
  505. if len(caseExpr.Whens) != 2 {
  506. t.Errorf("expected 2 WHEN clauses, got %d", len(caseExpr.Whens))
  507. }
  508. if caseExpr.Else == nil {
  509. t.Error("expected ELSE clause")
  510. }
  511. }
  512. func TestParseExprCast(t *testing.T) {
  513. expr := parseExpr(t, "CAST(x AS INTEGER)")
  514. cast, ok := expr.(*CastExpr)
  515. if !ok {
  516. t.Fatalf("expected CastExpr, got %T", expr)
  517. }
  518. if cast.Type.Name != "INTEGER" {
  519. t.Errorf("expected INTEGER type, got %s", cast.Type.Name)
  520. }
  521. }
  522. func TestParseExprFunction(t *testing.T) {
  523. tests := []struct {
  524. input string
  525. name string
  526. argCount int
  527. star bool
  528. distinct bool
  529. }{
  530. {"COUNT(*)", "COUNT", 0, true, false},
  531. {"COUNT(id)", "COUNT", 1, false, false},
  532. {"COUNT(DISTINCT id)", "COUNT", 1, false, true},
  533. {"SUM(amount)", "SUM", 1, false, false},
  534. {"UPPER(name)", "UPPER", 1, false, false},
  535. {"COALESCE(a, b, c)", "COALESCE", 3, false, false},
  536. }
  537. for _, tt := range tests {
  538. t.Run(tt.input, func(t *testing.T) {
  539. expr := parseExpr(t, tt.input)
  540. fn, ok := expr.(*FunctionCall)
  541. if !ok {
  542. t.Fatalf("expected FunctionCall, got %T", expr)
  543. }
  544. if fn.Name != tt.name {
  545. t.Errorf("expected name %s, got %s", tt.name, fn.Name)
  546. }
  547. if len(fn.Args) != tt.argCount {
  548. t.Errorf("expected %d args, got %d", tt.argCount, len(fn.Args))
  549. }
  550. if fn.Star != tt.star {
  551. t.Errorf("expected Star=%v, got %v", tt.star, fn.Star)
  552. }
  553. if fn.Distinct != tt.distinct {
  554. t.Errorf("expected Distinct=%v, got %v", tt.distinct, fn.Distinct)
  555. }
  556. })
  557. }
  558. }
  559. func TestParseExprSubquery(t *testing.T) {
  560. expr := parseExpr(t, "id IN (SELECT user_id FROM orders)")
  561. in, ok := expr.(*InExpr)
  562. if !ok {
  563. t.Fatalf("expected InExpr, got %T", expr)
  564. }
  565. if in.Subquery == nil {
  566. t.Error("expected subquery")
  567. }
  568. }
  569. func TestParseExprExists(t *testing.T) {
  570. expr := parseExpr(t, "EXISTS (SELECT 1 FROM users WHERE id = 1)")
  571. exists, ok := expr.(*ExistsExpr)
  572. if !ok {
  573. t.Fatalf("expected ExistsExpr, got %T", expr)
  574. }
  575. if exists.Subquery == nil {
  576. t.Error("expected subquery")
  577. }
  578. }
  579. func TestParseExprColumnRef(t *testing.T) {
  580. tests := []struct {
  581. input string
  582. table string
  583. column string
  584. }{
  585. {"id", "", "id"},
  586. {"users.id", "users", "id"},
  587. {"u.name", "u", "name"},
  588. }
  589. for _, tt := range tests {
  590. t.Run(tt.input, func(t *testing.T) {
  591. expr := parseExpr(t, tt.input)
  592. ref, ok := expr.(*ColumnRef)
  593. if !ok {
  594. t.Fatalf("expected ColumnRef, got %T", expr)
  595. }
  596. if ref.Table != tt.table {
  597. t.Errorf("expected table %q, got %q", tt.table, ref.Table)
  598. }
  599. if ref.Column != tt.column {
  600. t.Errorf("expected column %q, got %q", tt.column, ref.Column)
  601. }
  602. })
  603. }
  604. }
  605. // Error cases
  606. func TestParseErrors(t *testing.T) {
  607. tests := []struct {
  608. name string
  609. input string
  610. }{
  611. {"missing columns", "SELECT FROM users"},
  612. {"missing VALUES", "INSERT INTO users"},
  613. {"missing SET", "UPDATE users WHERE id = 1"},
  614. {"missing table name", "DELETE FROM WHERE id = 1"},
  615. {"unclosed paren", "SELECT * FROM users WHERE (id = 1"},
  616. {"invalid token", "SELECT @ FROM users"},
  617. }
  618. for _, tt := range tests {
  619. t.Run(tt.name, func(t *testing.T) {
  620. l := lexer.New(tt.input)
  621. p := New(l)
  622. _, err := p.Parse()
  623. if err == nil {
  624. t.Error("expected parse error")
  625. }
  626. })
  627. }
  628. }
  629. // Multiple statements
  630. func TestParseMultiple(t *testing.T) {
  631. input := `
  632. SELECT * FROM users;
  633. INSERT INTO users VALUES (1, 'John');
  634. DELETE FROM users WHERE id = 1
  635. `
  636. l := lexer.New(input)
  637. p := New(l)
  638. stmts, err := p.ParseMultiple()
  639. if err != nil {
  640. t.Fatalf("parse error: %v", err)
  641. }
  642. if len(stmts) != 3 {
  643. t.Errorf("expected 3 statements, got %d", len(stmts))
  644. }
  645. }
  646. func TestParseRejectsTrailingReturning(t *testing.T) {
  647. l := lexer.New("INSERT INTO users (id) VALUES (1) RETURNING id")
  648. if _, err := New(l).Parse(); err == nil {
  649. t.Fatal("expected RETURNING to be rejected before execution")
  650. }
  651. }
  652. func TestParsePostgresCompatibilityClauses(t *testing.T) {
  653. t.Run("alter add column if not exists", func(t *testing.T) {
  654. stmt := parse(t, "ALTER TABLE users ADD COLUMN IF NOT EXISTS revision INTEGER DEFAULT 0")
  655. action := stmt.(*AlterTableStmt).Action.(*AddColumnAction)
  656. if !action.IfNotExists || action.Column.Name != "revision" {
  657. t.Fatalf("unexpected action: %#v", action)
  658. }
  659. })
  660. t.Run("on conflict do update", func(t *testing.T) {
  661. stmt := parse(t, "INSERT INTO users (id, count) VALUES (1, 1) ON CONFLICT (id) DO UPDATE SET count = users.count + 1")
  662. insert := stmt.(*InsertStmt)
  663. if len(insert.ConflictTarget) != 1 || insert.ConflictTarget[0] != "id" || len(insert.ConflictUpdate) != 1 {
  664. t.Fatalf("unexpected conflict clause: %#v", insert)
  665. }
  666. })
  667. t.Run("jsonb cast", func(t *testing.T) {
  668. parse(t, "SELECT CAST('{}' AS JSONB)")
  669. })
  670. }
  671. // Phase 4: PRAGMA and EXPLAIN tests
  672. func TestParsePragmaTableInfo(t *testing.T) {
  673. stmt := parse(t, "PRAGMA table_info(users)")
  674. pragma, ok := stmt.(*PragmaStmt)
  675. if !ok {
  676. t.Fatalf("expected PragmaStmt, got %T", stmt)
  677. }
  678. if pragma.Name != "table_info" {
  679. t.Errorf("expected pragma name 'table_info', got %s", pragma.Name)
  680. }
  681. if pragma.Arg != "users" {
  682. t.Errorf("expected arg 'users', got %s", pragma.Arg)
  683. }
  684. }
  685. func TestParsePragmaTableList(t *testing.T) {
  686. stmt := parse(t, "PRAGMA table_list")
  687. pragma, ok := stmt.(*PragmaStmt)
  688. if !ok {
  689. t.Fatalf("expected PragmaStmt, got %T", stmt)
  690. }
  691. if pragma.Name != "table_list" {
  692. t.Errorf("expected pragma name 'table_list', got %s", pragma.Name)
  693. }
  694. }
  695. func TestParsePragmaDatabaseList(t *testing.T) {
  696. stmt := parse(t, "PRAGMA database_list")
  697. pragma := stmt.(*PragmaStmt)
  698. if pragma.Name != "database_list" {
  699. t.Errorf("expected pragma name 'database_list', got %s", pragma.Name)
  700. }
  701. }
  702. func TestParsePragmaVersion(t *testing.T) {
  703. stmt := parse(t, "PRAGMA version")
  704. pragma := stmt.(*PragmaStmt)
  705. if pragma.Name != "version" {
  706. t.Errorf("expected pragma name 'version', got %s", pragma.Name)
  707. }
  708. }
  709. func TestParseExplain(t *testing.T) {
  710. stmt := parse(t, "EXPLAIN SELECT * FROM users")
  711. explain, ok := stmt.(*ExplainStmt)
  712. if !ok {
  713. t.Fatalf("expected ExplainStmt, got %T", stmt)
  714. }
  715. if explain.QueryPlan {
  716. t.Error("expected QueryPlan to be false")
  717. }
  718. _, ok = explain.Statement.(*SelectStmt)
  719. if !ok {
  720. t.Errorf("expected SelectStmt inside EXPLAIN, got %T", explain.Statement)
  721. }
  722. }
  723. func TestParseExplainQueryPlan(t *testing.T) {
  724. stmt := parse(t, "EXPLAIN QUERY PLAN SELECT * FROM users WHERE id = 1")
  725. explain, ok := stmt.(*ExplainStmt)
  726. if !ok {
  727. t.Fatalf("expected ExplainStmt, got %T", stmt)
  728. }
  729. if !explain.QueryPlan {
  730. t.Error("expected QueryPlan to be true")
  731. }
  732. sel, ok := explain.Statement.(*SelectStmt)
  733. if !ok {
  734. t.Errorf("expected SelectStmt inside EXPLAIN, got %T", explain.Statement)
  735. }
  736. if sel.Where == nil {
  737. t.Error("expected WHERE clause in explained statement")
  738. }
  739. }
  740. func TestParseExplainInsert(t *testing.T) {
  741. stmt := parse(t, "EXPLAIN INSERT INTO users (name) VALUES ('John')")
  742. explain := stmt.(*ExplainStmt)
  743. _, ok := explain.Statement.(*InsertStmt)
  744. if !ok {
  745. t.Errorf("expected InsertStmt inside EXPLAIN, got %T", explain.Statement)
  746. }
  747. }
  748. // Phase 5: Transaction statement tests
  749. func TestParseBegin(t *testing.T) {
  750. stmt := parse(t, "BEGIN")
  751. _, ok := stmt.(*BeginStmt)
  752. if !ok {
  753. t.Fatalf("expected BeginStmt, got %T", stmt)
  754. }
  755. }
  756. func TestParseBeginTransaction(t *testing.T) {
  757. stmt := parse(t, "BEGIN TRANSACTION")
  758. _, ok := stmt.(*BeginStmt)
  759. if !ok {
  760. t.Fatalf("expected BeginStmt, got %T", stmt)
  761. }
  762. }
  763. func TestParseCommit(t *testing.T) {
  764. stmt := parse(t, "COMMIT")
  765. _, ok := stmt.(*CommitStmt)
  766. if !ok {
  767. t.Fatalf("expected CommitStmt, got %T", stmt)
  768. }
  769. }
  770. func TestParseCommitTransaction(t *testing.T) {
  771. stmt := parse(t, "COMMIT TRANSACTION")
  772. _, ok := stmt.(*CommitStmt)
  773. if !ok {
  774. t.Fatalf("expected CommitStmt, got %T", stmt)
  775. }
  776. }
  777. func TestParseRollback(t *testing.T) {
  778. stmt := parse(t, "ROLLBACK")
  779. rollback, ok := stmt.(*RollbackStmt)
  780. if !ok {
  781. t.Fatalf("expected RollbackStmt, got %T", stmt)
  782. }
  783. if rollback.Savepoint != "" {
  784. t.Errorf("expected empty savepoint, got %s", rollback.Savepoint)
  785. }
  786. }
  787. func TestParseRollbackToSavepoint(t *testing.T) {
  788. stmt := parse(t, "ROLLBACK TO SAVEPOINT sp1")
  789. rollback, ok := stmt.(*RollbackStmt)
  790. if !ok {
  791. t.Fatalf("expected RollbackStmt, got %T", stmt)
  792. }
  793. if rollback.Savepoint != "sp1" {
  794. t.Errorf("expected savepoint 'sp1', got %s", rollback.Savepoint)
  795. }
  796. }
  797. func TestParseRollbackTo(t *testing.T) {
  798. stmt := parse(t, "ROLLBACK TO sp1")
  799. rollback := stmt.(*RollbackStmt)
  800. if rollback.Savepoint != "sp1" {
  801. t.Errorf("expected savepoint 'sp1', got %s", rollback.Savepoint)
  802. }
  803. }
  804. func TestParseSavepoint(t *testing.T) {
  805. stmt := parse(t, "SAVEPOINT my_savepoint")
  806. sp, ok := stmt.(*SavepointStmt)
  807. if !ok {
  808. t.Fatalf("expected SavepointStmt, got %T", stmt)
  809. }
  810. if sp.Name != "my_savepoint" {
  811. t.Errorf("expected savepoint name 'my_savepoint', got %s", sp.Name)
  812. }
  813. }
  814. func TestParseReleaseSavepoint(t *testing.T) {
  815. stmt := parse(t, "RELEASE SAVEPOINT sp1")
  816. rel, ok := stmt.(*ReleaseStmt)
  817. if !ok {
  818. t.Fatalf("expected ReleaseStmt, got %T", stmt)
  819. }
  820. if rel.Name != "sp1" {
  821. t.Errorf("expected savepoint name 'sp1', got %s", rel.Name)
  822. }
  823. }
  824. func TestParseRelease(t *testing.T) {
  825. stmt := parse(t, "RELEASE sp1")
  826. rel := stmt.(*ReleaseStmt)
  827. if rel.Name != "sp1" {
  828. t.Errorf("expected savepoint name 'sp1', got %s", rel.Name)
  829. }
  830. }
  831. // Benchmark
  832. func BenchmarkParseSelect(b *testing.B) {
  833. input := `SELECT u.id, u.name, u.email, COUNT(o.id) as order_count
  834. FROM users u
  835. LEFT JOIN orders o ON u.id = o.user_id
  836. WHERE u.active = TRUE AND u.created_at >= '2024-01-01'
  837. GROUP BY u.id, u.name, u.email
  838. HAVING COUNT(o.id) > 5
  839. ORDER BY order_count DESC
  840. LIMIT 100 OFFSET 0`
  841. b.ResetTimer()
  842. for i := 0; i < b.N; i++ {
  843. l := lexer.New(input)
  844. p := New(l)
  845. _, _ = p.Parse()
  846. }
  847. }
  848. func BenchmarkParseCreateTable(b *testing.B) {
  849. input := `CREATE TABLE users (
  850. id INTEGER PRIMARY KEY AUTOINCREMENT,
  851. name TEXT NOT NULL,
  852. email VARCHAR(255) UNIQUE,
  853. age INTEGER DEFAULT 0,
  854. active BOOLEAN DEFAULT TRUE,
  855. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  856. )`
  857. b.ResetTimer()
  858. for i := 0; i < b.N; i++ {
  859. l := lexer.New(input)
  860. p := New(l)
  861. _, _ = p.Parse()
  862. }
  863. }
  864. // CREATE INDEX tests
  865. func TestParseCreateIndex(t *testing.T) {
  866. stmt := parse(t, "CREATE INDEX idx_email ON users (email)")
  867. idx, ok := stmt.(*CreateIndexStmt)
  868. if !ok {
  869. t.Fatalf("expected CreateIndexStmt, got %T", stmt)
  870. }
  871. if idx.Name != "idx_email" {
  872. t.Errorf("expected index name idx_email, got %s", idx.Name)
  873. }
  874. if idx.Table != "users" {
  875. t.Errorf("expected table users, got %s", idx.Table)
  876. }
  877. if len(idx.Columns) != 1 || idx.Columns[0].Name != "email" {
  878. t.Error("expected column email")
  879. }
  880. if idx.Unique {
  881. t.Error("expected non-unique index")
  882. }
  883. if idx.IfNotExists {
  884. t.Error("expected IfNotExists to be false")
  885. }
  886. }
  887. func TestParseCreateUniqueIndex(t *testing.T) {
  888. stmt := parse(t, "CREATE UNIQUE INDEX idx_email ON users (email)")
  889. idx, ok := stmt.(*CreateIndexStmt)
  890. if !ok {
  891. t.Fatalf("expected CreateIndexStmt, got %T", stmt)
  892. }
  893. if !idx.Unique {
  894. t.Error("expected unique index")
  895. }
  896. }
  897. func TestParseCreateIndexIfNotExists(t *testing.T) {
  898. stmt := parse(t, "CREATE INDEX IF NOT EXISTS idx_email ON users (email)")
  899. idx, ok := stmt.(*CreateIndexStmt)
  900. if !ok {
  901. t.Fatalf("expected CreateIndexStmt, got %T", stmt)
  902. }
  903. if !idx.IfNotExists {
  904. t.Error("expected IfNotExists to be true")
  905. }
  906. }
  907. func TestParseCreateIndexMultiColumn(t *testing.T) {
  908. stmt := parse(t, "CREATE INDEX idx_name_email ON users (name, email)")
  909. idx, ok := stmt.(*CreateIndexStmt)
  910. if !ok {
  911. t.Fatalf("expected CreateIndexStmt, got %T", stmt)
  912. }
  913. if len(idx.Columns) != 2 {
  914. t.Fatalf("expected 2 columns, got %d", len(idx.Columns))
  915. }
  916. if idx.Columns[0].Name != "name" {
  917. t.Errorf("expected first column name, got %s", idx.Columns[0].Name)
  918. }
  919. if idx.Columns[1].Name != "email" {
  920. t.Errorf("expected second column email, got %s", idx.Columns[1].Name)
  921. }
  922. }
  923. func TestParseCreateIndexWithDesc(t *testing.T) {
  924. stmt := parse(t, "CREATE INDEX idx_created ON users (created_at DESC)")
  925. idx, ok := stmt.(*CreateIndexStmt)
  926. if !ok {
  927. t.Fatalf("expected CreateIndexStmt, got %T", stmt)
  928. }
  929. if len(idx.Columns) != 1 {
  930. t.Fatalf("expected 1 column, got %d", len(idx.Columns))
  931. }
  932. if !idx.Columns[0].Desc {
  933. t.Error("expected DESC ordering")
  934. }
  935. }
  936. // DROP INDEX tests
  937. func TestParseDropIndex(t *testing.T) {
  938. stmt := parse(t, "DROP INDEX idx_email")
  939. drop, ok := stmt.(*DropIndexStmt)
  940. if !ok {
  941. t.Fatalf("expected DropIndexStmt, got %T", stmt)
  942. }
  943. if drop.Name != "idx_email" {
  944. t.Errorf("expected index name idx_email, got %s", drop.Name)
  945. }
  946. if drop.IfExists {
  947. t.Error("expected IfExists to be false")
  948. }
  949. }
  950. func TestParseDropIndexIfExists(t *testing.T) {
  951. stmt := parse(t, "DROP INDEX IF EXISTS idx_email")
  952. drop, ok := stmt.(*DropIndexStmt)
  953. if !ok {
  954. t.Fatalf("expected DropIndexStmt, got %T", stmt)
  955. }
  956. if !drop.IfExists {
  957. t.Error("expected IfExists to be true")
  958. }
  959. }
  960. // Subquery in FROM clause tests
  961. func TestParseSelectFromSubquery(t *testing.T) {
  962. stmt := parse(t, "SELECT * FROM (SELECT id, name FROM users) AS u")
  963. sel, ok := stmt.(*SelectStmt)
  964. if !ok {
  965. t.Fatalf("expected SelectStmt, got %T", stmt)
  966. }
  967. if len(sel.From) != 1 {
  968. t.Fatalf("expected 1 FROM item, got %d", len(sel.From))
  969. }
  970. if sel.From[0].Subquery == nil {
  971. t.Fatal("expected subquery in FROM")
  972. }
  973. if sel.From[0].Alias != "u" {
  974. t.Errorf("expected alias 'u', got '%s'", sel.From[0].Alias)
  975. }
  976. // Check subquery
  977. subquery := sel.From[0].Subquery
  978. if len(subquery.Columns) != 2 {
  979. t.Errorf("expected 2 columns in subquery, got %d", len(subquery.Columns))
  980. }
  981. if len(subquery.From) != 1 || subquery.From[0].Name != "users" {
  982. t.Error("expected subquery FROM users")
  983. }
  984. }
  985. func TestParseSelectFromSubqueryWithWhere(t *testing.T) {
  986. stmt := parse(t, "SELECT name FROM (SELECT id, name FROM users WHERE active = TRUE) AS active_users WHERE id > 10")
  987. sel, ok := stmt.(*SelectStmt)
  988. if !ok {
  989. t.Fatalf("expected SelectStmt, got %T", stmt)
  990. }
  991. if sel.From[0].Subquery == nil {
  992. t.Fatal("expected subquery in FROM")
  993. }
  994. // Check outer WHERE clause
  995. if sel.Where == nil {
  996. t.Error("expected outer WHERE clause")
  997. }
  998. // Check subquery WHERE clause
  999. if sel.From[0].Subquery.Where == nil {
  1000. t.Error("expected subquery WHERE clause")
  1001. }
  1002. }
  1003. func TestParseSelectFromSubqueryComplex(t *testing.T) {
  1004. stmt := parse(t, "SELECT u.name, u.total FROM (SELECT user_id, SUM(amount) AS total FROM orders GROUP BY user_id) AS u")
  1005. sel, ok := stmt.(*SelectStmt)
  1006. if !ok {
  1007. t.Fatalf("expected SelectStmt, got %T", stmt)
  1008. }
  1009. if sel.From[0].Subquery == nil {
  1010. t.Fatal("expected subquery in FROM")
  1011. }
  1012. subquery := sel.From[0].Subquery
  1013. if len(subquery.GroupBy) == 0 {
  1014. t.Error("expected GROUP BY in subquery")
  1015. }
  1016. // Check that columns reference the alias
  1017. if len(sel.Columns) != 2 {
  1018. t.Fatalf("expected 2 columns, got %d", len(sel.Columns))
  1019. }
  1020. }
  1021. func TestParseSelectFromNestedSubquery(t *testing.T) {
  1022. stmt := parse(t, "SELECT * FROM (SELECT * FROM (SELECT id FROM users) AS inner_q) AS outer_q")
  1023. sel, ok := stmt.(*SelectStmt)
  1024. if !ok {
  1025. t.Fatalf("expected SelectStmt, got %T", stmt)
  1026. }
  1027. if sel.From[0].Subquery == nil {
  1028. t.Fatal("expected subquery in FROM")
  1029. }
  1030. // Check nested subquery
  1031. outerSubquery := sel.From[0].Subquery
  1032. if len(outerSubquery.From) == 0 || outerSubquery.From[0].Subquery == nil {
  1033. t.Error("expected nested subquery")
  1034. }
  1035. }
  1036. // ALTER TABLE tests
  1037. func TestParseAlterTableAddColumn(t *testing.T) {
  1038. stmt := parse(t, "ALTER TABLE users ADD COLUMN age INTEGER")
  1039. alter, ok := stmt.(*AlterTableStmt)
  1040. if !ok {
  1041. t.Fatalf("expected AlterTableStmt, got %T", stmt)
  1042. }
  1043. if alter.Table != "users" {
  1044. t.Errorf("expected table users, got %s", alter.Table)
  1045. }
  1046. action, ok := alter.Action.(*AddColumnAction)
  1047. if !ok {
  1048. t.Fatalf("expected AddColumnAction, got %T", alter.Action)
  1049. }
  1050. if action.Column.Name != "age" {
  1051. t.Errorf("expected column name age, got %s", action.Column.Name)
  1052. }
  1053. if action.Column.Type.Name != "INTEGER" {
  1054. t.Errorf("expected column type INTEGER, got %s", action.Column.Type.Name)
  1055. }
  1056. }
  1057. func TestParseAlterTableAddColumnOptional(t *testing.T) {
  1058. stmt := parse(t, "ALTER TABLE users ADD age INTEGER")
  1059. alter, ok := stmt.(*AlterTableStmt)
  1060. if !ok {
  1061. t.Fatalf("expected AlterTableStmt, got %T", stmt)
  1062. }
  1063. action, ok := alter.Action.(*AddColumnAction)
  1064. if !ok {
  1065. t.Fatalf("expected AddColumnAction, got %T", alter.Action)
  1066. }
  1067. if action.Column.Name != "age" {
  1068. t.Errorf("expected column name age, got %s", action.Column.Name)
  1069. }
  1070. }
  1071. func TestParseAlterTableDropColumn(t *testing.T) {
  1072. stmt := parse(t, "ALTER TABLE users DROP COLUMN email")
  1073. alter, ok := stmt.(*AlterTableStmt)
  1074. if !ok {
  1075. t.Fatalf("expected AlterTableStmt, got %T", stmt)
  1076. }
  1077. action, ok := alter.Action.(*DropColumnAction)
  1078. if !ok {
  1079. t.Fatalf("expected DropColumnAction, got %T", alter.Action)
  1080. }
  1081. if action.Column != "email" {
  1082. t.Errorf("expected column email, got %s", action.Column)
  1083. }
  1084. }
  1085. func TestParseAlterTableRename(t *testing.T) {
  1086. stmt := parse(t, "ALTER TABLE users RENAME TO customers")
  1087. alter, ok := stmt.(*AlterTableStmt)
  1088. if !ok {
  1089. t.Fatalf("expected AlterTableStmt, got %T", stmt)
  1090. }
  1091. action, ok := alter.Action.(*RenameTableAction)
  1092. if !ok {
  1093. t.Fatalf("expected RenameTableAction, got %T", alter.Action)
  1094. }
  1095. if action.NewName != "customers" {
  1096. t.Errorf("expected new name customers, got %s", action.NewName)
  1097. }
  1098. }
  1099. func TestParseAlterTableRenameColumn(t *testing.T) {
  1100. stmt := parse(t, "ALTER TABLE users RENAME COLUMN name TO full_name")
  1101. alter, ok := stmt.(*AlterTableStmt)
  1102. if !ok {
  1103. t.Fatalf("expected AlterTableStmt, got %T", stmt)
  1104. }
  1105. action, ok := alter.Action.(*RenameColumnAction)
  1106. if !ok {
  1107. t.Fatalf("expected RenameColumnAction, got %T", alter.Action)
  1108. }
  1109. if action.OldName != "name" {
  1110. t.Errorf("expected old name 'name', got %s", action.OldName)
  1111. }
  1112. if action.NewName != "full_name" {
  1113. t.Errorf("expected new name 'full_name', got %s", action.NewName)
  1114. }
  1115. }
  1116. // ATTACH/DETACH DATABASE tests
  1117. func TestParseAttach(t *testing.T) {
  1118. stmt := parse(t, "ATTACH DATABASE 'test.db' AS testdb")
  1119. attach, ok := stmt.(*AttachStmt)
  1120. if !ok {
  1121. t.Fatalf("expected AttachStmt, got %T", stmt)
  1122. }
  1123. if attach.FilePath != "test.db" {
  1124. t.Errorf("expected file path 'test.db', got '%s'", attach.FilePath)
  1125. }
  1126. if attach.Alias != "testdb" {
  1127. t.Errorf("expected alias 'testdb', got '%s'", attach.Alias)
  1128. }
  1129. }
  1130. func TestParseAttachOptional(t *testing.T) {
  1131. stmt := parse(t, "ATTACH 'another.db' AS other")
  1132. attach, ok := stmt.(*AttachStmt)
  1133. if !ok {
  1134. t.Fatalf("expected AttachStmt, got %T", stmt)
  1135. }
  1136. if attach.FilePath != "another.db" {
  1137. t.Errorf("expected file path 'another.db', got '%s'", attach.FilePath)
  1138. }
  1139. if attach.Alias != "other" {
  1140. t.Errorf("expected alias 'other', got '%s'", attach.Alias)
  1141. }
  1142. }
  1143. func TestParseDetach(t *testing.T) {
  1144. stmt := parse(t, "DETACH DATABASE testdb")
  1145. detach, ok := stmt.(*DetachStmt)
  1146. if !ok {
  1147. t.Fatalf("expected DetachStmt, got %T", stmt)
  1148. }
  1149. if detach.Alias != "testdb" {
  1150. t.Errorf("expected alias 'testdb', got '%s'", detach.Alias)
  1151. }
  1152. }
  1153. func TestParseDetachOptional(t *testing.T) {
  1154. stmt := parse(t, "DETACH other")
  1155. detach, ok := stmt.(*DetachStmt)
  1156. if !ok {
  1157. t.Fatalf("expected DetachStmt, got %T", stmt)
  1158. }
  1159. if detach.Alias != "other" {
  1160. t.Errorf("expected alias 'other', got '%s'", detach.Alias)
  1161. }
  1162. }