module test

import sqlite/sqlite3

// TODO(zephyr): For now, we're just doing a very basic test to estimate whether
// I'm doing Koka FFI correctly. An actual test suite would be excellent.

tail fun do-while(f: () -> <div|e> maybe<a>): <div|e> a
  match f()
    Nothing -> do-while(f)
    Just(r) -> r

fun stmt(db: sqlite3, sql: string, bind: maybe<string> = Nothing)
  println(sql)
  match db.prepare(sql.slice)
    Left(r-prep) -> println("  prepare result: " ++ r-prep.show)
    Right((stmt, rest)) ->
      println("  prepare remainder: " ++ rest.show)
      match bind
        Nothing -> ()
        Just(text) -> 
          val r = stmt.bind-text(1, text)
          println("  bind result: " ++ r.show)
      val r-step = do-while
        val r = stmt.step
        match r
          Row ->
            for(stmt.column-count) fn(i)
              println("    col " ++ i.show ++ ": " ++ stmt.text(i))
            Nothing
          r -> Just(r)
      println("  final step result:     " ++ r-step.show)
      val r-fin = stmt.finalize
      println("  finalize result: " ++ r-fin.show)

pub fun main()
  println("initialize result: " ++ startup-initialized.show)
  val (db, r-open) = open(Filename("koka-test.sqlite3"))
  println("open result: " ++ r-open.show)
  stmt(db, "DROP TABLE IF EXISTS koka; -- reset previous test runs")
  stmt(db, "CREATE TABLE koka(v TEXT NOT NULL)")
  stmt(db, "INSERT INTO koka VALUES (?);", Just("value inserted from koka"))
  stmt(db, "SELECT * FROM koka")
  val r-close = db.close
  println("close result: " ++ r-close.show)
