summary refs log tree commit diff homepage
path: root/sqlite.cr
diff options
context:
space:
mode:
Diffstat (limited to 'sqlite.cr')
-rw-r--r--sqlite.cr17
1 files changed, 13 insertions, 4 deletions
diff --git a/sqlite.cr b/sqlite.cr
index 4cca647..5dfbe4d 100644
--- a/sqlite.cr
+++ b/sqlite.cr
@@ -26,6 +26,9 @@ lib SQLite
   type Statement = Void*
 
   fun errstr = sqlite3_errstr(rc : LibC::Int) : LibC::Char*
+  fun mprintf = sqlite3_mprintf(format : LibC::Char*, ...) : LibC::Char*
+  fun free = sqlite3_free(format : Void*, ...)
+
   fun open = sqlite3_open(filename : LibC::Char*, db : Database*) : LibC::Int
   fun prepare = sqlite3_prepare(db : Database, query : LibC::Char*,
                                 length : LibC::Int, stmt : Statement*,
@@ -45,7 +48,9 @@ class Database
     id INTEGER PRIMARY KEY,
     nick TEXT NOT NULL UNIQUE,
     opennic TEXT NOT NULL UNIQUE,
-    icann TEXT NOT NULL UNIQUE)";
+    icann TEXT NOT NULL UNIQUE)"
+  INSERT_MEMBER = "INSERT INTO member (nick, opennic, icann)
+    VALUES (%Q, %Q, %Q)"
 
   class Statement
     def initialize(db, query)
@@ -92,7 +97,7 @@ class Database
     end
   end
 
-  def initialize(path : String)
+  def initialize(path : String, opennic, icann)
     Database.check SQLite.open path, out @ref
     self.exec "PRAGMA user_version" do |row|
       version = row[0].int
@@ -101,6 +106,8 @@ class Database
       if version == 0
         self.exec SCHEMA do end
         self.exec "PRAGMA user_version = #{MIGRATIONS.size}" do end
+        # Avoid out-of-bound when looking for neighbors.
+        self.exec INSERT_MEMBER, "self", opennic, icann do end
       end
     rescue ex
       self.finalize
@@ -108,8 +115,10 @@ class Database
     end
   end
 
-  def exec(query : String)
-    stmt = Statement.new @ref, query
+  def exec(query : String, *values)
+    sql = SQLite.mprintf query, *values
+    stmt = Statement.new @ref, String.new sql
+    SQLite.free sql
     loop do
       rc = stmt.step
       case rc