Skip to content

Instantly share code, notes, and snippets.

@jdriscoll
Last active August 29, 2015 14:22
Show Gist options
  • Save jdriscoll/3d80af82cde0292b6d38 to your computer and use it in GitHub Desktop.
Save jdriscoll/3d80af82cde0292b6d38 to your computer and use it in GitHub Desktop.
Load SQL queries from text file
-- all_things
SELECT * FROM things
-- thing_with_id
SELECT * FROM things WHERE id = :id
import Foundation
class Sequel {
static let sharedInstance = Sequel()
var queries: [String: String] = [:]
init() {
let path = NSBundle.mainBundle().pathForResource("Queries", ofType: "sql")
var err: NSError?
if let text = NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: &err) {
let lines = text.componentsSeparatedByString("\n") as! [String]
var curKey: String?
var curSql: String?
for line in lines {
if line.isEmpty {
continue
}
// New query
if line.hasPrefix("--") {
// Save the last query we parsed
if let key = curKey, let sql = curSql {
queries[key] = sql
}
curKey = line.substringFromIndex(advance(line.startIndex, 2)).trim()
curSql = nil
}
else {
if let sql = curSql {
curSql = join(" ", [sql, line.trim()])
}
else {
curSql = line.trim()
}
}
}
// Save the last query we parsed
if let key = curKey, let sql = curSql {
queries[key] = sql
}
}
else {
fatalError("Unable to load queries: \(err)")
}
}
subscript(key: String) -> String {
return queries[key]!
}
}
@jdriscoll
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment