mirror of
https://github.com/vlang/v.git
synced 2025-08-04 10:17:22 -04:00

* orm: added is none and !is none handling * orm: added NullType, support option fields and deprecate [nonull] Nullable DB fields are now determined by corresponding option struct field. The [nonull] attribute is deprecated and fields are all NOT NULL now, unless they are option fields. New orm primitive, NullType, added to support passing none values to db backends, which have been updated to support it. Also, empty string and 0 numberic values are no longer skipped during insert (since they may be valid values). * orm: fix [nonull] deprecation warning * orm: add null handling to update and select also, improved formatting for orm cgen, and removed optimised operand handling of orm `is` and `!is` operators * sqlite: read/report NULLs using new orm NullType * postgres: returning data primitives now returns new orm.NullType * orm: initialise NullType Primitives properly * orm: do not smart cast operands inside sql * orm: fix bad setting of option value * orm: improve orm_null_test.v, adding/fixing selects * orm: cleanup: rename NullType->Null, use serial const, cgen output * orm: handle automatically generated fields more explicitly During insert, fields which are * [sql: serial] * [default: whatever] and where the data is a default value (e.g., 0, ""), those fields are not sent to the db, so that the db can generate auto-increment or default values. (This was previously done only for [primary] fields, and not in all circumstances, but that is not correct -- primary and serial/auto-increment fields are differnet.) * orm: udpated README * orm: select cgen fixes: read from uninit res; fail to init res * orm: udpated tests * orm: fix option sub-struct fields * orm: fixed joins to option structs Changed orm.write_orm_select() so that you pass to it the name of a resut variable which it populates with the result (or not) and changed use of it in sql_select_expr() and calls in write_orm_select() to populate substructs. * orm: fix pg driver handling of NULL results * orm: move runtime checks to comptime checker; cache checked tables * orm: vfmt :( * orm: markdown formatting * orm: renamed orm.time_ and orm.enum_; updated db drivers * checker: updated orm tests * orm: fix issue setting up ast option values as orm primitives * checker: ORM use of none/options and operations (added tests) * orm: fixed tests * db: clean code * examples: remove orm nonull attributes * orm: skip test memory santisation for orm_null_test.v * orm: make the type-to-primitive converstion fns not public * orm: mv object var c-code from checker->cgen; fix memory corruption Code in checker/orm.v used the SqlStmtLine object field name to store c-specific referenecs to option and array fields (for arrays of children). I moved this logic to cgen. And fixed an issue introduced with option fields, where an array of children was unpacked into a non-array result which could corrupt memory. * orm: fixed vast error * orm: skip 2 tests on ubuntu-musl which require sqlite3.h * cgen: prevent casting a struct (string) * v fmt orm_fkey_attribute.vv, orm_multidim_array.vv, orm_table_attributes.vv; run `VAUTOFIX=1 ./v vlib/v/compiler_errors_test.v`
194 lines
5.1 KiB
V
194 lines
5.1 KiB
V
module sqlite
|
|
|
|
import orm
|
|
import time
|
|
|
|
// @select is used internally by V's ORM for processing `SELECT ` queries
|
|
pub fn (db DB) @select(config orm.SelectConfig, data orm.QueryData, where orm.QueryData) ![][]orm.Primitive {
|
|
// 1. Create query and bind necessary data
|
|
query := orm.orm_select_gen(config, '`', true, '?', 1, where)
|
|
$if trace_sqlite ? {
|
|
eprintln('> @select query: "${query}"')
|
|
}
|
|
stmt := db.new_init_stmt(query)!
|
|
defer {
|
|
stmt.finalize()
|
|
}
|
|
mut c := 1
|
|
sqlite_stmt_binder(stmt, where, query, mut c)!
|
|
sqlite_stmt_binder(stmt, data, query, mut c)!
|
|
|
|
mut ret := [][]orm.Primitive{}
|
|
|
|
if config.is_count {
|
|
// 2. Get count of returned values & add it to ret array
|
|
step := stmt.step()
|
|
if step !in [sqlite_row, sqlite_ok, sqlite_done] {
|
|
return db.error_message(step, query)
|
|
}
|
|
count := stmt.sqlite_select_column(0, 8)!
|
|
ret << [count]
|
|
return ret
|
|
}
|
|
for {
|
|
// 2. Parse returned values
|
|
step := stmt.step()
|
|
if step == sqlite_done {
|
|
break
|
|
}
|
|
if step != sqlite_ok && step != sqlite_row {
|
|
break
|
|
}
|
|
mut row := []orm.Primitive{}
|
|
for i, typ in config.types {
|
|
primitive := stmt.sqlite_select_column(i, typ)!
|
|
row << primitive
|
|
}
|
|
ret << row
|
|
}
|
|
return ret
|
|
}
|
|
|
|
// sql stmt
|
|
|
|
// insert is used internally by V's ORM for processing `INSERT ` queries
|
|
pub fn (db DB) insert(table string, data orm.QueryData) ! {
|
|
query, converted_data := orm.orm_stmt_gen(.sqlite, table, '`', .insert, true, '?',
|
|
1, data, orm.QueryData{})
|
|
sqlite_stmt_worker(db, query, converted_data, orm.QueryData{})!
|
|
}
|
|
|
|
// update is used internally by V's ORM for processing `UPDATE ` queries
|
|
pub fn (db DB) update(table string, data orm.QueryData, where orm.QueryData) ! {
|
|
query, _ := orm.orm_stmt_gen(.sqlite, table, '`', .update, true, '?', 1, data, where)
|
|
sqlite_stmt_worker(db, query, data, where)!
|
|
}
|
|
|
|
// delete is used internally by V's ORM for processing `DELETE ` queries
|
|
pub fn (db DB) delete(table string, where orm.QueryData) ! {
|
|
query, _ := orm.orm_stmt_gen(.sqlite, table, '`', .delete, true, '?', 1, orm.QueryData{},
|
|
where)
|
|
sqlite_stmt_worker(db, query, orm.QueryData{}, where)!
|
|
}
|
|
|
|
// last_id is used internally by V's ORM for post-processing `INSERT ` queries
|
|
pub fn (db DB) last_id() int {
|
|
query := 'SELECT last_insert_rowid();'
|
|
|
|
return db.q_int(query) or { 0 }
|
|
}
|
|
|
|
// DDL (table creation/destroying etc)
|
|
|
|
// create is used internally by V's ORM for processing table creation queries (DDL)
|
|
pub fn (db DB) create(table string, fields []orm.TableField) ! {
|
|
query := orm.orm_table_gen(table, '`', true, 0, fields, sqlite_type_from_v, false) or {
|
|
return err
|
|
}
|
|
sqlite_stmt_worker(db, query, orm.QueryData{}, orm.QueryData{})!
|
|
}
|
|
|
|
// drop is used internally by V's ORM for processing table destroying queries (DDL)
|
|
pub fn (db DB) drop(table string) ! {
|
|
query := 'DROP TABLE `${table}`;'
|
|
sqlite_stmt_worker(db, query, orm.QueryData{}, orm.QueryData{})!
|
|
}
|
|
|
|
// helper
|
|
|
|
// Executes query and bind prepared statement data directly
|
|
fn sqlite_stmt_worker(db DB, query string, data orm.QueryData, where orm.QueryData) ! {
|
|
$if trace_sqlite ? {
|
|
eprintln('> sqlite_stmt_worker query: "${query}"')
|
|
}
|
|
stmt := db.new_init_stmt(query)!
|
|
defer {
|
|
stmt.finalize()
|
|
}
|
|
mut c := 1
|
|
sqlite_stmt_binder(stmt, data, query, mut c)!
|
|
sqlite_stmt_binder(stmt, where, query, mut c)!
|
|
stmt.orm_step(query)!
|
|
}
|
|
|
|
// Binds all values of d in the prepared statement
|
|
fn sqlite_stmt_binder(stmt Stmt, d orm.QueryData, query string, mut c &int) ! {
|
|
for data in d.data {
|
|
err := bind(stmt, c, data)
|
|
|
|
if err != 0 {
|
|
return stmt.db.error_message(err, query)
|
|
}
|
|
c++
|
|
}
|
|
}
|
|
|
|
// Universal bind function
|
|
fn bind(stmt Stmt, c &int, data orm.Primitive) int {
|
|
mut err := 0
|
|
match data {
|
|
i8, i16, int, u8, u16, u32, bool {
|
|
err = stmt.bind_int(c, int(data))
|
|
}
|
|
i64, u64 {
|
|
err = stmt.bind_i64(c, i64(data))
|
|
}
|
|
f32, f64 {
|
|
err = stmt.bind_f64(c, unsafe { *(&f64(&data)) })
|
|
}
|
|
string {
|
|
err = stmt.bind_text(c, data)
|
|
}
|
|
time.Time {
|
|
err = stmt.bind_int(c, int(data.unix))
|
|
}
|
|
orm.InfixType {
|
|
err = bind(stmt, c, data.right)
|
|
}
|
|
orm.Null {
|
|
err = stmt.bind_null(c)
|
|
}
|
|
}
|
|
return err
|
|
}
|
|
|
|
// Selects column in result and converts it to an orm.Primitive
|
|
fn (stmt Stmt) sqlite_select_column(idx int, typ int) !orm.Primitive {
|
|
if typ in orm.nums || typ == -1 {
|
|
return stmt.get_int(idx) or { return orm.Null{} }
|
|
} else if typ in orm.num64 {
|
|
return stmt.get_i64(idx) or { return orm.Null{} }
|
|
} else if typ in orm.float {
|
|
return stmt.get_f64(idx) or { return orm.Null{} }
|
|
} else if typ == orm.type_string {
|
|
if v := stmt.get_text(idx) {
|
|
return v.clone()
|
|
} else {
|
|
return orm.Null{}
|
|
}
|
|
} else if typ == orm.enum_ {
|
|
return stmt.get_i64(idx) or { return orm.Null{} }
|
|
} else if typ == orm.time_ {
|
|
if v := stmt.get_int(idx) {
|
|
return time.unix(v)
|
|
} else {
|
|
return orm.Null{}
|
|
}
|
|
} else {
|
|
return error('Unknown type ${typ}')
|
|
}
|
|
}
|
|
|
|
// Convert type int to sql type string
|
|
fn sqlite_type_from_v(typ int) !string {
|
|
return if typ in orm.nums || typ in orm.num64 || typ in [orm.serial, orm.time_, orm.enum_] {
|
|
'INTEGER'
|
|
} else if typ in orm.float {
|
|
'REAL'
|
|
} else if typ == orm.type_string {
|
|
'TEXT'
|
|
} else {
|
|
error('Unknown type ${typ}')
|
|
}
|
|
}
|