Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293/// Splits a migration file into individual statements.////// PostgresNIO sends every query through the extended protocol, which allows/// exactly one statement per query, while the migration files hold many. The/// splitter understands `--` comments, single-quoted strings, double-quoted/// identifiers and `$tag$` dollar quoting, so a semicolon inside any of those/// does not end a statement. The file's checksum is still computed over the/// raw bytes, so this never changes what `schema_migrations` records.enum SQLStatementSplitter { static func split(_ sql: String) -> [String] { var statements: [String] = [] var current = "" let characters = Array(sql) var index = 0
func flush() { let trimmed = current.trimmingCharacters(in: .whitespacesAndNewlines) if !trimmed.isEmpty { statements.append(trimmed) } current = "" }
while index < characters.count { let character = characters[index] let next: Character? = index + 1 < characters.count ? characters[index + 1] : nil
if character == "-", next == "-" { // Line comment: skip to the end of the line, keeping the newline. while index < characters.count, characters[index] != "\n" { index += 1 } continue } if character == "'" || character == "\"" { let quote = character current.append(character) index += 1 while index < characters.count { current.append(characters[index]) if characters[index] == quote { if index + 1 < characters.count, characters[index + 1] == quote { current.append(characters[index + 1]) index += 2 continue } break } index += 1 } index += 1 continue } if character == "$", let tag = dollarTag(characters, at: index) { let end = findDollarTagEnd(characters, from: index + tag.count, tag: tag) current.append(contentsOf: characters[index..<end]) index = end continue } if character == ";" { flush() index += 1 continue } current.append(character) index += 1 } flush() return statements }
/// Returns the full `$tag$` token starting at `index`, or nil. private static func dollarTag(_ characters: [Character], at index: Int) -> [Character]? { var end = index + 1 while end < characters.count, characters[end].isLetter || characters[end].isNumber || characters[end] == "_" { end += 1 } guard end < characters.count, characters[end] == "$" else { return nil } return Array(characters[index...end]) }
private static func findDollarTagEnd(_ characters: [Character], from start: Int, tag: [Character]) -> Int { var index = start while index + tag.count <= characters.count { if Array(characters[index..<(index + tag.count)]) == tag { return index + tag.count } index += 1 } return characters.count }}