Last active
August 29, 2015 14:22
-
-
Save jdriscoll/3d80af82cde0292b6d38 to your computer and use it in GitHub Desktop.
Load SQL queries from text file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- all_things | |
SELECT * FROM things | |
-- thing_with_id | |
SELECT * FROM things WHERE id = :id |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uses String.trim() extension found here: http://themainthread.com/blog/2015/04/trim-a-string-in-swift.html