sqlite: add a last_insert_rowid fn (#10341)

pull/10347/head
Ken 2021-06-05 00:10:20 +09:00 committed by GitHub
parent 18bebcc3be
commit 5266b4921d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 0 deletions

View File

@ -47,6 +47,8 @@ fn C.sqlite3_open(&char, &&C.sqlite3) int
fn C.sqlite3_close(&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 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 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. // Returns a single cell with value int.
pub fn (db DB) q_int(query string) int { pub fn (db DB) q_int(query string) int {
stmt := &C.sqlite3_stmt(0) stmt := &C.sqlite3_stmt(0)

View File

@ -9,8 +9,11 @@ fn test_sqlite() {
db.exec('drop table if exists users') db.exec('drop table if exists users')
db.exec("create table users (id integer primary key, name text default '');") db.exec("create table users (id integer primary key, name text default '');")
db.exec("insert into users (name) values ('Sam')") db.exec("insert into users (name) values ('Sam')")
assert db.last_insert_rowid() == 1
db.exec("insert into users (name) values ('Peter')") db.exec("insert into users (name) values ('Peter')")
assert db.last_insert_rowid() == 2
db.exec("insert into users (name) values ('Kate')") db.exec("insert into users (name) values ('Kate')")
assert db.last_insert_rowid() == 3
nr_users := db.q_int('select count(*) from users') nr_users := db.q_int('select count(*) from users')
assert nr_users == 3 assert nr_users == 3
name := db.q_string('select name from users where id = 1') name := db.q_string('select name from users where id = 1')