shard-crystal-sqlite3/src/sqlite3/connection.cr

52 lines
1.2 KiB
Crystal
Raw Normal View History

class SQLite3::Connection < DB::Connection
2016-02-04 00:29:19 +00:00
def initialize(database)
super
2016-02-04 00:29:19 +00:00
filename = self.class.filename(database.uri)
# TODO maybe enable Flag::URI to parse query string in the uri as additional flags
check LibSQLite3.open_v2(filename, out @db, (Flag::READWRITE | Flag::CREATE), nil)
end
2016-02-04 00:29:19 +00:00
def self.filename(uri : URI)
URI.unescape (if path = uri.path
(uri.host || "") + path
else
uri.opaque.not_nil!
end)
end
2016-02-04 00:29:19 +00:00
def build_statement(query)
2016-02-04 00:52:45 +00:00
Statement.new(self, query)
end
2016-02-04 00:29:19 +00:00
def do_close
super
LibSQLite3.close_v2(self)
end
# Dump the database to another SQLite3 database. This can be used for backing up a SQLite3 Database
# to disk or the opposite
def dump(to : SQLite3::Connection)
backup_item = LibSQLite3.backup_init(to.@db, "main", @db, "main")
if backup_item.null?
raise Exception.new(to.@db)
end
code = LibSQLite3.backup_step(backup_item, -1)
if code != LibSQLite3::Code::DONE
raise Exception.new(to.@db)
end
code = LibSQLite3.backup_finish(backup_item)
if code != LibSQLite3::Code::OKAY
raise Exception.new(to.@db)
end
end
def to_unsafe
@db
end
private def check(code)
raise Exception.new(self) unless code == 0
end
end