I'm new to SQL so don't know if I'm doing something wrong or this is a bug.
The following produces runtime error: "Error: unhandled exception: unable to close due to unfinalized statements or unfinished backups [DbError]"
The code is mostly adapted from 'Nim in Action'. The first run on db creation is OK and on second run it crashes.
import db_sqlite
type
Database* = ref object
db: DbConn
proc newDb*(filename = "pages.db"): Database =
new result
result.db = open(filename, "", "", "")
proc close*(database: Database) =
database.db.close()
proc setup*(database: Database) =
database.db.exec(sql"""
CREATE TABLE IF NOT EXISTS Pages(
id text PRIMARY KEY,
pagesocr text
);
""")
proc insert*(database: Database, id, pagesocr: string): bool {.discardable.} =
try:
database.db.exec(sql"INSERT INTO Pages VALUES(?, ?);", id, pagesocr)
finally:
return false
true
proc find(database: Database, id: string): string =
result = database.db.getValue(sql"SELECT pagesocr FROM Pages WHERE id = ?;", id)
var db = newDb()
db.setup()
db.insert("bub_aaa", "1,2,3,0,6")
db.insert("bub_ddd", "1,2,3,0,7")
echo db.find("bub_ddd")
db.close()
Alright, I thought SQL gracefully ignored adding a duplicate key but guess not. I've added this function:
proc exists(database: Database, id: string): bool =
result = if len(database.db.getValue(sql"SELECT id FROM Pages WHERE id = ?;", id)) > 0: true else: false
eg.
if not db.exists("bub_aaa"): db.insert("bub_aaa", "1,2,3,0,6")
A method to cancel the offending SQL command during the try->finally would be great.
Crashing run-time during db.close() seems harsh as it requires no overlooked problems in the data or SQL methods, and figuring out when the problem happened during the program run (db.close often happens at program shutdown)