v/vlib/sqlite/sqlite.v

87 lines
1.6 KiB
V
Raw Normal View History

2019-10-27 21:32:15 +01:00
module sqlite
#flag -lsqlite3
#flag freebsd -I/usr/local/include
2019-12-15 04:18:14 +01:00
#flag freebsd -Wl -L/usr/local/lib -lsqlite3
2019-10-27 21:32:15 +01:00
#include "sqlite3.h"
struct C.sqlite3
struct C.sqlite3_stmt
pub struct DB {
2019-10-27 21:32:15 +01:00
mut:
conn &C.sqlite3
}
pub struct Row {
2019-10-27 21:32:15 +01:00
pub mut:
vals []string
}
pub fn connect(path string) DB {
2019-12-04 11:08:28 +01:00
db := &C.sqlite3(0)
2019-10-27 21:32:15 +01:00
C.sqlite3_open(path.str, &db)
return DB {conn: db}
}
pub fn (db DB) q_int(query string) int {
2019-12-04 11:08:28 +01:00
stmt := &C.sqlite3_stmt(0)
2019-10-27 21:32:15 +01:00
C.sqlite3_prepare_v2(db.conn, query.str, - 1, &stmt, 0)
C.sqlite3_step(stmt)
res := C.sqlite3_column_int(stmt, 0)
C.sqlite3_finalize(stmt)
return res
}
fn C.sqlite3_column_text(voidptr, int) byteptr
2019-11-24 04:27:02 +01:00
fn C.sqlite3_column_int(voidptr, int) int
fn C.sqlite3_open()
fn C.sqlite3_step() int
fn C.sqlite3_prepare_v2()
fn C.sqlite3_finalize()
fn C.sqlite3_column_count(voidptr) int
2019-10-27 21:32:15 +01:00
pub fn (db DB) q_string(query string) string {
2019-12-04 11:08:28 +01:00
stmt := &C.sqlite3_stmt(0)
2019-10-27 21:32:15 +01:00
C.sqlite3_prepare_v2(db.conn, query.str, - 1, &stmt, 0)
C.sqlite3_step(stmt)
res := tos_clone(C.sqlite3_column_text(stmt, 0))
C.sqlite3_finalize(stmt)
return res
}
pub fn (db DB) exec(query string) []Row {
2019-12-04 11:08:28 +01:00
stmt := &C.sqlite3_stmt(0)
2019-10-27 21:32:15 +01:00
C.sqlite3_prepare_v2(db.conn, query.str, - 1, &stmt, 0)
nr_cols := C.sqlite3_column_count(stmt)
//println('nr cols $nr_cols')
mut rows := []Row
for {
ret := C.sqlite3_step(stmt)
if ret != 0x64 {
break
2019-12-04 11:08:28 +01:00
}
2019-10-27 21:32:15 +01:00
mut row := Row{}
for i in 0..nr_cols {
val := tos_clone(C.sqlite3_column_text(stmt, i))
row.vals << val
2019-10-27 22:10:39 +01:00
//println(val)
2019-10-27 21:32:15 +01:00
}
rows << row
}
return rows
}
pub fn (db DB) exec_one(query string) ?Row {
rows := db.exec(query)
return rows[0]
}
/*
pub fn (db DB) exec_param(query string, param string) []Row {
}
*/