Lots of stuffs

Primarely setup stuffs for diesel
TODO: Add switch in src/storage/mod.rs for sqlite/postgres
This commit is contained in:
mStar aka a person 2023-12-31 22:50:58 +00:00
parent 180a4a7771
commit 4732b00085
22 changed files with 142 additions and 13 deletions

View file

@ -26,7 +26,7 @@
// "forwardPorts": [],
// Use 'postCreateCommand' to run commands after the container is created.
"postCreateCommand": "cargo install diesel_cli --no-default-features --features postgres sqlite"
"postCreateCommand": "cargo install diesel_cli --no-default-features --features postgres,sqlite"
// Configure tool-specific properties.
// "customizations": {},

1
.env
View file

@ -1 +0,0 @@
DATABASE_URL=./src/storage/db.sqlite

4
.gitignore vendored
View file

@ -1,2 +1,4 @@
/target
src/storage/db.sqlite
db.sqlite
.env
.lapce/

File diff suppressed because one or more lines are too long

3
diesel-devel Executable file
View file

@ -0,0 +1,3 @@
#/bin/bash
touch db.sqlite
DATABASE_URL="db.sqlite";diesel --config-file diesel_devel.toml $@

View file

@ -2,8 +2,8 @@
# see https://diesel.rs/guides/configuring-diesel-cli
[print_schema]
file = "src/schema.rs"
file = "src/storage/diesel_db/postgres.rs"
custom_type_derives = ["diesel::query_builder::QueryId"]
[migrations_directory]
dir = "migrations"
dir = "migrations/postgres"

9
diesel_devel.toml Normal file
View file

@ -0,0 +1,9 @@
# For documentation on how to configure this file,
# see https://diesel.rs/guides/configuring-diesel-cli
[print_schema]
file = "src/storage/diesel_db/sqlite.rs"
custom_type_derives = ["diesel::query_builder::QueryId"]
[migrations_directory]
dir = "migrations/sqlite"

View file

View file

@ -0,0 +1,6 @@
-- This file was automatically created by Diesel to setup helper functions
-- and other internal bookkeeping. This file is safe to edit, any future
-- changes will be added to existing projects as new migrations.
DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass);
DROP FUNCTION IF EXISTS diesel_set_updated_at();

View file

@ -0,0 +1,36 @@
-- This file was automatically created by Diesel to setup helper functions
-- and other internal bookkeeping. This file is safe to edit, any future
-- changes will be added to existing projects as new migrations.
-- Sets up a trigger for the given table to automatically set a column called
-- `updated_at` whenever the row is modified (unless `updated_at` was included
-- in the modified columns)
--
-- # Example
--
-- ```sql
-- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW());
--
-- SELECT diesel_manage_updated_at('users');
-- ```
CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$
BEGIN
EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s
FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl);
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$
BEGIN
IF (
NEW IS DISTINCT FROM OLD AND
NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at
) THEN
NEW.updated_at := current_timestamp;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

10
migrations/sqlite/.keep Normal file
View file

@ -0,0 +1,10 @@
// Copyright (c) 2023 mStar
//
// Licensed under the EUPL, Version 1.2
//
// You may not use this work except in compliance with the Licence.
// You should have received a copy of the Licence along with this work. If not, see:
// <https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12>.
// See the Licence for the specific language governing permissions and limitations under the Licence.
//

View file

@ -0,0 +1,6 @@
-- This file was automatically created by Diesel to setup helper functions
-- and other internal bookkeeping. This file is safe to edit, any future
-- changes will be added to existing projects as new migrations.
DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass);
DROP FUNCTION IF EXISTS diesel_set_updated_at();

View file

@ -0,0 +1,36 @@
-- This file was automatically created by Diesel to setup helper functions
-- and other internal bookkeeping. This file is safe to edit, any future
-- changes will be added to existing projects as new migrations.
-- Sets up a trigger for the given table to automatically set a column called
-- `updated_at` whenever the row is modified (unless `updated_at` was included
-- in the modified columns)
--
-- # Example
--
-- ```sql
-- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW());
--
-- SELECT diesel_manage_updated_at('users');
-- ```
CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$
BEGIN
EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s
FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl);
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$
BEGIN
IF (
NEW IS DISTINCT FROM OLD AND
NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at
) THEN
NEW.updated_at := current_timestamp;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

View file

@ -0,0 +1 @@
-- This file should undo anything in `up.sql`

View file

@ -0,0 +1 @@
-- Your SQL goes here

View file

@ -17,5 +17,5 @@ mod webui;
fn main() {
storage::establish_connection("./src/storage/db.sqlite");
let _ = storage::establish_connection("./src/storage/db.sqlite");
}

View file

@ -0,0 +1,12 @@
// Copyright (c) 2023 mStar
//
// Licensed under the EUPL, Version 1.2
//
// You may not use this work except in compliance with the Licence.
// You should have received a copy of the Licence along with this work. If not, see:
// <https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12>.
// See the Licence for the specific language governing permissions and limitations under the Licence.
//
mod sqlite;
mod postgres;

View file

View file

View file

@ -8,19 +8,27 @@
// See the Licence for the specific language governing permissions and limitations under the Licence.
//
use diesel::{prelude::*, pg::PgConnection, sqlite::Sqlite};
mod diesel_db;
use anyhow::{Error, bail};
use diesel::{prelude::*, pg::{PgConnection, Pg}};
use diesel_migrations::{EmbeddedMigrations, embed_migrations, MigrationHarness};
use std::error::Error;
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations");
pub const POSTGRES_MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations/postgres");
pub fn establish_connection(db_url: &str) -> Result<PgConnection, Error> {
//SqliteConnection::establish(db_url).unwrap_or_else(|e| panic!("Error connecting to {}: {}", db_url, e))
let mut conn = PgConnection::establish(db_url)
.unwrap_or_else(|e| panic!("Error connecting to {}: {}", db_url, e));
// TODO: Add migrations here
let c: MigrationHarness<PgConnection> = &mut conn;
c.run_pending_migrations(MIGRATIONS)?;
run_migrations(&mut conn)?;
//c.run_pending_migrations(MIGRATIONS)?;
Ok(conn)
}
fn run_migrations(conn: &mut impl MigrationHarness<Pg>) -> Result<(), Error> {
match conn.run_pending_migrations(POSTGRES_MIGRATIONS) {
Ok(_) => Ok(()),
Err(e) => bail!("Migrations failed. Error {}", e)
}
}