insert tasks

This commit is contained in:
Ayrat Badykov 2021-06-06 11:44:46 +03:00
parent 8f1f1cc7fa
commit 506fd1c4cb
No known key found for this signature in database
GPG key ID: 16AE533AB7A3E8C6
6 changed files with 75 additions and 6 deletions

View file

@ -9,5 +9,8 @@ license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
diesel = { version = "1.4.6", features = ["postgres"] }
diesel = { version = "1.4.6", features = ["postgres", "serde_json", "chrono", "uuidv07"] }
dotenv = "0.15.0"
uuid = { version = "0.8", features = ["v4"] }
chrono = "0.4"
serde_json = "1.0"

View file

@ -1 +1 @@
-- This file should undo anything in `up.sql`
DROP TABLE fang_tasks;

View file

@ -1,6 +1,8 @@
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE TABLE fang_tasks (
id BIGSERIAL primary key,
metadata jsonb,
id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
metadata jsonb NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);

View file

@ -1,3 +1,6 @@
#[macro_use]
extern crate diesel;
// pub trait JobQueue {
// type Job;
// type Error;
@ -11,6 +14,10 @@
// pub trait Storage {
// fn save() ->
// }
pub mod postgres;
mod schema;
#[cfg(test)]
mod tests {
#[test]

57
src/postgres.rs Normal file
View file

@ -0,0 +1,57 @@
use crate::schema::fang_tasks;
use chrono::{DateTime, Utc};
use diesel::pg::PgConnection;
use diesel::prelude::*;
use diesel::result::Error;
use dotenv::dotenv;
use std::env;
use uuid::Uuid;
#[derive(Queryable, Identifiable, Debug, Eq, PartialEq)]
#[table_name = "fang_tasks"]
pub struct Task {
pub id: Uuid,
pub metadata: serde_json::Value,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
#[derive(Insertable)]
#[table_name = "fang_tasks"]
pub struct NewTask {
pub metadata: serde_json::Value,
}
pub struct Postgres {
pub database_url: String,
pub connection: PgConnection,
}
impl Postgres {
pub fn new(database_url: Option<String>) -> Self {
dotenv().ok();
let url = match database_url {
Some(string_url) => string_url,
None => {
let url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
url
}
};
let connection =
PgConnection::establish(&url).expect(&format!("Error connecting to {}", url));
Self {
connection,
database_url: url,
}
}
pub fn insert(&self, params: &NewTask) -> Result<Task, Error> {
diesel::insert_into(fang_tasks::table)
.values(params)
.get_result::<Task>(&self.connection)
}
}

View file

@ -1,7 +1,7 @@
table! {
fang_tasks (id) {
id -> Int8,
metadata -> Nullable<Jsonb>,
id -> Uuid,
metadata -> Jsonb,
created_at -> Timestamptz,
updated_at -> Timestamptz,
}