From 5266b4921d51ca651af55ddfa45715245ae284f1 Mon Sep 17 00:00:00 2001 From: Ken Date: Sat, 5 Jun 2021 00:10:20 +0900 Subject: [PATCH] sqlite: add a last_insert_rowid fn (#10341) --- vlib/sqlite/sqlite.v | 8 ++++++++ vlib/sqlite/sqlite_test.v | 3 +++ 2 files changed, 11 insertions(+) diff --git a/vlib/sqlite/sqlite.v b/vlib/sqlite/sqlite.v index a915b988b3..0704e61f62 100644 --- a/vlib/sqlite/sqlite.v +++ b/vlib/sqlite/sqlite.v @@ -47,6 +47,8 @@ fn C.sqlite3_open(&char, &&C.sqlite3) int fn C.sqlite3_close(&C.sqlite3) int +fn C.sqlite3_last_insert_rowid(&C.sqlite3) i64 + // fn C.sqlite3_prepare_v2(&C.sqlite3, &char, int, &&C.sqlite3_stmt, &&char) int @@ -124,6 +126,12 @@ fn get_int_from_stmt(stmt &C.sqlite3_stmt) int { return res } +// Returns last insert rowid +// https://www.sqlite.org/c3ref/last_insert_rowid.html +pub fn (db DB) last_insert_rowid() i64 { + return C.sqlite3_last_insert_rowid(db.conn) +} + // Returns a single cell with value int. pub fn (db DB) q_int(query string) int { stmt := &C.sqlite3_stmt(0) diff --git a/vlib/sqlite/sqlite_test.v b/vlib/sqlite/sqlite_test.v index c0ffa80c10..f1e9db36cf 100644 --- a/vlib/sqlite/sqlite_test.v +++ b/vlib/sqlite/sqlite_test.v @@ -9,8 +9,11 @@ fn test_sqlite() { 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')") + assert db.last_insert_rowid() == 1 db.exec("insert into users (name) values ('Peter')") + assert db.last_insert_rowid() == 2 db.exec("insert into users (name) values ('Kate')") + assert db.last_insert_rowid() == 3 nr_users := db.q_int('select count(*) from users') assert nr_users == 3 name := db.q_string('select name from users where id = 1')