♻️ refactor: ree.

This commit is contained in:
Dominic Harris 2022-04-04 16:20:25 -04:00
parent 648b6aac4e
commit 16f170c382
No known key found for this signature in database
GPG Key ID: 93CCF85F3E2A4F65
3 changed files with 21 additions and 27 deletions

View File

@ -1 +0,0 @@
ALTER TABLE pastes ADD column single_view BOOLEAN DEFAULT false;

View File

@ -1,21 +0,0 @@
CREATE TABLE IF NOT EXISTS pastes (
"id" TEXT PRIMARY KEY,
"content" TEXT NOT NULL,
"views" BIGINT DEFAULT 0,
"single_view" BOOLEAN DEFAULT false,
"expires_at" TIMESTAMP WITHOUT TIME ZONE,
"created_at" TIMESTAMP WITHOUT TIME ZONE DEFAULT(NOW() AT TIME ZONE 'utc')
);
CREATE OR REPLACE FUNCTION deleteExpiredPastes() RETURNS trigger AS $pastes_expire$ BEGIN
DELETE FROM pastes
WHERE "expires_at" IS NOT NULL
AND "expires_at" < now() AT TIME ZONE 'utc';
RETURN NEW;
END;
$pastes_expire$ LANGUAGE plpgsql;
CREATE TRIGGER checkPastes BEFORE
INSERT
OR
UPDATE ON pastes FOR STATEMENT EXECUTE PROCEDURE deleteExpiredPastes();

View File

@ -12,7 +12,11 @@ use actix_web::{
};
use config::Config;
use sqlx::{migrate::Migrator, postgres::PgPoolOptions, PgPool};
use sqlx::{
migrate::Migrator,
postgres::{PgPoolOptions, PgRow},
PgPool, Row,
};
use crate::routes::{
get_paste, get_raw_paste, get_stats, get_total_pastes_badge, get_version_badge, new_paste,
@ -25,10 +29,22 @@ pub struct AppState {
}
pub async fn migrations(pool: &PgPool) -> Result<(), sqlx::Error> {
Migrator::new(Path::new("./migrations"))
.await?
.run(pool)
.await?;
let mut migrator = Migrator::new(Path::new("./migrations")).await?;
for migration in migrator.iter() {
if migration.version == 0 {
let row: bool = sqlx::query("SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'pastes')")
.try_map(|row: PgRow| row.try_get::<bool, _>("exists"))
.fetch_one(pool).await?;
// The table exists so we dont want to run initial migration
if row == true {}
}
println!("Running migration: {:?}", migration);
}
migrator.run(pool).await?;
Ok(())
}