Skip to content

Commit

Permalink
refactor(webserver): add DAO suffix to database bridge objects (#1133)
Browse files Browse the repository at this point in the history
  • Loading branch information
wsxiaoys authored Dec 27, 2023
1 parent 3339a6c commit aee107c
Show file tree
Hide file tree
Showing 6 changed files with 50 additions and 48 deletions.
4 changes: 2 additions & 2 deletions ee/tabby-webserver/src/service/cron/job_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ use tokio::{io::AsyncBufReadExt, process::Child};
use tokio_cron_scheduler::Job;
use tracing::error;

use crate::service::db::{DbConn, JobRun};
use crate::service::db::{DbConn, JobRunDAO};

pub async fn run_job(db_conn: DbConn, job_name: String, schedule: &str) -> anyhow::Result<Job> {
let job = Job::new_async(schedule, move |_, _| {
let job_name = job_name.clone();
let db_conn = db_conn.clone();
Box::pin(async move {
// create job run record
let mut run = JobRun {
let mut run = JobRunDAO {
job_name: job_name.clone(),
start_time: chrono::Utc::now(),
..Default::default()
Expand Down
16 changes: 8 additions & 8 deletions ee/tabby-webserver/src/service/db/invitations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ use uuid::Uuid;
use super::DbConn;
use crate::schema::auth;

pub struct Invitation {
pub struct InvitationDAO {
pub id: i32,
pub email: String,
pub code: String,

pub created_at: String,
}

impl Invitation {
impl InvitationDAO {
fn from_row(row: &Row<'_>) -> std::result::Result<Self, rusqlite::Error> {
Ok(Self {
id: row.get(0)?,
Expand All @@ -24,8 +24,8 @@ impl Invitation {
}
}

impl From<Invitation> for auth::InvitationNext {
fn from(val: Invitation) -> Self {
impl From<InvitationDAO> for auth::InvitationNext {
fn from(val: InvitationDAO) -> Self {
Self {
id: juniper::ID::new(val.id.to_string()),
email: val.email,
Expand All @@ -42,7 +42,7 @@ impl DbConn {
limit: Option<usize>,
skip_id: Option<i32>,
backwards: bool,
) -> Result<Vec<Invitation>> {
) -> Result<Vec<InvitationDAO>> {
let query = Self::make_pagination_query(
"invitations",
&["id", "email", "code", "created_at"],
Expand All @@ -55,15 +55,15 @@ impl DbConn {
.conn
.call(move |c| {
let mut stmt = c.prepare(&query)?;
let invit_iter = stmt.query_map([], Invitation::from_row)?;
let invit_iter = stmt.query_map([], InvitationDAO::from_row)?;
Ok(invit_iter.filter_map(|x| x.ok()).collect::<Vec<_>>())
})
.await?;

Ok(invitations)
}

pub async fn get_invitation_by_code(&self, code: &str) -> Result<Option<Invitation>> {
pub async fn get_invitation_by_code(&self, code: &str) -> Result<Option<InvitationDAO>> {
let code = code.to_owned();
let token = self
.conn
Expand All @@ -72,7 +72,7 @@ impl DbConn {
.query_row(
r#"SELECT id, email, code, created_at FROM invitations WHERE code = ?"#,
[code],
Invitation::from_row,
InvitationDAO::from_row,
)
.optional())
})
Expand Down
22 changes: 11 additions & 11 deletions ee/tabby-webserver/src/service/db/job_runs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use super::DbConn;
use crate::schema::job;

#[derive(Default, Clone)]
pub struct JobRun {
pub struct JobRunDAO {
pub id: i32,
pub job_name: String,
pub start_time: DateTime<Utc>,
Expand All @@ -15,7 +15,7 @@ pub struct JobRun {
pub stderr: String,
}

impl JobRun {
impl JobRunDAO {
fn from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Self> {
Ok(Self {
id: row.get(0)?,
Expand All @@ -29,8 +29,8 @@ impl JobRun {
}
}

impl From<JobRun> for job::JobRun {
fn from(run: JobRun) -> Self {
impl From<JobRunDAO> for job::JobRun {
fn from(run: JobRunDAO) -> Self {
Self {
id: juniper::ID::new(run.id.to_string()),
job_name: run.job_name,
Expand All @@ -45,7 +45,7 @@ impl From<JobRun> for job::JobRun {

/// db read/write operations for `job_runs` table
impl DbConn {
pub async fn create_job_run(&self, run: JobRun) -> Result<i32> {
pub async fn create_job_run(&self, run: JobRunDAO) -> Result<i32> {
let rowid = self
.conn
.call(move |c| {
Expand Down Expand Up @@ -93,7 +93,7 @@ impl DbConn {
Ok(())
}

pub async fn update_job_status(&self, run: JobRun) -> Result<()> {
pub async fn update_job_status(&self, run: JobRunDAO) -> Result<()> {
self.conn
.call(move |c| {
let mut stmt = c.prepare(
Expand All @@ -115,7 +115,7 @@ impl DbConn {
limit: Option<usize>,
skip_id: Option<i32>,
backwards: bool,
) -> Result<Vec<JobRun>> {
) -> Result<Vec<JobRunDAO>> {
let query = Self::make_pagination_query(
"job_runs",
&[
Expand All @@ -136,7 +136,7 @@ impl DbConn {
.conn
.call(move |c| {
let mut stmt = c.prepare(&query)?;
let run_iter = stmt.query_map([], JobRun::from_row)?;
let run_iter = stmt.query_map([], JobRunDAO::from_row)?;
Ok(run_iter.filter_map(|x| x.ok()).collect::<Vec<_>>())
})
.await?;
Expand All @@ -152,7 +152,7 @@ mod tests {
#[tokio::test]
async fn test_create_job_run() {
let db = DbConn::new_in_memory().await.unwrap();
let run = JobRun {
let run = JobRunDAO {
id: 0,
job_name: "test".to_string(),
start_time: chrono::Utc::now(),
Expand All @@ -164,7 +164,7 @@ mod tests {
let id = db.create_job_run(run).await.unwrap();
assert_eq!(id, 1);

let run = JobRun {
let run = JobRunDAO {
id: 0,
job_name: "test".to_string(),
start_time: chrono::Utc::now(),
Expand All @@ -176,7 +176,7 @@ mod tests {
let id = db.create_job_run(run).await.unwrap();
assert_eq!(id, 2);

let run = JobRun {
let run = JobRunDAO {
id: 0,
job_name: "test".to_string(),
start_time: chrono::Utc::now(),
Expand Down
2 changes: 1 addition & 1 deletion ee/tabby-webserver/src/service/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ mod users;

use anyhow::Result;
use include_dir::{include_dir, Dir};
pub use job_runs::JobRun;
pub use job_runs::JobRunDAO;
use lazy_static::lazy_static;
use rusqlite::params;
use rusqlite_migration::AsyncMigrations;
Expand Down
14 changes: 7 additions & 7 deletions ee/tabby-webserver/src/service/db/refresh_tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use rusqlite::{params, OptionalExtension, Row};
use super::DbConn;

#[allow(unused)]
pub struct RefreshToken {
pub struct RefreshTokenDAO {
id: u32,
created_at: DateTime<Utc>,

Expand All @@ -14,14 +14,14 @@ pub struct RefreshToken {
pub expires_at: DateTime<Utc>,
}

impl RefreshToken {
impl RefreshTokenDAO {
fn select(clause: &str) -> String {
r#"SELECT id, user_id, token, expires_at, created_at FROM refresh_tokens WHERE "#.to_owned()
+ clause
}

fn from_row(row: &Row<'_>) -> std::result::Result<RefreshToken, rusqlite::Error> {
Ok(RefreshToken {
fn from_row(row: &Row<'_>) -> std::result::Result<RefreshTokenDAO, rusqlite::Error> {
Ok(RefreshTokenDAO {
id: row.get(0)?,
user_id: row.get(1)?,
token: row.get(2)?,
Expand Down Expand Up @@ -89,15 +89,15 @@ impl DbConn {
Ok(res? as i32)
}

pub async fn get_refresh_token(&self, token: &str) -> Result<Option<RefreshToken>> {
pub async fn get_refresh_token(&self, token: &str) -> Result<Option<RefreshTokenDAO>> {
let token = token.to_string();
let token = self
.conn
.call(move |c| {
Ok(c.query_row(
RefreshToken::select("token = ?").as_str(),
RefreshTokenDAO::select("token = ?").as_str(),
params![token],
RefreshToken::from_row,
RefreshTokenDAO::from_row,
)
.optional())
})
Expand Down
40 changes: 21 additions & 19 deletions ee/tabby-webserver/src/service/db/users.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use super::DbConn;
use crate::schema::auth;

#[allow(unused)]
pub struct User {
pub struct UserDAO {
created_at: DateTime<Utc>,
updated_at: DateTime<Utc>,

Expand All @@ -20,15 +20,15 @@ pub struct User {
pub auth_token: String,
}

impl User {
impl UserDAO {
fn select(clause: &str) -> String {
r#"SELECT id, email, password_encrypted, is_admin, created_at, updated_at, auth_token FROM users WHERE "#
.to_owned()
+ clause
}

fn from_row(row: &Row<'_>) -> std::result::Result<User, rusqlite::Error> {
Ok(User {
fn from_row(row: &Row<'_>) -> std::result::Result<UserDAO, rusqlite::Error> {
Ok(UserDAO {
id: row.get(0)?,
email: row.get(1)?,
password_encrypted: row.get(2)?,
Expand All @@ -40,8 +40,8 @@ impl User {
}
}

impl From<User> for auth::User {
fn from(val: User) -> Self {
impl From<UserDAO> for auth::User {
fn from(val: UserDAO) -> Self {
auth::User {
id: juniper::ID::new(val.id.to_string()),
email: val.email,
Expand Down Expand Up @@ -106,29 +106,31 @@ impl DbConn {
Ok(res as i32)
}

pub async fn get_user(&self, id: i32) -> Result<Option<User>> {
pub async fn get_user(&self, id: i32) -> Result<Option<UserDAO>> {
let user = self
.conn
.call(move |c| {
Ok(
c.query_row(User::select("id = ?").as_str(), params![id], User::from_row)
.optional(),
Ok(c.query_row(
UserDAO::select("id = ?").as_str(),
params![id],
UserDAO::from_row,
)
.optional())
})
.await?;

Ok(user?)
}

pub async fn get_user_by_email(&self, email: &str) -> Result<Option<User>> {
pub async fn get_user_by_email(&self, email: &str) -> Result<Option<UserDAO>> {
let email = email.to_owned();
let user = self
.conn
.call(move |c| {
Ok(c.query_row(
User::select("email = ?").as_str(),
UserDAO::select("email = ?").as_str(),
params![email],
User::from_row,
UserDAO::from_row,
)
.optional())
})
Expand All @@ -137,12 +139,12 @@ impl DbConn {
Ok(user?)
}

pub async fn list_admin_users(&self) -> Result<Vec<User>> {
pub async fn list_admin_users(&self) -> Result<Vec<UserDAO>> {
let users = self
.conn
.call(move |c| {
let mut stmt = c.prepare(&User::select("is_admin"))?;
let user_iter = stmt.query_map([], User::from_row)?;
let mut stmt = c.prepare(&UserDAO::select("is_admin"))?;
let user_iter = stmt.query_map([], UserDAO::from_row)?;
Ok(user_iter.filter_map(|x| x.ok()).collect::<Vec<_>>())
})
.await?;
Expand All @@ -155,7 +157,7 @@ impl DbConn {
limit: Option<usize>,
skip_id: Option<i32>,
backwards: bool,
) -> Result<Vec<User>> {
) -> Result<Vec<UserDAO>> {
let query = Self::make_pagination_query(
"users",
&[
Expand All @@ -176,7 +178,7 @@ impl DbConn {
.conn
.call(move |c| {
let mut stmt = c.prepare(&query)?;
let user_iter = stmt.query_map([], User::from_row)?;
let user_iter = stmt.query_map([], UserDAO::from_row)?;
Ok(user_iter.filter_map(|x| x.ok()).collect::<Vec<_>>())
})
.await?;
Expand Down Expand Up @@ -269,7 +271,7 @@ mod tests {
let conn = DbConn::new_in_memory().await.unwrap();

let empty: Vec<i32> = vec![];
let to_ids = |users: Vec<User>| users.into_iter().map(|u| u.id).collect::<Vec<_>>();
let to_ids = |users: Vec<UserDAO>| users.into_iter().map(|u| u.id).collect::<Vec<_>>();

// empty
// forwards
Expand Down

0 comments on commit aee107c

Please sign in to comment.