v/vlib/orm/README.md
Tim Marston 756075380b
orm: add null handling and option fields (#19379)
* 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`
2023-10-05 19:09:03 +03:00

173 lines
3.3 KiB
Markdown

# ORM
## Null
Use option fields in V structs for fields which can be NULL. Regular,
non-option fields are defied as NOT NULL when creating tables.
## Attributes
### Structs
- `[table: 'name']` sets a custom table name
### Fields
- `[primary]` sets the field as the primary key
- `[unique]` sets the field as unique
- `[unique: 'foo']` adds the field to a unique group
- `[skip]` or `[sql: '-']` field will be skipped
- `[sql: type]` where `type` is a V type such as `int` or `f64`
- `[sql: serial]` lets the DB backend choose a column type for a auto-increment field
- `[sql: 'name']` sets a custom column name for the field
- `[sql_type: 'SQL TYPE']` sets the sql type which is used in sql
- `[default: 'raw_sql]` inserts `raw_sql` verbatim in a "DEFAULT" clause when
create a new table, allowing for values like `CURRENT_TIME`
- `[fkey: 'parent_id']` sets foreign key for an field which holds an array
## Usage
```v ignore
import time
[table: 'foos']
struct Foo {
id int [primary; sql: serial]
name string
created_at time.Time [default: 'CURRENT_TIME]
updated_at ?string [sql_type: 'TIMESTAMP]
deleted_at ?time.Time
children []Child [fkey: 'parent_id']
}
struct Child {
id int [primary; sql: serial]
parent_id int
name string
}
```
### Create
```v ignore
sql db {
create table Foo
}!
```
### Drop
```v ignore
sql db {
drop table Foo
}!
```
### Insert
```v ignore
foo := Foo{
name: 'abc'
created_at: time.now()
// updated_at defaults to none
// deleted_at defaults to none
children: [
Child{
name: 'abc'
},
Child{
name: 'def'
},
]
}
sql db {
insert foo into Foo
}!
```
When inserting, `[sql: serial]` fields, and fields with a `[default: 'raw_sql']`
attribute are not sent to the database when the value being sent is the default
for the V struct field (e.g., 0 int, or an empty string). This allows the
database to insert default values for auto-increment fields and where you have
specified a default.
### Update
```v ignore
sql db {
update Foo set updated_at = time.now() where name == 'abc' && updated_at is none
}!
```
Note that `is none` and `!is none` can be used to select for NULL fields.
### Delete
```v ignore
sql db {
delete from Foo where id > 10
}!
```
### Select
```v ignore
result := sql db {
select from Foo where id == 1
}!
```
```v ignore
result := sql db {
select from Foo where id > 1 && name != 'lasanha' limit 5
}!
```
```v ignore
result := sql db {
select from Foo where id > 1 order by id
}!
```
### Example
```v ignore
import db.pg
struct Member {
id string [default: 'gen_random_uuid()'; primary; sql_type: 'uuid']
name string
created_at string [default: 'CURRENT_TIMESTAMP'; sql_type: 'TIMESTAMP']
}
fn main() {
db := pg.connect(pg.Config{
host: 'localhost'
port: 5432
user: 'user'
password: 'password'
dbname: 'dbname'
})!
defer {
db.close()
}
sql db {
create table Member
}!
new_member := Member{
name: 'John Doe'
}
sql db {
insert new_member into Member
}!
selected_members := sql db {
select from Member where name == 'John Doe' limit 1
}!
john_doe := selected_members.first()
sql db {
update Member set name = 'Hitalo' where id == john_doe.id
}!
}
```