dom96 / jester

A sinatra-like web framework for Nim.
MIT License
1.56k stars 120 forks source link

how to make exit procs work with --threads:on? #283

Closed sdmcallister closed 2 years ago

sdmcallister commented 2 years ago

I want to make sure that I close the database when the program terminates (using Ctrl-c or if there was a failure).

The code below mostly works :). With only atExitProc it normally doesn't close the db. With setControlCHook it normally does. Sometimes both fire! Wondering what the proper approach is.

import jester
import duckdb_wrapper
import std/exitprocs

var dbconfig: duckdb_config
if (duckdb_create_config(dbconfig.addr) == DuckDBError):
    echo "Error: Couldn't create config"
    quit(1)

if (duckdb_set_config(dbconfig, "access_mode", "READ_ONLY") == DuckDBError):
    echo "Error: Couldn't set config read only"
    quit(1)

var db: duckdb_database

if (duckdb_open_ext("test.db", db.addr, dbconfig, nil) == DuckDBError):
    echo "Error: Couldn't Open with config"
    quit(1)
duckdb_destroy_config(dbconfig.addr)

proc atExit() {.noconv.} =
    duckdb_close(addr(db))
    echo "bye"
    quit(0)
exitprocs.addExitProc(atExit) # doesn't always work with threads
setControlCHook(atExit) # seems required

routes:
    get "/":
        var con: duckdb_connection
        if (duckdb_connect(db, con.addr) == DuckDBError):
            resp "Error: couldn't connect"

        var res: duckdb_result
        if duckdb_query(con, "SELECT * FROM integers", addr(res)) == DuckDBError:
            duckdb_disconnect(addr(con))
            resp "Error: Query failed"

        var qvals: seq[string]
        for row in 0..<res.row_count:
            for col in 0..<res.column_count:
                let val = duckdb_value_varchar(addr(res), col, row)
                qvals.add($val)
                duckdb_free(val)
        duckdb_destroy_result(addr(res))
        duckdb_disconnect(addr(con))
        resp $qvals # returns to the browser a slice/array from the table
dom96 commented 2 years ago

pretty sure this isn't a jester-specific question, moving to Nim.

dom96 commented 2 years ago

Apparently I can't move it there. Please reopen in that repo or better yet ask in forum.