/* * Start the processing thread */ static ERL_NIF_TERM esqlite_start(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { esqlite_connection *conn; ERL_NIF_TERM db_conn; /* Initialize the resource */ conn = enif_alloc_resource(esqlite_connection_type, sizeof(esqlite_connection)); if(!conn) return make_error_tuple(env, "no_memory"); conn->db = NULL; /* Create command queue */ conn->commands = queue_create(); if(!conn->commands) { enif_release_resource(conn); return make_error_tuple(env, "command_queue_create_failed"); } /* Start command processing thread */ conn->opts = enif_thread_opts_create("esqldb_thread_opts"); if(enif_thread_create("esqlite_connection", &conn->tid, esqlite_connection_run, conn, conn->opts) != 0) { enif_release_resource(conn); return make_error_tuple(env, "thread_create_failed"); } db_conn = enif_make_resource(env, conn); enif_release_resource(conn); return make_ok_tuple(env, db_conn); }
static ERL_NIF_TERM do_prepare(ErlNifEnv *env, esqlite_connection *conn, const ERL_NIF_TERM arg) { ErlNifBinary bin; esqlite_statement *stmt; ERL_NIF_TERM esqlite_stmt; const char *tail; int rc; enif_inspect_iolist_as_binary(env, arg, &bin); stmt = enif_alloc_resource(esqlite_statement_type, sizeof(esqlite_statement)); if(!stmt) return make_error_tuple(env, "no_memory"); rc = sqlite3_prepare_v2(conn->db, (char *) bin.data, bin.size, &(stmt->statement), &tail); if(rc != SQLITE_OK) return make_sqlite3_error_tuple(env, rc, conn->db); enif_keep_resource(conn); stmt->connection = conn; esqlite_stmt = enif_make_resource(env, stmt); enif_release_resource(stmt); return make_ok_tuple(env, esqlite_stmt); }
/* * Nr of changes */ static ERL_NIF_TERM do_changes(ErlNifEnv *env, esqlite_connection *conn, const ERL_NIF_TERM arg) { int changes = sqlite3_changes(conn->db); ERL_NIF_TERM changes_term = enif_make_int64(env, changes); return make_ok_tuple(env, changes_term); }
/* * insert action */ static ERL_NIF_TERM do_insert(ErlNifEnv *env, esqlite_connection *conn, const ERL_NIF_TERM arg) { ErlNifBinary bin; int rc; ERL_NIF_TERM eos = enif_make_int(env, 0); enif_inspect_iolist_as_binary(env, enif_make_list2(env, arg, eos), &bin); rc = sqlite3_exec(conn->db, (char *) bin.data, NULL, NULL, NULL); if(rc != SQLITE_OK) return make_sqlite3_error_tuple(env, rc, conn->db); sqlite3_int64 last_rowid = sqlite3_last_insert_rowid(conn->db); ERL_NIF_TERM last_rowid_term = enif_make_int64(env, last_rowid); return make_ok_tuple(env, last_rowid_term); }