parseSQLFile parses the content of a SQL file into an SQLMigration struct It looks for the up and down annotations to split the file into up and down migrations example of file: -- migrate:up tx=true CREATE TABLE users (id INT PRIMARY KEY, name TEXT); -- migrate:down tx=false DROP TABLE users; In th
(fileContent []byte, config Configuration)
| 157 | // DROP TABLE users; |
| 158 | // In this example, the up migration will be run in a transaction, while the down migration will not |
| 159 | func parseSQLFile(fileContent []byte, config Configuration) (SQLMigration, error) { |
| 160 | file := SQLMigration{ |
| 161 | up: "", |
| 162 | down: "", |
| 163 | txUp: true, |
| 164 | txDown: true, |
| 165 | } |
| 166 | |
| 167 | var upLines, downLines [][]byte |
| 168 | var current *[][]byte // nil = before up, &upLines = in up, &downLines = in down |
| 169 | |
| 170 | txRegexp := regexp.MustCompile(`tx=(true|false)`) |
| 171 | scanner := bufio.NewScanner(bytes.NewReader(fileContent)) |
| 172 | for scanner.Scan() { |
| 173 | line := scanner.Bytes() |
| 174 | |
| 175 | if bytes.HasPrefix(line, []byte(config.SQLFileUpAnnotation)) { |
| 176 | parseTxAnnotation(scanner.Text(), &file.txUp, txRegexp) |
| 177 | current = &upLines |
| 178 | continue |
| 179 | } |
| 180 | if bytes.HasPrefix(line, []byte(config.SQLFileDownAnnotation)) { |
| 181 | parseTxAnnotation(scanner.Text(), &file.txDown, txRegexp) |
| 182 | current = &downLines |
| 183 | continue |
| 184 | } |
| 185 | |
| 186 | if current != nil { |
| 187 | *current = append(*current, bytes.Clone(line)) // Clone car scanner réutilise le buffer |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | if err := scanner.Err(); err != nil { |
| 192 | return file, fmt.Errorf("failed to scan file: %w", err) |
| 193 | } |
| 194 | |
| 195 | file.up = string(bytes.Join(upLines, []byte("\n"))) |
| 196 | file.down = string(bytes.Join(downLines, []byte("\n"))) |
| 197 | |
| 198 | return file, nil |
| 199 | } |
| 200 | |
| 201 | // parseTxAnnotation parses the tx annotation from the given text and sets the value of b accordingly |
| 202 | // A typical refexp is regexp.MustCompile(`tx=(true|false)`) |