ORM

(This is still in an alpha state)

V has a built-in ORM (object-relational mapping) which supports SQLite, MySQL and Postgres, but soon it will support 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. // sets a custom table name. Default is struct name (case-sensitive)
  3. [table: 'customers']
  4. struct Customer {
  5. id int [primary; sql: serial] // a field named `id` of integer type must be the first field
  6. name string [nonull]
  7. nr_orders int
  8. country string [nonull]
  9. }
  10. db := sqlite.connect('customers.db')?
  11. // you can create tables:
  12. // CREATE TABLE IF NOT EXISTS `Customer` (
  13. // `id` INTEGER PRIMARY KEY,
  14. // `name` TEXT NOT NULL,
  15. // `nr_orders` INTEGER,
  16. // `country` TEXT NOT NULL
  17. // )
  18. sql db {
  19. create table Customer
  20. }
  21. // select count(*) from customers
  22. nr_customers := sql db {
  23. select count from Customer
  24. }
  25. println('number of all customers: $nr_customers')
  26. // V syntax can be used to build queries
  27. uk_customers := sql db {
  28. select from Customer where country == 'uk' && nr_orders > 0
  29. }
  30. println(uk_customers.len)
  31. for customer in uk_customers {
  32. println('$customer.id - $customer.name')
  33. }
  34. // by adding `limit 1` we tell V that there will be only one object
  35. customer := sql db {
  36. select from Customer where id == 1 limit 1
  37. }
  38. println('$customer.id - $customer.name')
  39. // insert a new customer
  40. new_customer := Customer{
  41. name: 'Bob'
  42. nr_orders: 10
  43. }
  44. sql db {
  45. insert new_customer into Customer
  46. }

For more examples and the docs, see vlib/orm.