2019-08-20 17:32:39 +03:00
|
|
|
module main
|
|
|
|
|
2020-03-26 11:23:54 +03:00
|
|
|
import pg
|
2019-08-20 17:32:39 +03:00
|
|
|
|
2021-02-09 12:31:25 +03:00
|
|
|
const dash = '----------------------------------------------------------------'
|
|
|
|
|
2019-08-20 17:32:39 +03:00
|
|
|
struct Customer {
|
2021-06-07 18:25:20 +03:00
|
|
|
id int
|
|
|
|
name string
|
2019-08-20 17:32:39 +03:00
|
|
|
nr_orders int
|
2021-06-07 18:25:20 +03:00
|
|
|
country string
|
2019-08-20 17:32:39 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
2021-06-07 18:25:20 +03:00
|
|
|
/*
|
|
|
|
db := pg.connect(pg.Config{
|
2019-12-05 22:31:56 +03:00
|
|
|
host: 'localhost' //'127.0.0.1'
|
|
|
|
user: 'postgres'
|
|
|
|
dbname: 'customerdb'
|
|
|
|
}) or {
|
|
|
|
println('failed to connect')
|
|
|
|
println(err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-08-20 17:32:39 +03:00
|
|
|
nr_customers := db.select count from Customer
|
|
|
|
println('Total customers: $nr_customers')
|
2019-12-05 22:31:56 +03:00
|
|
|
|
2019-08-20 17:32:39 +03:00
|
|
|
// V syntax can be used to build queries
|
2021-02-09 12:31:25 +03:00
|
|
|
println(dash)
|
2019-12-10 00:06:24 +03:00
|
|
|
bg_country := 'Bulgaria'
|
|
|
|
bg_customers := db.select from Customer where country == bg_country && id != 2
|
2019-08-20 17:32:39 +03:00
|
|
|
for customer in bg_customers {
|
|
|
|
println('$customer.country | $customer.id - $customer.name')
|
|
|
|
}
|
2019-12-05 22:31:56 +03:00
|
|
|
|
2021-02-09 12:31:25 +03:00
|
|
|
println(dash)
|
2019-08-22 22:33:57 +03:00
|
|
|
ru_customers := db.select from Customer where country == 'Russia'
|
2019-08-20 17:32:39 +03:00
|
|
|
for customer in ru_customers {
|
|
|
|
println('$customer.country | $customer.id - $customer.name')
|
|
|
|
}
|
2019-12-05 22:31:56 +03:00
|
|
|
|
2019-08-20 17:32:39 +03:00
|
|
|
// by adding `limit 1` we tell V that there will be only one object
|
2021-02-09 12:31:25 +03:00
|
|
|
println(dash)
|
2021-03-01 02:18:14 +03:00
|
|
|
existing := db.select from Customer where id == 1 limit 1 or { panic(err) }
|
2019-08-20 17:32:39 +03:00
|
|
|
println('Existing customer name: $existing.name')
|
|
|
|
println('Existing customer full information:')
|
|
|
|
println(existing)
|
2019-12-05 22:31:56 +03:00
|
|
|
|
2021-02-09 12:31:25 +03:00
|
|
|
println(dash)
|
2019-12-05 22:31:56 +03:00
|
|
|
q := Customer{}
|
|
|
|
// It's easy to handle queries that don't return any data
|
|
|
|
if anon := db.select from Customer where id == 12345 && name == q.name &&
|
|
|
|
nr_orders > q.nr_orders limit 1 {
|
2019-08-20 17:32:39 +03:00
|
|
|
println('Non existing customer name: $anon.name')
|
|
|
|
}
|
2019-12-05 22:31:56 +03:00
|
|
|
// Insert a new customer
|
2019-08-20 17:32:39 +03:00
|
|
|
nc := Customer{
|
|
|
|
name: 'John Doe'
|
|
|
|
nr_orders: 10
|
|
|
|
}
|
2021-04-25 18:57:55 +03:00
|
|
|
db.insert(nc)*/
|
2019-08-20 17:32:39 +03:00
|
|
|
}
|