Skip to content

Instantly share code, notes, and snippets.

@aturley
Last active June 26, 2020 10:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aturley/33a815ff6490be84e27f to your computer and use it in GitHub Desktop.
Save aturley/33a815ff6490be84e27f to your computer and use it in GitHub Desktop.
This is a Pony reimplementation of the C example from the SQLite quickstart page (http://sqlite.org/quickstart.html), using Pony's FFI system (http://tutorial.ponylang.org/c-ffi/calling-c/). In writing it I found a bug in Pony (which was subsequently fixed), so the exercise was good for something other than just learning. I'm still learning Pony…
use "collections"
use "lib:sqlite3"
actor Main
let _env: Env
new create(env: Env) =>
_env = env
let args = env.args
var db: Pointer[U8] = Pointer[U8]
var zErrMsg: Pointer[U8] = Pointer[U8]
var rc: I32 = 0
let prog = try
args(0)
else
_env.err.print("There's no 0th argument, I don't know how you got here.")
_env.exitcode(1)
return
end
if (args.size() != 3) then
_env.err.print(recover String().append("Usage: ").append(prog).append(" DATABASE SQL-STATEMENT") end)
_env.exitcode(1)
return
end
(let database, let sql) = try
(args(1), args(2))
else
("", "")
end
rc = @sqlite3_open[I32](database.cstring(), addressof db)
if (rc != 0) then
let errMsg = String.from_cstring(@sqlite3_errmsg[Pointer[U8]](db))
let msg = String().append("Can't open database: ").append(errMsg)
_env.err.print(msg.clone())
@sqlite3_close[None](db)
_env.exitcode(1)
return
end
rc = @sqlite3_exec[I32](db, sql.cstring(), addressof this.callback, this, addressof zErrMsg)
if (rc != 0) then
let errMsg = String.from_cstring(zErrMsg)
let msg = String().append("SQL error: ").append(errMsg)
_env.err.print(msg.clone())
@sqlite3_free[None](zErrMsg)
end
@sqlite3_close[None](db)
fun iso callback(argc: I32, argv: Pointer[Pointer[U8]], azColName: Pointer[Pointer[U8]]): I32 =>
let args = Array[Pointer[U8]].from_cstring(argv, USize.from[I32](argc))
let colNames = Array[Pointer[U8]].from_cstring(azColName, USize.from[I32](argc))
for i in Range[USize](0, USize.from[I32](argc)) do
try
let arg = String.from_cstring(args(i))
let columnName = String.from_cstring(colNames(i))
_env.out.print(" = ".join([columnName, arg]))
end
_env.out.print("")
end
I32(0)
@anacrolix
Copy link

What was the bug, can you link to the issue?

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