Skip to content

Commit bbfd444

Browse files
900: Port `bin/populate` over to use Diesel r=carols10cents This was a pretty straightforward piece to port. Once tuple inserts are available (Diesel 1.0 likely) this would probably benefit from getting rid of the struct that's only ever used once. I switched to using Chrono here, as the `time` crate doesn't have a type that maps only to a date, so it has no type that Diesel supports for insert here.
2 parents 9219e5a + 8014a54 commit bbfd444

File tree

1 file changed

+32
-21
lines changed

1 file changed

+32
-21
lines changed

src/bin/populate.rs

+32-21
Original file line numberDiff line numberDiff line change
@@ -7,44 +7,55 @@
77
#![deny(warnings)]
88

99
extern crate cargo_registry;
10-
extern crate postgres;
11-
extern crate time;
10+
extern crate chrono;
11+
#[macro_use]
12+
extern crate diesel;
13+
#[macro_use]
14+
extern crate diesel_codegen;
1215
extern crate rand;
1316

14-
use std::env;
15-
use time::Duration;
17+
use chrono::{Utc, NaiveDate, Duration};
18+
use diesel::pg::PgConnection;
19+
use diesel::prelude::*;
1620
use rand::{StdRng, Rng};
21+
use std::env;
22+
23+
use cargo_registry::schema::version_downloads;
1724

18-
#[allow(dead_code)]
1925
fn main() {
20-
let conn = cargo_registry::db::connect_now_old();
21-
{
22-
let tx = conn.transaction().unwrap();
23-
update(&tx).unwrap();
24-
tx.set_commit();
25-
tx.finish().unwrap();
26-
}
26+
let conn = cargo_registry::db::connect_now().unwrap();
27+
conn.transaction(|| update(&conn)).unwrap();
2728
}
2829

29-
fn update(tx: &postgres::transaction::Transaction) -> postgres::Result<()> {
30+
fn update(conn: &PgConnection) -> QueryResult<()> {
3031
let ids = env::args().skip(1).filter_map(
3132
|arg| arg.parse::<i32>().ok(),
3233
);
3334
for id in ids {
34-
let now = time::now_utc().to_timespec();
3535
let mut rng = StdRng::new().unwrap();
3636
let mut dls = rng.gen_range(5000i32, 10000);
3737

3838
for day in 0..90 {
39-
let moment = now + Duration::days(-day);
39+
let moment = Utc::now().date().naive_utc() + Duration::days(-day);
4040
dls += rng.gen_range(-100, 100);
41-
tx.execute(
42-
"INSERT INTO version_downloads \
43-
(version_id, downloads, date) \
44-
VALUES ($1, $2, $3)",
45-
&[&id, &dls, &moment],
46-
)?;
41+
42+
let version_download = VersionDownload {
43+
version_id: id,
44+
downloads: dls,
45+
date: moment,
46+
};
47+
diesel::insert(&version_download)
48+
.into(version_downloads::table)
49+
.execute(conn)?;
4750
}
4851
}
4952
Ok(())
5053
}
54+
55+
#[derive(Insertable)]
56+
#[table_name = "version_downloads"]
57+
struct VersionDownload {
58+
version_id: i32,
59+
downloads: i32,
60+
date: NaiveDate,
61+
}

0 commit comments

Comments
 (0)