refactor: migrate to postgres
This commit is contained in:
parent
d4e68ccbd8
commit
2b014ad915
19 changed files with 181 additions and 81 deletions
|
|
@ -1,31 +1,33 @@
|
|||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT * FROM users WHERE name = ?",
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT * FROM users WHERE name = $1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "id",
|
||||
"ordinal": 0,
|
||||
"type_info": "Int64"
|
||||
"name": "id",
|
||||
"type_info": "Int8"
|
||||
},
|
||||
{
|
||||
"name": "name",
|
||||
"ordinal": 1,
|
||||
"name": "name",
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "password",
|
||||
"ordinal": 2,
|
||||
"name": "password",
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "is_admin",
|
||||
"ordinal": 3,
|
||||
"name": "is_admin",
|
||||
"type_info": "Bool"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
"Left": [
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
|
|
@ -34,5 +36,5 @@
|
|||
false
|
||||
]
|
||||
},
|
||||
"hash": "fbf4d83d9836cf85d01059e679bcbf7dc463eea0579afacc0267f0f8c33640d3"
|
||||
"hash": "d08992cf2c132fedbed21b94d545e154fa2a7a2a2bf79fd033341d1bb5a6c0f2"
|
||||
}
|
||||
9
.vscode/settings.json
vendored
9
.vscode/settings.json
vendored
|
|
@ -1,11 +1,4 @@
|
|||
{
|
||||
"sqltools.useNodeRuntime": true,
|
||||
"sqltools.connections": [
|
||||
{
|
||||
"previewLimit": 50,
|
||||
"driver": "SQLite",
|
||||
"name": "rave-users",
|
||||
"database": "${workspaceFolder:rave}/users.db"
|
||||
}
|
||||
]
|
||||
"sqltools.connections": []
|
||||
}
|
||||
|
|
@ -20,8 +20,12 @@ poem = { version = "1.3.58", features = [
|
|||
quick-xml = { version = "0.30.0", features = ["serialize"] }
|
||||
serde = { version = "1.0.188", features = ["derive"] }
|
||||
serde_json = "1.0.107"
|
||||
sqlx = { version = "0.7.2", features = ["time", "sqlite", "runtime-tokio"] }
|
||||
time = { version = "0.3.29", features = ["serde-human-readable", "macros", "parsing"] }
|
||||
sqlx = { version = "0.7.2", features = ["time", "postgres", "runtime-tokio"] }
|
||||
time = { version = "0.3.29", features = [
|
||||
"serde-human-readable",
|
||||
"macros",
|
||||
"parsing",
|
||||
] }
|
||||
tokio = { version = "1.32.0", features = ["full"] }
|
||||
tracing = { version = "0.1.37", features = ["async-await"] }
|
||||
tracing-subscriber = { version = "0.3.17", features = [
|
||||
|
|
|
|||
14
docker-compose.yml
Normal file
14
docker-compose.yml
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
version: '3'
|
||||
|
||||
services:
|
||||
dev-db:
|
||||
image: postgres:15
|
||||
restart: always
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_DB: postgres
|
||||
ports:
|
||||
- 12345:5432
|
||||
volumes:
|
||||
- /tmp/rave-dev-db:/var/lib/postgresql/data
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
-- Add migration script here
|
||||
CREATE TABLE users (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
password TEXT NOT NULL,
|
||||
is_admin BOOLEAN NOT NULL DEFAULT FALSE
|
||||
);
|
||||
INSERT INTO users (name, password, is_admin)
|
||||
VALUES ('admin', 'admin', TRUE);
|
||||
INSERT INTO users (id, name, password, is_admin)
|
||||
VALUES (0, 'admin', 'admin', TRUE);
|
||||
15
migrations/0002_create-albums.sql
Normal file
15
migrations/0002_create-albums.sql
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
-- Add migration script here
|
||||
CREATE TABLE IF NOT EXISTS album (
|
||||
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
artist TEXT,
|
||||
artist_id INTEGER,
|
||||
cover_art TEXT,
|
||||
song_count INTEGER,
|
||||
duration INTEGER,
|
||||
play_count INTEGER,
|
||||
created timestamptz DEFAULT current_timestamp,
|
||||
starred timestamptz DEFAULT current_timestamp,
|
||||
year INTEGER,
|
||||
genre TEXT
|
||||
);
|
||||
21
migrations/0003_create-tracks.sql
Normal file
21
migrations/0003_create-tracks.sql
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
-- Add migration script here
|
||||
CREATE TABLE IF NOT EXISTS tracks (
|
||||
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||
parent INTEGER NOT NULL REFERENCES album(id),
|
||||
is_dir BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
title TEXT NOT NULL,
|
||||
album TEXT,
|
||||
artist TEXT,
|
||||
track INTEGER,
|
||||
year INTEGER,
|
||||
genre TEXT,
|
||||
cover_art TEXT,
|
||||
duration INTEGER,
|
||||
path TEXT,
|
||||
play_count INTEGER,
|
||||
created timestamptz DEFAULT current_timestamp,
|
||||
starred timestamptz,
|
||||
album_id TEXT,
|
||||
artist_id TEXT,
|
||||
disc_number INTEGER
|
||||
)
|
||||
22
src/main.rs
22
src/main.rs
|
|
@ -1,19 +1,17 @@
|
|||
#![warn(clippy::pedantic, clippy::nursery)]
|
||||
#![deny(clippy::unwrap_used, clippy::panic)]
|
||||
#![deny(clippy::unwrap_used)]
|
||||
#![allow(clippy::module_name_repetitions, clippy::too_many_lines)]
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use color_eyre::Result;
|
||||
use poem::{
|
||||
get,
|
||||
listener::TcpListener,
|
||||
middleware,
|
||||
web::{CompressionAlgo, CompressionLevel},
|
||||
Endpoint, EndpointExt, Route,
|
||||
};
|
||||
use rest::build;
|
||||
use sqlx::SqlitePool;
|
||||
use sqlx::PgPool;
|
||||
use tracing::info;
|
||||
use tracing_subscriber::{fmt, EnvFilter};
|
||||
|
||||
|
|
@ -21,6 +19,7 @@ mod authentication;
|
|||
mod random_types;
|
||||
mod rest;
|
||||
mod subsonic;
|
||||
mod ui;
|
||||
mod user;
|
||||
mod utils;
|
||||
|
||||
|
|
@ -37,7 +36,7 @@ async fn main() -> Result<()> {
|
|||
|
||||
sqlx::migrate!().run(&pool).await?;
|
||||
|
||||
let route = route.with(middleware::AddData::new(pool));
|
||||
let route = route.with(utils::middleware::DbConnectionMiddleware::new(pool));
|
||||
|
||||
let server = create_server();
|
||||
|
||||
|
|
@ -52,18 +51,18 @@ async fn main() -> Result<()> {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
async fn create_pool() -> SqlitePool {
|
||||
async fn create_pool() -> PgPool {
|
||||
let url = std::env::var("DATABASE_URL").expect("DATABASE_URL not set");
|
||||
|
||||
SqlitePool::connect(&url)
|
||||
PgPool::connect(&url)
|
||||
.await
|
||||
.expect("Failed to connect to database")
|
||||
}
|
||||
|
||||
fn create_route() -> Box<dyn Endpoint<Output = poem::Response>> {
|
||||
Route::new()
|
||||
.at("/", get(hello_world))
|
||||
.nest("/rest", build())
|
||||
.nest("/", ui::build())
|
||||
.nest("/rest", rest::build())
|
||||
.with(middleware::CatchPanic::new())
|
||||
.with(
|
||||
middleware::Compression::new()
|
||||
|
|
@ -108,11 +107,6 @@ fn install_tracing() -> Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
#[poem::handler]
|
||||
const fn hello_world() -> &'static str {
|
||||
"Hello, world!"
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
|
|||
|
|
@ -1,20 +1,19 @@
|
|||
use poem::web::{Data, Query};
|
||||
use serde::Deserialize;
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use crate::{
|
||||
authentication::Authentication,
|
||||
subsonic::{AlbumId3, Child, Error, MediaType, SubsonicResponse},
|
||||
utils,
|
||||
utils::{self, middleware::DbConn},
|
||||
};
|
||||
|
||||
use poem::web::{Data, Query};
|
||||
use serde::Deserialize;
|
||||
|
||||
#[poem::handler]
|
||||
pub async fn get_album(
|
||||
Data(pool): Data<&SqlitePool>,
|
||||
Data(conn): Data<&DbConn>,
|
||||
auth: Authentication,
|
||||
Query(params): Query<GetAlbumParams>,
|
||||
) -> SubsonicResponse {
|
||||
let u = utils::verify_user(pool, auth).await;
|
||||
let u = utils::verify_user(conn.clone(), auth).await;
|
||||
|
||||
match u {
|
||||
Ok(_) => {}
|
||||
|
|
|
|||
|
|
@ -1,21 +1,20 @@
|
|||
use poem::web::{Data, Query};
|
||||
use serde::Deserialize;
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use crate::{
|
||||
authentication::Authentication,
|
||||
random_types::SortType,
|
||||
subsonic::{Child, Error, SubsonicResponse},
|
||||
utils,
|
||||
utils::{self, middleware::DbConn},
|
||||
};
|
||||
|
||||
#[poem::handler]
|
||||
pub async fn get_album_list(
|
||||
Data(pool): Data<&SqlitePool>,
|
||||
Data(conn): Data<&DbConn>,
|
||||
auth: Authentication,
|
||||
Query(params): Query<GetAlbumListParams>,
|
||||
) -> SubsonicResponse {
|
||||
let u = utils::verify_user(pool, auth).await;
|
||||
let u = utils::verify_user(conn.clone(), auth).await;
|
||||
|
||||
match u {
|
||||
Ok(_) => {}
|
||||
|
|
|
|||
|
|
@ -1,20 +1,19 @@
|
|||
use poem::web::{Data, Query};
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use crate::{
|
||||
authentication::Authentication,
|
||||
rest::get_album_list::GetAlbumListParams,
|
||||
subsonic::{AlbumId3, SubsonicResponse},
|
||||
utils,
|
||||
utils::{self, middleware::DbConn},
|
||||
};
|
||||
|
||||
#[poem::handler]
|
||||
pub async fn get_album_list2(
|
||||
Data(pool): Data<&SqlitePool>,
|
||||
Data(conn): Data<&DbConn>,
|
||||
auth: Authentication,
|
||||
Query(params): Query<GetAlbumListParams>,
|
||||
) -> SubsonicResponse {
|
||||
let u = utils::verify_user(pool, auth).await;
|
||||
let u = utils::verify_user(conn.clone(), auth).await;
|
||||
|
||||
match u {
|
||||
Ok(_) => {}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,14 @@
|
|||
use poem::web::Data;
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use crate::{authentication::Authentication, subsonic::SubsonicResponse, utils};
|
||||
use crate::{
|
||||
authentication::Authentication,
|
||||
subsonic::SubsonicResponse,
|
||||
utils::{self, middleware::DbConn},
|
||||
};
|
||||
|
||||
#[poem::handler]
|
||||
pub async fn get_license(Data(pool): Data<&SqlitePool>, auth: Authentication) -> SubsonicResponse {
|
||||
let u = utils::verify_user(pool, auth).await;
|
||||
pub async fn get_license(Data(conn): Data<&DbConn>, auth: Authentication) -> SubsonicResponse {
|
||||
let u = utils::verify_user(conn.clone(), auth).await;
|
||||
|
||||
match u {
|
||||
Ok(_) => {}
|
||||
|
|
|
|||
|
|
@ -1,18 +1,17 @@
|
|||
use poem::web::Data;
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use crate::{
|
||||
authentication::Authentication,
|
||||
subsonic::{MusicFolder, SubsonicResponse},
|
||||
utils,
|
||||
utils::{self, middleware::DbConn},
|
||||
};
|
||||
|
||||
#[poem::handler]
|
||||
pub async fn get_music_folders(
|
||||
Data(pool): Data<&SqlitePool>,
|
||||
Data(conn): Data<&DbConn>,
|
||||
auth: Authentication,
|
||||
) -> SubsonicResponse {
|
||||
let u = utils::verify_user(pool, auth).await;
|
||||
let u = utils::verify_user(conn.clone(), auth).await;
|
||||
|
||||
match u {
|
||||
Ok(_) => {}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,14 @@
|
|||
use poem::web::Data;
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use crate::{authentication::Authentication, subsonic::SubsonicResponse, utils};
|
||||
use crate::{
|
||||
authentication::Authentication,
|
||||
subsonic::SubsonicResponse,
|
||||
utils::{self, middleware::DbConn},
|
||||
};
|
||||
|
||||
#[poem::handler]
|
||||
pub async fn ping(Data(pool): Data<&SqlitePool>, auth: Authentication) -> SubsonicResponse {
|
||||
let u = utils::verify_user(pool, auth).await;
|
||||
pub async fn ping(Data(conn): Data<&DbConn>, auth: Authentication) -> SubsonicResponse {
|
||||
let u = utils::verify_user(conn.clone(), auth).await;
|
||||
|
||||
match u {
|
||||
Ok(_) => SubsonicResponse::new_empty(),
|
||||
|
|
|
|||
|
|
@ -4,19 +4,21 @@ use poem::{
|
|||
IntoResponse, Response,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use crate::{authentication::Authentication, utils};
|
||||
use crate::{
|
||||
authentication::Authentication,
|
||||
utils::{self, middleware::DbConn},
|
||||
};
|
||||
|
||||
const SONG: &[u8] = include_bytes!("../../../data.mp3");
|
||||
|
||||
#[poem::handler]
|
||||
pub async fn stream(
|
||||
Data(pool): Data<&SqlitePool>,
|
||||
Data(conn): Data<&DbConn>,
|
||||
auth: Authentication,
|
||||
Query(_params): Query<StreamParams>,
|
||||
) -> Response {
|
||||
let u = utils::verify_user(pool, auth).await;
|
||||
let u = utils::verify_user(conn.clone(), auth).await;
|
||||
|
||||
match u {
|
||||
Ok(_) => {}
|
||||
|
|
|
|||
5
src/ui.rs
Normal file
5
src/ui.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
use poem::{Endpoint, EndpointExt, Route};
|
||||
|
||||
pub fn build() -> Box<dyn Endpoint<Output = poem::Response>> {
|
||||
Route::new().boxed()
|
||||
}
|
||||
15
src/user.rs
15
src/user.rs
|
|
@ -1,6 +1,7 @@
|
|||
use color_eyre::Result;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use crate::utils::middleware::DbConn;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct User {
|
||||
|
|
@ -20,10 +21,10 @@ impl User {
|
|||
}
|
||||
}
|
||||
|
||||
pub async fn get_user(pool: &SqlitePool, name: &str) -> Result<Option<User>> {
|
||||
Ok(
|
||||
sqlx::query_as!(User, "SELECT * FROM users WHERE name = ?", name)
|
||||
.fetch_optional(pool)
|
||||
.await?,
|
||||
)
|
||||
pub async fn get_user(conn: DbConn, name: &str) -> Result<Option<User>> {
|
||||
let user = sqlx::query_as!(User, "SELECT * FROM users WHERE name = $1", name)
|
||||
.fetch_optional(&*conn)
|
||||
.await?;
|
||||
|
||||
Ok(user)
|
||||
}
|
||||
|
|
|
|||
12
src/utils.rs
12
src/utils.rs
|
|
@ -1,4 +1,3 @@
|
|||
use sqlx::SqlitePool;
|
||||
use tracing::error;
|
||||
|
||||
use crate::{
|
||||
|
|
@ -7,11 +6,10 @@ use crate::{
|
|||
user::{get_user, User},
|
||||
};
|
||||
|
||||
pub async fn verify_user(
|
||||
pool: &SqlitePool,
|
||||
auth: Authentication,
|
||||
) -> Result<User, SubsonicResponse> {
|
||||
let user = get_user(pool, &auth.username).await;
|
||||
use self::middleware::DbConn;
|
||||
|
||||
pub async fn verify_user(conn: DbConn, auth: Authentication) -> Result<User, SubsonicResponse> {
|
||||
let user = get_user(conn, &auth.username).await;
|
||||
|
||||
match user {
|
||||
Ok(Some(u)) => {
|
||||
|
|
@ -34,3 +32,5 @@ pub async fn verify_user(
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub mod middleware;
|
||||
|
|
|
|||
47
src/utils/middleware.rs
Normal file
47
src/utils/middleware.rs
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use poem::{Endpoint, Middleware};
|
||||
use sqlx::PgPool;
|
||||
|
||||
pub type DbConn = Arc<PgPool>;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct DbConnectionMiddleware {
|
||||
db: PgPool,
|
||||
}
|
||||
|
||||
impl DbConnectionMiddleware {
|
||||
pub const fn new(db: PgPool) -> Self {
|
||||
Self { db }
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: Endpoint> Middleware<E> for DbConnectionMiddleware {
|
||||
type Output = DbConnectionMwEndpoint<E>;
|
||||
|
||||
fn transform(&self, ep: E) -> Self::Output {
|
||||
DbConnectionMwEndpoint {
|
||||
inner: ep,
|
||||
db: self.db.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct DbConnectionMwEndpoint<E> {
|
||||
inner: E,
|
||||
db: PgPool,
|
||||
}
|
||||
|
||||
#[poem::async_trait]
|
||||
impl<E: Endpoint> Endpoint for DbConnectionMwEndpoint<E> {
|
||||
type Output = E::Output;
|
||||
|
||||
async fn call(&self, mut req: poem::Request) -> Result<Self::Output, poem::Error> {
|
||||
let conn = Arc::new(self.db.clone());
|
||||
|
||||
req.extensions_mut().insert(conn);
|
||||
|
||||
self.inner.call(req).await
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue