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. }
  8. db := sqlite.connect('customers.db')?
  9. // select count(*) from Customer
  10. nr_customers := sql db { select count from Customer }
  11. println('number of all customers: $nr_customers')
  12. // V syntax can be used to build queries
  13. // db.select returns an array
  14. uk_customers := sql db { select from Customer where country == 'uk' && nr_orders > 0 }
  15. println(uk_customers.len)
  16. for customer in uk_customers {
  17. println('$customer.id - $customer.name')
  18. }
  19. // by adding `limit 1` we tell V that there will be only one object
  20. customer := sql db { select from Customer where id == 1 limit 1 }
  21. println('$customer.id - $customer.name')
  22. // insert a new customer
  23. new_customer := Customer{name: 'Bob', nr_orders: 10}
  24. sql db { insert new_customer into Customer }

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