Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ anyhow = "1.0.75"
async-trait = "0.1.73"
aws-config = "0.56.1"
aws-sdk-s3 = "0.31.2"
clap = { version = "4.4.5", features = ["derive"] }
dotenvy = "0.15.7"
rusqlite = { version = "0.29.0", features = ["backup"] }
tempfile = "3.8.0"
Expand Down
26 changes: 10 additions & 16 deletions src/argument.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,14 @@
use anyhow::{bail, Result};

use crate::errors::SqliteBackupError;
use clap::Parser;

/// Easily to backup your SQLite database
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
pub struct Argument {
pub source_path: String,
}
/// The project name
#[arg(long, default_value = "default")]
pub project_name: String,

impl Argument {
pub fn build(args: &[String]) -> Result<Self> {
if let Some(source_path) = args.get(1) {
let argument = Self {
source_path: source_path.clone(),
};
Ok(argument)
} else {
bail!(SqliteBackupError::NoSourceFileError);
}
}
/// The path to the database to backup
#[arg(long)]
pub db: String,
}
13 changes: 2 additions & 11 deletions src/backup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,14 @@ pub trait Backup {
pub struct SqliteSourceFile<'a> {
pub path: &'a Path,
pub filename: &'a str,
pub db_name: &'a str,
pub db_extension: &'a str,
}

impl<'a> SqliteSourceFile<'a> {
pub fn from(src_path: &'a str) -> Result<Self> {
let path = Path::new(src_path);
let filename = convert_os_str_result_to_str(path.file_name())?;
let db_name = convert_os_str_result_to_str(path.file_stem())?;
let db_extension = convert_os_str_result_to_str(path.extension())?;

Ok(Self {
path,
filename,
db_name,
db_extension,
})

Ok(Self { path, filename })
}
}

Expand Down
6 changes: 4 additions & 2 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use std::{env, fmt::Display};

use anyhow::Result;

#[derive(PartialEq)]
enum AppEnv {
#[derive(PartialEq, Debug)]
pub enum AppEnv {
Prod,
Dev,
Test,
Expand All @@ -22,6 +22,7 @@ impl Display for AppEnv {

#[derive(Debug)]
pub struct Config {
pub app_env: AppEnv,
pub bucket_name: String,
pub account_id: String,
pub access_key_id: String,
Expand All @@ -47,6 +48,7 @@ impl Config {
}

let config = Self {
app_env,
bucket_name: env::var("BUCKET_NAME")?,
account_id: env::var("ACCOUNT_ID")?,
access_key_id: env::var("ACCESS_KEY_ID")?,
Expand Down
24 changes: 7 additions & 17 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,18 @@
use anyhow::{Context, Result};
use clap::Parser;
use rusqlite::Connection;
use sqlite_backup::{
argument,
argument::{self, Argument},
backup::{Backup, SqliteBackup, SqliteSourceFile},
config::Config,
uploader::{R2Uploader, Uploader},
};
use std::env;

#[tokio::main]
async fn main() -> Result<()> {
let cfg = Config::load().context("load env vars")?;
let args = env::args().collect::<Vec<String>>();
match argument::Argument::build(&args) {
Ok(arg) => run(&arg, &cfg).await?,

Err(err) => eprintln!("Application Error: {}", err),
}
let args = Argument::parse();
run(&args, &cfg).await?;

println!("Done");

Expand All @@ -28,7 +24,7 @@ async fn run(arg: &argument::Argument, cfg: &Config) -> Result<()> {
let tmp_dir = tempfile::tempdir()?;

// backup data
let src_file = SqliteSourceFile::from(arg.source_path.as_str()).context("parse source path")?;
let src_file = SqliteSourceFile::from(arg.db.as_str()).context("parse source path")?;
let src_conn = Connection::open(src_file.path).context("create source connection")?;
let dest = tmp_dir.path().join(src_file.filename);
SqliteBackup::new(src_conn, dest.display().to_string(), |p| {
Expand All @@ -41,14 +37,8 @@ async fn run(arg: &argument::Argument, cfg: &Config) -> Result<()> {
.context("backup source to destination")?;

// upload
let uploader = R2Uploader::new(cfg).await;
uploader
.upload_object(
dest,
format!("sqlite__{}", src_file.db_name).as_str(),
src_file.db_extension,
)
.await?;
let uploader = R2Uploader::new(arg, cfg).await;
uploader.upload_object(dest, src_file.filename).await?;

// close temp dir
tmp_dir.close()?;
Expand Down
22 changes: 16 additions & 6 deletions src/uploader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,25 @@ use aws_sdk_s3::{
};
use time::format_description;

use crate::config::{self};
use crate::{
argument,
config::{self},
};

#[async_trait]
pub trait Uploader {
async fn upload_object(&self, path: PathBuf, db_name: &str, extension: &str) -> Result<()>;
async fn upload_object(&self, src_path: PathBuf, dest_name: &str) -> Result<()>;
}

pub struct R2Uploader {
client: Client,
bucket: String,
project_name: String,
app_env: String,
}

impl R2Uploader {
pub async fn new(cfg: &config::Config) -> Self {
pub async fn new(arg: &argument::Argument, cfg: &config::Config) -> Self {
let endpoint = format!(
"https://{}.r2.cloudflarestorage.com",
cfg.account_id.clone()
Expand All @@ -46,20 +51,25 @@ impl R2Uploader {
Self {
client,
bucket: cfg.bucket_name.clone(),
project_name: arg.project_name.clone(),
app_env: cfg.app_env.to_string(),
}
}
}

#[async_trait]
impl Uploader for R2Uploader {
async fn upload_object(&self, path: PathBuf, db_name: &str, extension: &str) -> Result<()> {
let body = ByteStream::from_path(path)
async fn upload_object(&self, src_path: PathBuf, dest_name: &str) -> Result<()> {
let body = ByteStream::from_path(src_path)
.await
.context("create file stream")?;
let key = uuid::Uuid::new_v4();
let format = format_description::parse("[year]-[month]-[day]")?;
let today = time::OffsetDateTime::now_utc().format(&format)?;
let object_key = format!("{db_name}/{today}__{key}.{extension}");
let object_key = format!(
"{}/{}/{}/{today}__{key}",
self.app_env, self.project_name, dest_name,
);

self.client
.put_object()
Expand Down