db: increase db module level in vlib

pull/4121/head
yuyi 2020-03-26 16:21:34 +08:00 committed by GitHub
parent fb4f7b6827
commit cd6d175180
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 34 additions and 37 deletions

View File

@ -1,4 +1,4 @@
// import mysql // import db.mysql
// pub fn main() { // pub fn main() {
// conn := mysql.connect('localhost', 'root', '', 'mysql') // conn := mysql.connect('localhost', 'root', '', 'mysql')
@ -11,5 +11,5 @@
// } // }
fn main() { fn main() {
} }

View File

@ -1,6 +1,6 @@
module main module main
import pg import db.pg
struct Customer { struct Customer {
id int id int
@ -58,5 +58,3 @@ fn main() {
} }
db.insert(nc) db.insert(nc)
} }

View File

@ -1,22 +1,22 @@
import sqlite import db.sqlite
fn main() { fn main() {
db := sqlite.connect(':memory:') db := sqlite.connect(':memory:')
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')")
db.exec("insert into users (name) values ('Peter')") db.exec("insert into users (name) values ('Peter')")
db.exec("insert into users (name) values ('Kate')") db.exec("insert into users (name) values ('Kate')")
nr_users := db.q_int('select count(*) from users') nr_users := db.q_int('select count(*) from users')
println('nr users = $nr_users') println('nr users = $nr_users')
name := db.q_string('select name from users where id = 1') name := db.q_string('select name from users where id = 1')
assert name == 'Sam' assert name == 'Sam'
users, code := db.exec('select * from users') users, code := db.exec('select * from users')
println("SQL Result code: $code") println("SQL Result code: $code")
for row in users { for row in users {
println(row.vals) println(row.vals)
} }
} }

View File

@ -2036,7 +2036,7 @@ fn (p mut Parser) var_expr(v Var) string {
p.next() p.next()
return p.select_query(fn_ph) return p.select_query(fn_ph)
} }
if typ == 'pg__DB' && !p.fileis('pg.v') && p.peek() == .name { if typ == 'db_dot_pg__DB' && !p.fileis('pg.v') && p.peek() == .name {
name := p.tokens[p.token_idx].lit name := p.tokens[p.token_idx].lit
if !name.contains('exec') && !name.starts_with('q_') { if !name.contains('exec') && !name.starts_with('q_') {
p.next() p.next()

View File

@ -134,7 +134,7 @@ fn (p mut Parser) select_query(fn_ph int) string {
println('sql query="$q"') println('sql query="$q"')
p.cgen.insert_before('// DEBUG_SQL prefix: $qprefix | fn_ph: $fn_ph | query: "$q" ') p.cgen.insert_before('// DEBUG_SQL prefix: $qprefix | fn_ph: $fn_ph | query: "$q" ')
if n == 'count' { if n == 'count' {
p.cgen.set_placeholder(fn_ph, 'pg__DB_q_int(') p.cgen.set_placeholder(fn_ph, 'db_dot_pg__DB_q_int(')
p.gen(', tos2("$q"))') p.gen(', tos2("$q"))')
} }
else { else {
@ -161,13 +161,13 @@ $params_gen
Option_${table_name} opt_${qprefix}$tmp; Option_${table_name} opt_${qprefix}$tmp;
void* ${qprefix}res = PQexecParams(db.conn, "$q", $p.sql_i, 0, ${qprefix}params, 0, 0, 0) ; void* ${qprefix}res = PQexecParams(db.conn, "$q", $p.sql_i, 0, ${qprefix}params, 0, 0, 0) ;
array_pg__Row ${qprefix}rows = pg__res_to_rows ( ${qprefix}res ) ; array_db_dot_pg__Row ${qprefix}rows = db_dot_pg__res_to_rows ( ${qprefix}res ) ;
Option_pg__Row opt_${qprefix}row = pg__rows_first_or_empty( ${qprefix}rows ); Option_db_dot_pg__Row opt_${qprefix}row = db_dot_pg__rows_first_or_empty( ${qprefix}rows );
if (! opt_${qprefix}row . ok ) { if (! opt_${qprefix}row . ok ) {
opt_${qprefix}$tmp = v_error( opt_${qprefix}row . error ); opt_${qprefix}$tmp = v_error( opt_${qprefix}row . error );
}else{ }else{
$table_name ${qprefix}$tmp; $table_name ${qprefix}$tmp;
pg__Row ${qprefix}row = *(pg__Row*) opt_${qprefix}row . data; db_dot_pg__Row ${qprefix}row = *(db_dot_pg__Row*) opt_${qprefix}row . data;
${obj_gen.str()} ${obj_gen.str()}
opt_${qprefix}$tmp = opt_ok( & ${qprefix}$tmp, sizeof($table_name) ); opt_${qprefix}$tmp = opt_ok( & ${qprefix}$tmp, sizeof($table_name) );
} }
@ -183,12 +183,12 @@ ${obj_gen.str()}
$params_gen $params_gen
void* ${qprefix}res = PQexecParams(db.conn, "$q", $p.sql_i, 0, ${qprefix}params, 0, 0, 0) ; void* ${qprefix}res = PQexecParams(db.conn, "$q", $p.sql_i, 0, ${qprefix}params, 0, 0, 0) ;
array_pg__Row ${qprefix}rows = pg__res_to_rows(${qprefix}res); array_db_dot_pg__Row ${qprefix}rows = db_dot_pg__res_to_rows(${qprefix}res);
// TODO preallocate // TODO preallocate
array ${qprefix}arr_$tmp = new_array(0, 0, sizeof($table_name)); array ${qprefix}arr_$tmp = new_array(0, 0, sizeof($table_name));
for (int i = 0; i < ${qprefix}rows.len; i++) { for (int i = 0; i < ${qprefix}rows.len; i++) {
pg__Row ${qprefix}row = *(pg__Row*)array_get(${qprefix}rows, i); db_dot_pg__Row ${qprefix}row = *(db_dot_pg__Row*)array_get(${qprefix}rows, i);
$table_name ${qprefix}$tmp; $table_name ${qprefix}$tmp;
${obj_gen.str()} ${obj_gen.str()}
_PUSH(&${qprefix}arr_$tmp, ${qprefix}$tmp, ${tmp}2, $table_name); _PUSH(&${qprefix}arr_$tmp, ${qprefix}$tmp, ${tmp}2, $table_name);
@ -337,4 +337,3 @@ fn (p mut Parser) update_query(fn_ph int) {
println('update q="$q"') println('update q="$q"')
p.genln('.conn, "$q", $nr_vals, 0, params, 0, 0, 0)') p.genln('.conn, "$q", $nr_vals, 0, params, 0, 0, 0)')
} }

View File

@ -35,7 +35,7 @@ fn C.PQnfields(voidptr) int
fn C.PQexec(voidptr) voidptr fn C.PQexec(voidptr) voidptr
fn C.PQexecParams(voidptr) voidptr fn C.PQexecParams(voidptr) voidptr
pub fn connect(config pg.Config) ?DB { pub fn connect(config Config) ?DB {
conninfo := 'host=$config.host port=$config.port user=$config.user dbname=$config.dbname password=$config.password' conninfo := 'host=$config.host port=$config.port user=$config.user dbname=$config.dbname password=$config.password'
conn := C.PQconnectdb(conninfo.str) conn := C.PQconnectdb(conninfo.str)
status := C.PQstatus(conn) status := C.PQstatus(conn)
@ -47,10 +47,10 @@ pub fn connect(config pg.Config) ?DB {
return DB {conn: conn} return DB {conn: conn}
} }
fn res_to_rows(res voidptr) []pg.Row { fn res_to_rows(res voidptr) []Row {
nr_rows := C.PQntuples(res) nr_rows := C.PQntuples(res)
nr_cols := C.PQnfields(res) nr_cols := C.PQnfields(res)
mut rows := []pg.Row mut rows := []Row
for i in 0..nr_rows { for i in 0..nr_rows {
mut row := Row{} mut row := Row{}
for j in 0..nr_cols { for j in 0..nr_cols {
@ -90,11 +90,11 @@ pub fn (db DB) q_string(query string) string {
return val return val
} }
pub fn (db DB) q_strings(query string) []pg.Row { pub fn (db DB) q_strings(query string) []Row {
return db.exec(query) return db.exec(query)
} }
pub fn (db DB) exec(query string) []pg.Row { pub fn (db DB) exec(query string) []Row {
res := C.PQexec(db.conn, query.str) res := C.PQexec(db.conn, query.str)
e := string(C.PQerrorMessage(db.conn)) e := string(C.PQerrorMessage(db.conn))
if e != '' { if e != '' {
@ -105,14 +105,14 @@ pub fn (db DB) exec(query string) []pg.Row {
return res_to_rows(res) return res_to_rows(res)
} }
fn rows_first_or_empty(rows []pg.Row) ?pg.Row { fn rows_first_or_empty(rows []Row) ?Row {
if rows.len == 0 { if rows.len == 0 {
return error('no row') return error('no row')
} }
return rows[0] return rows[0]
} }
pub fn (db DB) exec_one(query string) ?pg.Row { pub fn (db DB) exec_one(query string) ?Row {
res := C.PQexec(db.conn, query.str) res := C.PQexec(db.conn, query.str)
e := string(C.PQerrorMessage(db.conn)) e := string(C.PQerrorMessage(db.conn))
if e != '' { if e != '' {
@ -124,7 +124,7 @@ pub fn (db DB) exec_one(query string) ?pg.Row {
// The entire function can be considered unsafe because of the malloc and the // The entire function can be considered unsafe because of the malloc and the
// free. This prevents warnings and doesn't seem to affect behavior. // free. This prevents warnings and doesn't seem to affect behavior.
pub fn (db DB) exec_param_many(query string, params []string) []pg.Row { pub fn (db DB) exec_param_many(query string, params []string) []Row {
unsafe { unsafe {
mut param_vals := &byteptr( malloc( params.len * sizeof(byteptr) ) ) mut param_vals := &byteptr( malloc( params.len * sizeof(byteptr) ) )
for i in 0..params.len { for i in 0..params.len {
@ -136,7 +136,7 @@ pub fn (db DB) exec_param_many(query string, params []string) []pg.Row {
} }
} }
pub fn (db DB) exec_param2(query string, param, param2 string) []pg.Row { pub fn (db DB) exec_param2(query string, param, param2 string) []Row {
mut param_vals := [2]byteptr mut param_vals := [2]byteptr
param_vals[0] = param.str param_vals[0] = param.str
param_vals[1] = param2.str param_vals[1] = param2.str
@ -144,14 +144,14 @@ pub fn (db DB) exec_param2(query string, param, param2 string) []pg.Row {
return db.handle_error_or_result(res, 'exec_param2') return db.handle_error_or_result(res, 'exec_param2')
} }
pub fn (db DB) exec_param(query string, param string) []pg.Row { pub fn (db DB) exec_param(query string, param string) []Row {
mut param_vals := [1]byteptr mut param_vals := [1]byteptr
param_vals[0] = param.str param_vals[0] = param.str
res := C.PQexecParams(db.conn, query.str, 1, 0, param_vals, 0, 0, 0) res := C.PQexecParams(db.conn, query.str, 1, 0, param_vals, 0, 0, 0)
return db.handle_error_or_result(res, 'exec_param') return db.handle_error_or_result(res, 'exec_param')
} }
fn (db DB) handle_error_or_result(res voidptr, elabel string) []pg.Row { fn (db DB) handle_error_or_result(res voidptr, elabel string) []Row {
e := string(C.PQerrorMessage(db.conn)) e := string(C.PQerrorMessage(db.conn))
if e != '' { if e != '' {
println('pg $elabel error:') println('pg $elabel error:')

View File

@ -1,20 +1,20 @@
import sqlite import db.sqlite
fn test_sqlite() { fn test_sqlite() {
db := sqlite.connect(':memory:') db := sqlite.connect(':memory:')
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')")
db.exec("insert into users (name) values ('Peter')") db.exec("insert into users (name) values ('Peter')")
db.exec("insert into users (name) values ('Kate')") db.exec("insert into users (name) values ('Kate')")
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')
assert name == 'Sam' assert name == 'Sam'
users, mut code := db.exec('select * from users') users, mut code := db.exec('select * from users')
assert users.len == 3 assert users.len == 3
assert code == 101 assert code == 101