From c831711a0e61d575123ef28c10a4dfb43883d487 Mon Sep 17 00:00:00 2001 From: Major Taylor Date: Mon, 21 Dec 2020 15:02:29 -0500 Subject: [PATCH] sqlite: add `close` method, and an `is_open` field (#7382) --- vlib/sqlite/sqlite.v | 20 ++++++++++++++++++-- vlib/sqlite/sqlite_test.v | 7 ++++++- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/vlib/sqlite/sqlite.v b/vlib/sqlite/sqlite.v index 46bc5c1be5..3c74795b8d 100644 --- a/vlib/sqlite/sqlite.v +++ b/vlib/sqlite/sqlite.v @@ -20,8 +20,10 @@ struct C.sqlite3_stmt { // pub struct DB { +pub mut: + is_open bool mut: - conn &C.sqlite3 + conn &C.sqlite3 } pub fn (db DB) str() string { @@ -63,7 +65,7 @@ fn C.sqlite3_errstr(int) charptr fn C.sqlite3_free(voidptr) -// Opens the connection with a database. +// connect Opens the connection with a database. pub fn connect(path string) ?DB { db := &C.sqlite3(0) if C.sqlite3_open(path.str, &db) != 0 { @@ -71,9 +73,23 @@ pub fn connect(path string) ?DB { } return DB{ conn: db + is_open: true } } +// close Closes the DB. +// TODO: For all functions, determine whether the connection is +// closed first, and determine what to do if it is +pub fn (mut db DB) close() ?bool { + code := C.sqlite3_close(db.conn) + if code == 0 { + db.is_open = false + } else { + return error('sqlite db error: failed to close with code: $code') + } + return true // successfully closed +} + // Only for V ORM fn (db DB) init_stmt(query string) &C.sqlite3_stmt { stmt := &C.sqlite3_stmt(0) diff --git a/vlib/sqlite/sqlite_test.v b/vlib/sqlite/sqlite_test.v index 021510d579..ebcd3aa10a 100644 --- a/vlib/sqlite/sqlite_test.v +++ b/vlib/sqlite/sqlite_test.v @@ -4,9 +4,10 @@ fn test_sqlite() { $if !linux { return } - db := sqlite.connect(':memory:') or { + mut db := sqlite.connect(':memory:') or { panic(err) } + assert db.is_open db.exec('drop table if exists users') db.exec("create table users (id integer primary key, name text default '');") db.exec("insert into users (name) values ('Sam')") @@ -25,4 +26,8 @@ fn test_sqlite() { panic(err) } assert user.vals.len == 2 + db.close() or { + panic(err) + } + assert !db.is_open }