1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate lazy_static;
mod serve;
use postgres::{Client, NoTls};
use std::sync::{Arc, Mutex};
lazy_static! {
static ref CLIENT: Arc<Mutex<Client>> = Arc::new(Mutex::new(
Client::connect("host=localhost user=postgres password=example", NoTls).unwrap()
));
}
fn main() {
//initialize_db().unwrap();
//setup_db().unwrap();
println!("connected with db");
rocket::ignite()
.mount("/", routes![serve::token, serve::get_tracks])
.launch();
}
fn setup_db() -> Result<(), postgres::Error> {
let name = "Ferris";
let data = None::<&[u8]>;
let mut client = CLIENT.lock().unwrap();
client.execute(
"INSERT INTO person (name, data) VALUES ($1, $2)",
&[&name, &data],
)?;
for row in client.query("SELECT id, name, data FROM person", &[])? {
let id: i32 = row.get(0);
let name: &str = row.get(1);
let data: Option<&[u8]> = row.get(2);
println!("found person: {} {} {:?}", id, name, data);
}
Ok(())
}
fn initialize_db() -> Result<(), postgres::Error> {
let mut client = CLIENT.lock().unwrap();
client.batch_execute(
"
DROP TABLE user_track; DROP TABLE suser; DROP TABLE track;
CREATE TABLE track (
track_id SERIAL PRIMARY KEY,
track_code TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
artist TEXT NOT NULL,
popularity int DEFAULT 50
);
CREATE TABLE suser (
user_id SERIAL PRIMARY KEY,
user_name TEXT NOT NULL UNIQUE
);
CREATE TABLE user_track (
track_id int REFERENCES track (track_id) ON UPDATE CASCADE ON DELETE CASCADE,
user_id int REFERENCES suser (user_id) ON UPDATE CASCADE ON DELETE CASCADE,
count int NOT NULL DEFAULT 1,
CONSTRAINT track_user_pkey PRIMARY KEY (track_id, user_id)
);
",
)?;
Ok(())
}
|