2
0

main.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. // sqllogictest runner — sends SQL via HTTP to a running PizzaSQL server and
  2. // compares results against the expected output in .test files.
  3. //
  4. // File format: https://www.sqlite.org/sqllogictest/doc/trunk/about.wiki
  5. //
  6. // Usage:
  7. //
  8. // go run ./cmd/sqllogictest -url http://localhost:8080 -dir testdata/sqllogictest
  9. package main
  10. import (
  11. "bufio"
  12. "bytes"
  13. "crypto/md5"
  14. "flag"
  15. "fmt"
  16. "math"
  17. "net/http"
  18. "os"
  19. "path/filepath"
  20. "sort"
  21. "strconv"
  22. "strings"
  23. "time"
  24. "github.com/goccy/go-json"
  25. )
  26. const engineName = "pizzasql"
  27. // ANSI color helpers
  28. const (
  29. colorReset = "\033[0m"
  30. colorRed = "\033[31m"
  31. colorGreen = "\033[32m"
  32. colorYellow = "\033[33m"
  33. colorCyan = "\033[36m"
  34. colorBold = "\033[1m"
  35. colorDim = "\033[2m"
  36. )
  37. // ── types ────────────────────────────────────────────────────────────────────
  38. type lineInfo struct {
  39. text string
  40. num int
  41. }
  42. type record struct {
  43. isStatement bool
  44. isQuery bool
  45. expectOK bool // statement: true → expect success
  46. typeStr string // query: column type chars (I/R/T)
  47. sortMode string // nosort | rowsort | valuesort
  48. label string
  49. sql string
  50. expected []string // flattened expected values, one per line
  51. skip bool
  52. file string
  53. line int
  54. }
  55. type queryRequest struct {
  56. SQL string `json:"sql"`
  57. }
  58. type queryResponse struct {
  59. Columns []struct {
  60. Name string `json:"name"`
  61. Type string `json:"type"`
  62. } `json:"columns"`
  63. Rows [][]interface{} `json:"rows"`
  64. Error *struct {
  65. Code string `json:"code"`
  66. Message string `json:"message"`
  67. } `json:"error"`
  68. }
  69. // ── runner ───────────────────────────────────────────────────────────────────
  70. type runner struct {
  71. baseURL string
  72. client *http.Client
  73. verbose bool
  74. stopOnFail bool
  75. passed int
  76. failed int
  77. skipped int
  78. total int // total files to run
  79. filesDone int // files completed
  80. logW *bufio.Writer
  81. logPath string
  82. }
  83. func main() {
  84. urlFlag := flag.String("url", "http://localhost:8080", "PizzaSQL server URL")
  85. dirFlag := flag.String("dir", "testdata/sqllogictest", "Directory containing .test files")
  86. fileFlag := flag.String("file", "", "Single .test file to run (overrides -dir)")
  87. verboseFlag := flag.Bool("v", false, "Print each passing record")
  88. stopFlag := flag.Bool("stop", false, "Stop on first failure")
  89. logFlag := flag.String("log", "sqllogictest-failures.log", "File to write failures to ('' to disable)")
  90. flag.Parse()
  91. r := &runner{
  92. baseURL: strings.TrimRight(*urlFlag, "/"),
  93. client: &http.Client{Timeout: 120 * time.Second},
  94. verbose: *verboseFlag,
  95. stopOnFail: *stopFlag,
  96. logPath: *logFlag,
  97. }
  98. if *logFlag != "" {
  99. lf, err := os.Create(*logFlag)
  100. if err != nil {
  101. fmt.Fprintf(os.Stderr, "cannot open log file: %v\n", err)
  102. os.Exit(1)
  103. }
  104. defer lf.Close()
  105. r.logW = bufio.NewWriter(lf)
  106. defer r.logW.Flush()
  107. }
  108. var files []string
  109. if *fileFlag != "" {
  110. files = []string{*fileFlag}
  111. } else {
  112. err := filepath.WalkDir(*dirFlag, func(path string, d os.DirEntry, err error) error {
  113. if err != nil {
  114. return err
  115. }
  116. if !d.IsDir() && strings.HasSuffix(path, ".test") {
  117. files = append(files, path)
  118. }
  119. return nil
  120. })
  121. if err != nil || len(files) == 0 {
  122. fmt.Fprintf(os.Stderr, "no .test files found in %s\n", *dirFlag)
  123. os.Exit(1)
  124. }
  125. sort.Strings(files)
  126. }
  127. r.total = len(files)
  128. start := time.Now()
  129. for _, f := range files {
  130. if err := r.runFile(f, start); err != nil {
  131. fmt.Fprintf(os.Stderr, "error in %s: %v\n", f, err)
  132. }
  133. if r.stopOnFail && r.failed > 0 {
  134. break
  135. }
  136. }
  137. // clear the progress line
  138. fmt.Print("\r\033[K")
  139. total := r.passed + r.failed
  140. elapsed := time.Since(start).Round(time.Millisecond)
  141. passColor, failColor := colorGreen, colorDim
  142. if r.failed > 0 {
  143. failColor = colorRed
  144. }
  145. pct := 0.0
  146. if total > 0 {
  147. pct = 100.0 * float64(r.passed) / float64(total)
  148. }
  149. fmt.Printf("%s--- Summary ---%s\n", colorBold, colorReset)
  150. var summaryQPS string
  151. if secs := elapsed.Seconds(); secs > 0 && total > 0 {
  152. qps := float64(total) / secs
  153. switch {
  154. case qps >= 1_000_000:
  155. summaryQPS = fmt.Sprintf("%.2fM q/s", qps/1_000_000)
  156. case qps >= 1_000:
  157. summaryQPS = fmt.Sprintf("%.2fk q/s", qps/1_000)
  158. default:
  159. summaryQPS = fmt.Sprintf("%.0f q/s", qps)
  160. }
  161. }
  162. fmt.Printf("passed: %s%d/%d (%.1f%%)%s\n", passColor, r.passed, total, pct, colorReset)
  163. fmt.Printf("failed: %s%d%s\n", failColor, r.failed, colorReset)
  164. fmt.Printf("skipped: %d\n", r.skipped)
  165. fmt.Printf("time: %s\n", elapsed)
  166. fmt.Printf("thru: %s%s%s\n", colorCyan, summaryQPS, colorReset)
  167. if r.failed > 0 && *logFlag != "" {
  168. fmt.Printf("log: %s%s%s\n", colorCyan, *logFlag, colorReset)
  169. }
  170. if r.failed > 0 {
  171. os.Exit(1)
  172. }
  173. }
  174. func (r *runner) runFile(path string, start time.Time) error {
  175. f, err := os.Open(path)
  176. if err != nil {
  177. return err
  178. }
  179. defer f.Close()
  180. records, err := parseFile(path, f)
  181. if err != nil {
  182. return err
  183. }
  184. // Drop any tables/views this file creates so it always runs against a clean state.
  185. for _, tbl := range collectCreatedTables(records) {
  186. r.execQuery("DROP TABLE IF EXISTS " + tbl) //nolint:errcheck
  187. }
  188. for _, v := range collectCreatedViews(records) {
  189. r.execQuery("DROP VIEW IF EXISTS " + v) //nolint:errcheck
  190. }
  191. labelCache := make(map[string][]string) // label → first result
  192. failsBefore := r.failed
  193. for _, rec := range records {
  194. if r.stopOnFail && r.failed > 0 {
  195. break
  196. }
  197. if rec.skip {
  198. r.skipped++
  199. continue
  200. }
  201. r.runRecord(rec, labelCache)
  202. r.printProgress(path, start)
  203. }
  204. r.filesDone++
  205. newFails := r.failed - failsBefore
  206. rel, _ := filepath.Rel("testdata/sqllogictest", path)
  207. if rel == "" {
  208. rel = filepath.Base(path)
  209. }
  210. var statusStr string
  211. if newFails == 0 {
  212. statusStr = colorGreen + "ok" + colorReset
  213. } else {
  214. statusStr = fmt.Sprintf("%s%d FAILED%s", colorRed, newFails, colorReset)
  215. }
  216. fmt.Printf("\r\033[K%s[%d/%d]%s %-52s %s\n", colorDim, r.filesDone, r.total, colorReset, rel, statusStr)
  217. return nil
  218. }
  219. func (r *runner) printProgress(currentFile string, start time.Time) {
  220. rel, _ := filepath.Rel("testdata/sqllogictest", currentFile)
  221. if rel == "" {
  222. rel = filepath.Base(currentFile)
  223. }
  224. elapsed := time.Since(start)
  225. elapsedStr := elapsed.Round(time.Second).String()
  226. var etaStr string
  227. if r.filesDone > 0 {
  228. rate := float64(r.filesDone) / elapsed.Seconds()
  229. eta := time.Duration(float64(r.total-r.filesDone) / rate * float64(time.Second)).Round(time.Second)
  230. etaStr = "eta " + eta.String()
  231. } else {
  232. etaStr = "eta --"
  233. }
  234. checked := r.passed + r.failed
  235. var rateStr string
  236. if checked > 0 {
  237. pct := 100.0 * float64(r.passed) / float64(checked)
  238. color := colorRed
  239. if r.failed == 0 {
  240. color = colorGreen
  241. } else if pct >= 90 {
  242. color = colorYellow
  243. }
  244. rateStr = fmt.Sprintf("%s%.1f%%%s", color, pct, colorReset)
  245. } else {
  246. rateStr = " --.--%"
  247. }
  248. var throughputStr string
  249. if secs := elapsed.Seconds(); secs > 0 && checked > 0 {
  250. qps := float64(checked) / secs
  251. switch {
  252. case qps >= 1_000_000:
  253. throughputStr = fmt.Sprintf("%.1fM q/s", qps/1_000_000)
  254. case qps >= 1_000:
  255. throughputStr = fmt.Sprintf("%.1fk q/s", qps/1_000)
  256. default:
  257. throughputStr = fmt.Sprintf("%.0f q/s", qps)
  258. }
  259. } else {
  260. throughputStr = "-- q/s"
  261. }
  262. fmt.Printf("\r\033[K%s[%d/%d]%s %-40s %s pass=%-6d %sfail=%-5d%s skip=%-5d %s / %s %s%s%s",
  263. colorDim, r.filesDone+1, r.total, colorReset,
  264. rel, rateStr,
  265. r.passed,
  266. colorRed, r.failed, colorReset,
  267. r.skipped,
  268. elapsedStr, etaStr,
  269. colorCyan, throughputStr, colorReset,
  270. )
  271. }
  272. // collectCreatedTables scans records for CREATE TABLE statements and returns
  273. // the table names so they can be pre-dropped before each test file runs.
  274. func collectCreatedViews(records []*record) []string {
  275. seen := map[string]bool{}
  276. var views []string
  277. for _, rec := range records {
  278. if !rec.isStatement {
  279. continue
  280. }
  281. fields := strings.Fields(rec.sql)
  282. if len(fields) < 3 {
  283. continue
  284. }
  285. if !strings.EqualFold(fields[0], "CREATE") || !strings.EqualFold(fields[1], "VIEW") {
  286. continue
  287. }
  288. idx := 2
  289. if strings.EqualFold(fields[idx], "IF") && len(fields) > idx+2 {
  290. idx = 5
  291. }
  292. if idx < len(fields) {
  293. name := strings.TrimSuffix(fields[idx], ";")
  294. if name != "" && !seen[name] {
  295. seen[name] = true
  296. views = append(views, name)
  297. }
  298. }
  299. }
  300. return views
  301. }
  302. func collectCreatedTables(records []*record) []string {
  303. seen := map[string]bool{}
  304. var tables []string
  305. for _, rec := range records {
  306. if !rec.isStatement {
  307. continue
  308. }
  309. fields := strings.Fields(rec.sql)
  310. if len(fields) < 3 {
  311. continue
  312. }
  313. if !strings.EqualFold(fields[0], "CREATE") || !strings.EqualFold(fields[1], "TABLE") {
  314. continue
  315. }
  316. idx := 2
  317. if strings.EqualFold(fields[idx], "IF") && len(fields) > idx+2 {
  318. idx = 5 // CREATE TABLE IF NOT EXISTS <name>
  319. }
  320. if idx < len(fields) {
  321. name := strings.TrimSuffix(strings.TrimSuffix(fields[idx], "("), ";")
  322. if name != "" && !seen[name] {
  323. seen[name] = true
  324. tables = append(tables, name)
  325. }
  326. }
  327. }
  328. return tables
  329. }
  330. func (r *runner) runRecord(rec *record, labelCache map[string][]string) {
  331. resp, err := r.execQuery(rec.sql)
  332. if err != nil {
  333. r.fail(rec, "http error: %v", err)
  334. return
  335. }
  336. if rec.isStatement {
  337. if rec.expectOK {
  338. if resp.Error != nil {
  339. r.fail(rec, "expected ok, got error: %s", resp.Error.Message)
  340. } else {
  341. r.pass(rec)
  342. }
  343. } else {
  344. if resp.Error == nil {
  345. r.fail(rec, "expected error, got ok")
  346. } else {
  347. r.pass(rec)
  348. }
  349. }
  350. return
  351. }
  352. // query record
  353. if resp.Error != nil {
  354. r.fail(rec, "unexpected error: %s", resp.Error.Message)
  355. return
  356. }
  357. got := r.formatResults(resp, rec.typeStr)
  358. ncols := len(rec.typeStr)
  359. if ncols == 0 {
  360. ncols = 1
  361. }
  362. // Apply sort before any comparison.
  363. switch rec.sortMode {
  364. case "rowsort":
  365. got = sortRows(got, ncols)
  366. case "valuesort":
  367. g := append([]string(nil), got...)
  368. sort.Strings(g)
  369. got = g
  370. }
  371. // Label caching: if this query has a label, compare against first occurrence.
  372. if rec.label != "" {
  373. if cached, seen := labelCache[rec.label]; seen {
  374. if !equalSlices(got, cached) {
  375. r.fail(rec, "label %q result mismatch\n want: %v\n got: %v", rec.label, cached, got)
  376. } else {
  377. r.pass(rec)
  378. }
  379. return
  380. }
  381. // First occurrence: store and fall through to normal expected-value check.
  382. labelCache[rec.label] = got
  383. }
  384. // hash format: "N values hashing to <md5>"
  385. if len(rec.expected) == 1 {
  386. parts := strings.Fields(rec.expected[0])
  387. if len(parts) == 5 && parts[1] == "values" && parts[2] == "hashing" && parts[3] == "to" {
  388. wantCount, _ := strconv.Atoi(parts[0])
  389. wantHash := parts[4]
  390. if len(got) != wantCount {
  391. r.fail(rec, "hash record: want %d values got %d", wantCount, len(got))
  392. return
  393. }
  394. h := md5.Sum([]byte(strings.Join(got, "\n") + "\n"))
  395. gotHash := fmt.Sprintf("%x", h)
  396. if gotHash != wantHash {
  397. r.fail(rec, "hash mismatch: want %s got %s", wantHash, gotHash)
  398. return
  399. }
  400. r.pass(rec)
  401. return
  402. }
  403. }
  404. exp := rec.expected
  405. switch rec.sortMode {
  406. case "rowsort":
  407. exp = sortRows(exp, ncols)
  408. case "valuesort":
  409. e := append([]string(nil), exp...)
  410. sort.Strings(e)
  411. exp = e
  412. }
  413. if !equalSlices(got, exp) {
  414. r.fail(rec, "result mismatch\n want: %v\n got: %v", exp, got)
  415. } else {
  416. r.pass(rec)
  417. }
  418. }
  419. // ── formatting ───────────────────────────────────────────────────────────────
  420. func (r *runner) formatResults(resp *queryResponse, typeStr string) []string {
  421. var vals []string
  422. for _, row := range resp.Rows {
  423. for i, v := range row {
  424. ct := byte('T')
  425. if i < len(typeStr) {
  426. ct = typeStr[i]
  427. }
  428. vals = append(vals, formatValue(v, ct))
  429. }
  430. }
  431. return vals
  432. }
  433. // formatValue converts a JSON value to the string representation expected by
  434. // the sqllogictest format. Type chars: I=integer, R=real (%.3g), T=text.
  435. func formatValue(v interface{}, colType byte) string {
  436. if v == nil {
  437. return "NULL"
  438. }
  439. switch colType {
  440. case 'I':
  441. switch n := v.(type) {
  442. case float64:
  443. return strconv.FormatInt(int64(n), 10)
  444. case int64:
  445. return strconv.FormatInt(n, 10)
  446. case int:
  447. return strconv.Itoa(n)
  448. case bool:
  449. if n {
  450. return "1"
  451. }
  452. return "0"
  453. case string:
  454. if i, err := strconv.ParseInt(n, 10, 64); err == nil {
  455. return strconv.FormatInt(i, 10)
  456. }
  457. return "0"
  458. default:
  459. return fmt.Sprintf("%v", v)
  460. }
  461. case 'R':
  462. switch n := v.(type) {
  463. case float64:
  464. return strconv.FormatFloat(n, 'g', 3, 64)
  465. case int64:
  466. return strconv.FormatFloat(float64(n), 'g', 3, 64)
  467. case int:
  468. return strconv.FormatFloat(float64(n), 'g', 3, 64)
  469. case string:
  470. if f, err := strconv.ParseFloat(n, 64); err == nil {
  471. return strconv.FormatFloat(f, 'g', 3, 64)
  472. }
  473. return "0"
  474. default:
  475. return fmt.Sprintf("%v", v)
  476. }
  477. default: // T
  478. switch s := v.(type) {
  479. case string:
  480. return s
  481. case bool:
  482. if s {
  483. return "1"
  484. }
  485. return "0"
  486. case float64:
  487. if s == math.Trunc(s) && !math.IsInf(s, 0) {
  488. return strconv.FormatInt(int64(s), 10)
  489. }
  490. return fmt.Sprintf("%g", s)
  491. default:
  492. return fmt.Sprintf("%v", v)
  493. }
  494. }
  495. }
  496. // ── helpers ───────────────────────────────────────────────────────────────────
  497. func sortRows(vals []string, ncols int) []string {
  498. if ncols <= 0 || len(vals) == 0 {
  499. return vals
  500. }
  501. nrows := len(vals) / ncols
  502. rows := make([][]string, nrows)
  503. for i := range rows {
  504. s, e := i*ncols, i*ncols+ncols
  505. if e > len(vals) {
  506. e = len(vals)
  507. }
  508. rows[i] = vals[s:e]
  509. }
  510. sort.Slice(rows, func(i, j int) bool {
  511. for k := 0; k < len(rows[i]) && k < len(rows[j]); k++ {
  512. if rows[i][k] != rows[j][k] {
  513. return rows[i][k] < rows[j][k]
  514. }
  515. }
  516. return len(rows[i]) < len(rows[j])
  517. })
  518. out := make([]string, 0, len(vals))
  519. for _, row := range rows {
  520. out = append(out, row...)
  521. }
  522. return out
  523. }
  524. func equalSlices(a, b []string) bool {
  525. if len(a) != len(b) {
  526. return false
  527. }
  528. for i := range a {
  529. if a[i] != b[i] {
  530. return false
  531. }
  532. }
  533. return true
  534. }
  535. func (r *runner) execQuery(sql string) (*queryResponse, error) {
  536. body, _ := json.Marshal(queryRequest{SQL: sql})
  537. resp, err := r.client.Post(r.baseURL+"/query", "application/json", bytes.NewReader(body))
  538. if err != nil {
  539. return nil, err
  540. }
  541. defer resp.Body.Close()
  542. var qr queryResponse
  543. if err := json.NewDecoder(resp.Body).Decode(&qr); err != nil {
  544. return nil, fmt.Errorf("decode response: %w", err)
  545. }
  546. return &qr, nil
  547. }
  548. func (r *runner) pass(rec *record) {
  549. r.passed++
  550. if r.verbose && r.logW != nil {
  551. fmt.Fprintf(r.logW, " ok %s:%d\n", rec.file, rec.line)
  552. }
  553. }
  554. func (r *runner) fail(rec *record, format string, args ...interface{}) {
  555. r.failed++
  556. msg := fmt.Sprintf(format, args...)
  557. sql := strings.ReplaceAll(strings.TrimSpace(rec.sql), "\n", " ")
  558. if len(sql) > 120 {
  559. sql = sql[:117] + "..."
  560. }
  561. line := fmt.Sprintf("FAIL %s:%d: %s\n SQL: %s\n", rec.file, rec.line, msg, sql)
  562. if r.logW != nil {
  563. fmt.Fprint(r.logW, line)
  564. r.logW.Flush()
  565. } else {
  566. fmt.Print(line)
  567. }
  568. }
  569. // ── parser ────────────────────────────────────────────────────────────────────
  570. // parseFile reads a sqllogictest file and returns all records.
  571. func parseFile(path string, f *os.File) ([]*record, error) {
  572. scanner := bufio.NewScanner(f)
  573. var lines []lineInfo
  574. n := 0
  575. for scanner.Scan() {
  576. n++
  577. text := scanner.Text()
  578. if !strings.HasPrefix(strings.TrimSpace(text), "#") {
  579. lines = append(lines, lineInfo{text: text, num: n})
  580. }
  581. }
  582. if err := scanner.Err(); err != nil {
  583. return nil, err
  584. }
  585. // split into blocks separated by blank lines
  586. var blocks [][]lineInfo
  587. var cur []lineInfo
  588. for _, li := range lines {
  589. if strings.TrimSpace(li.text) == "" {
  590. if len(cur) > 0 {
  591. blocks = append(blocks, cur)
  592. cur = nil
  593. }
  594. } else {
  595. cur = append(cur, li)
  596. }
  597. }
  598. if len(cur) > 0 {
  599. blocks = append(blocks, cur)
  600. }
  601. var records []*record
  602. haltSeen := false
  603. skipNext := false
  604. for _, block := range blocks {
  605. if haltSeen {
  606. break
  607. }
  608. // consume skipif / onlyif lines at the top of the block
  609. i := 0
  610. for i < len(block) {
  611. lower := strings.ToLower(strings.TrimSpace(block[i].text))
  612. if strings.HasPrefix(lower, "skipif ") {
  613. engine := strings.TrimSpace(block[i].text[7:])
  614. if strings.EqualFold(engine, engineName) {
  615. skipNext = true
  616. }
  617. i++
  618. } else if strings.HasPrefix(lower, "onlyif ") {
  619. engine := strings.TrimSpace(block[i].text[7:])
  620. if !strings.EqualFold(engine, engineName) {
  621. skipNext = true
  622. }
  623. i++
  624. } else {
  625. break
  626. }
  627. }
  628. if i >= len(block) {
  629. continue
  630. }
  631. directiveLine := block[i]
  632. parts := strings.Fields(directiveLine.text)
  633. if len(parts) == 0 {
  634. continue
  635. }
  636. rec := &record{file: path, line: directiveLine.num, skip: skipNext}
  637. skipNext = false
  638. body := block[i+1:]
  639. switch parts[0] {
  640. case "halt":
  641. haltSeen = true
  642. continue
  643. case "statement":
  644. rec.isStatement = true
  645. rec.expectOK = len(parts) > 1 && parts[1] == "ok"
  646. var sqlLines []string
  647. for _, li := range body {
  648. sqlLines = append(sqlLines, li.text)
  649. }
  650. rec.sql = strings.Join(sqlLines, "\n")
  651. case "query":
  652. rec.isQuery = true
  653. if len(parts) > 1 {
  654. rec.typeStr = strings.ToUpper(parts[1])
  655. }
  656. if len(parts) > 2 {
  657. rec.sortMode = parts[2]
  658. } else {
  659. rec.sortMode = "nosort"
  660. }
  661. if len(parts) > 3 {
  662. rec.label = parts[3]
  663. }
  664. inResults := false
  665. var sqlLines []string
  666. for _, li := range body {
  667. if strings.TrimSpace(li.text) == "----" {
  668. inResults = true
  669. continue
  670. }
  671. if inResults {
  672. rec.expected = append(rec.expected, strings.TrimSpace(li.text))
  673. } else {
  674. sqlLines = append(sqlLines, li.text)
  675. }
  676. }
  677. rec.sql = strings.Join(sqlLines, "\n")
  678. default:
  679. continue
  680. }
  681. if strings.TrimSpace(rec.sql) == "" {
  682. continue
  683. }
  684. records = append(records, rec)
  685. }
  686. return records, nil
  687. }