v2 / examples / database / psql / customer.v
71 lines · 62 sloc · 1.56 KB · a80bc2331450fc28c900097f8afafe173f161d27
Raw
1// vtest build: linux
2module main
3
4import db.pg
5
6struct Customer {
7 id int
8 name string
9 nr_orders int
10 country string
11}
12
13const dash = '----------------------------------------------------------------'
14
15fn main() {
16 db := pg.connect(
17 host: 'localhost' // or '127.0.0.1'
18 user: 'postgres'
19 dbname: 'customerdb'
20 ) or {
21 eprintln('failed to connect, error: ${err}')
22 return
23 }
24
25 nr_customers := sql db {
26 select count from Customer
27 }!
28 println('Total customers: ${nr_customers}')
29
30 println(dash)
31 bg_country := 'Bulgaria'
32 // V syntax can be used to build queries
33 bg_customers := sql db {
34 select from Customer where country == bg_country && id != 2
35 }!
36 for customer in bg_customers {
37 println('${customer.country} | ${customer.id} - ${customer.name}')
38 }
39
40 println(dash)
41 ru_customers := sql db {
42 select from Customer where country == 'Russia'
43 }!
44 for customer in ru_customers {
45 println('${customer.country} | ${customer.id} - ${customer.name}')
46 }
47
48 // by adding `limit 1` we tell V that there will be only one object
49 println(dash)
50 existing := sql db {
51 select from Customer where id == 1 limit 1
52 }!
53 println('Existing customer name: ${existing}[0].name')
54 println('Existing customer full information:')
55 println(existing)
56
57 println(dash)
58 q := Customer{}
59 // It's easy to handle queries that don't return any data
60 _ := sql db {
61 select from Customer where id == 12345 && name == q.name && nr_orders > q.nr_orders limit 1
62 }!
63 // Insert a new customer
64 nc := Customer{
65 name: 'John Doe'
66 nr_orders: 10
67 }
68 sql db {
69 insert nc into Customer
70 }!
71}
72