ORM

(This is still in an alpha state)

V has a built-in ORM (object-relational mapping) which supports SQLite, and will soon support MySQL, Postgres, MS SQL, and Oracle.

V’s ORM provides a number of benefits:

  • One syntax for all SQL dialects. (Migrating between databases becomes much easier.)
  • Queries are constructed using V’s syntax. (There’s no need to learn another syntax.)
  • Safety. (All queries are automatically sanitised to prevent SQL injection.)
  • Compile time checks. (This prevents typos which can only be caught during runtime.)
  • Readability and simplicity. (You don’t need to manually parse the results of a query and then manually construct objects from the parsed results.)
1. import sqlite
2. struct Customer { // struct name has to be the same as the table name (for now)
3. id int // a field named `id` of integer type must be the first field
4. name string
5. nr_orders int
6. country string
7. }

9. db := sqlite.connect('customers.db')?

11. // select count(*) from Customer
12. nr_customers := sql db { select count from Customer }
13. println('number of all customers: $nr_customers')

15. // V syntax can be used to build queries
16. // db.select returns an array
17. uk_customers := sql db { select from Customer where country == 'uk' && nr_orders > 0 }
18. println(uk_customers.len)
19. for customer in uk_customers {
20. println('$customer.id - $customer.name')
21. }

23. // by adding `limit 1` we tell V that there will be only one object
24. customer := sql db { select from Customer where id == 1 limit 1 }
25. println('$customer.id - $customer.name')

27. // insert a new customer
28. new_customer := Customer{name: 'Bob', nr_orders: 10}
29. sql db { insert new_customer into Customer }

For more examples, see vlib/orm/orm_test.v.