LoadAndSplitQueryFromReaders loads and split cql / sql query into one statement per string. Comments are removed from the query.
( readers []io.Reader, )
| 53 | // LoadAndSplitQueryFromReaders loads and split cql / sql query into one statement per string. |
| 54 | // Comments are removed from the query. |
| 55 | func LoadAndSplitQueryFromReaders( |
| 56 | readers []io.Reader, |
| 57 | ) ([]string, error) { |
| 58 | result := make([]string, 0, querySliceDefaultSize) |
| 59 | for _, r := range readers { |
| 60 | content, err := io.ReadAll(r) |
| 61 | if err != nil { |
| 62 | return nil, fmt.Errorf("error reading contents: %w", err) |
| 63 | } |
| 64 | n := len(content) |
| 65 | contentStr := string(bytes.ToLower(content)) |
| 66 | for i, j := 0, 0; i < n; i = j { |
| 67 | // stack to keep track of open parenthesis/blocks |
| 68 | var st []byte |
| 69 | var stmtBuilder strings.Builder |
| 70 | |
| 71 | stmtLoop: |
| 72 | for ; j < n; j++ { |
| 73 | switch contentStr[j] { |
| 74 | case queryDelimiter: |
| 75 | if len(st) == 0 { |
| 76 | j++ |
| 77 | break stmtLoop |
| 78 | } |
| 79 | |
| 80 | case sqlLeftParenthesis: |
| 81 | st = append(st, sqlLeftParenthesis) |
| 82 | |
| 83 | case sqlRightParenthesis: |
| 84 | if len(st) == 0 || st[len(st)-1] != sqlLeftParenthesis { |
| 85 | return nil, fmt.Errorf("error reading contents: unmatched right parenthesis") |
| 86 | } |
| 87 | st = st[:len(st)-1] |
| 88 | |
| 89 | case sqlDoubleDollarKeyword[0]: |
| 90 | if !hasWordAt(contentStr, sqlDoubleDollarKeyword, j) { |
| 91 | continue |
| 92 | } |
| 93 | if len(st) == 0 || st[len(st)-1] != sqlDoubleDollarKeyword[0] { |
| 94 | st = append(st, sqlDoubleDollarKeyword[0]) |
| 95 | j += len(sqlDoubleDollarKeyword) - 1 |
| 96 | } else { |
| 97 | st = st[:len(st)-1] |
| 98 | j += len(sqlDoubleDollarKeyword) - 1 |
| 99 | } |
| 100 | |
| 101 | case sqlIfKeyword[0]: |
| 102 | if !hasWordAt(contentStr, sqlIfKeyword, j) { |
| 103 | continue |
| 104 | } |
| 105 | if hasWordsBefore(contentStr, j-1, sqlAddKeyword, sqlColumnKeyword) || |
| 106 | hasWordsBefore(contentStr, j-1, sqlCreateKeyword, sqlIndexKeyword) || |
| 107 | hasWordsBefore(contentStr, j-1, sqlCreateKeyword, sqlIndexKeyword, sqlConcurrentlyKeyword) || |
| 108 | hasWordsBefore(contentStr, j-1, sqlCreateKeyword, sqlTableKeyword) { |
| 109 | continue |
| 110 | } |
| 111 | st = append(st, sqlIfKeyword[0]) |
| 112 | j += len(sqlIfKeyword) - 1 |