Skip to content

Commit

Permalink
sqlite connection uri and minor fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
harshdoesdev committed Oct 31, 2023
1 parent 3ca7ef0 commit 45278e6
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 41 deletions.
3 changes: 2 additions & 1 deletion fastn-core/src/library2022/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,12 +280,13 @@ impl Library2022 {
"user-details" => processor::user_details::process(value, kind, doc, &self.config),
"fastn-apps" => processor::apps::process(value, kind, doc, &self.config),
"is-reader" => processor::user_group::is_reader(value, kind, doc, &self.config).await,
"sql" => processor::sql::process(value, kind, doc).await,
"sql" => processor::sql::process(value, kind, doc, &self.config).await,
"package-query" => {
processor::sqlite::process(
value,
kind,
doc,
&self.config,
&fastn_core::library2022::processor::sql::get_db_config()?,
)
.await
Expand Down
34 changes: 10 additions & 24 deletions fastn-core/src/library2022/processor/sql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,45 +7,31 @@ pub struct DatabaseConfig {
pub(crate) fn get_db_config() -> ftd::interpreter::Result<DatabaseConfig> {
let db_url = std::env::var("FASTN_DB_URL").expect("FASTN_DB_URL is not set");

if db_url.contains("://") {
if let Some(db_url) = db_url.strip_prefix("sqlite:///") {
Ok(DatabaseConfig {
db_url: db_url.to_string(),
db_type: "sqlite".to_string(),
})
} else {
let url = url::Url::parse(&db_url).expect("Invalid DB Url");
let db_type = url.scheme().to_string();
let config = DatabaseConfig { db_url, db_type };
Ok(config)
} else {
let config = if db_url == ":memory:" {
DatabaseConfig {
db_url,
db_type: "sqlite".to_string(),
}
} else if let Some(path) = db_url.strip_prefix("file://") {
DatabaseConfig {
db_url: path.to_string(),
db_type: "sqlite".to_string(),
}
} else {
DatabaseConfig {
db_url,
db_type: "sqlite".to_string(),
}
};

Ok(config)
Ok(DatabaseConfig { db_url, db_type })
}
}

pub async fn process(
value: ftd::ast::VariableValue,
kind: ftd::interpreter::Kind,
doc: &ftd::interpreter::TDoc<'_>,
config: &fastn_core::Config,
) -> ftd::interpreter::Result<ftd::interpreter::Value> {
let db_config = fastn_core::library2022::processor::sql::get_db_config()?;
let db_type = db_config.db_type.as_str();

match db_type {
"pg" => Ok(fastn_core::library2022::processor::pg::process(value, kind, doc).await?),
"postgres" => Ok(fastn_core::library2022::processor::pg::process(value, kind, doc).await?),
"sqlite" => Ok(fastn_core::library2022::processor::sqlite::process(
value, kind, doc, &db_config,
value, kind, doc, config, &db_config,
)
.await?),
_ => unimplemented!("Database currently not supported."),
Expand Down
35 changes: 19 additions & 16 deletions fastn-core/src/library2022/processor/sqlite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub async fn process(
value: ftd::ast::VariableValue,
kind: ftd::interpreter::Kind,
doc: &ftd::interpreter::TDoc<'_>,
config: &fastn_core::Config,
db_config: &fastn_core::library2022::processor::sql::DatabaseConfig,
) -> ftd::interpreter::Result<ftd::interpreter::Value> {
let (headers, query) = get_p1_data("package-data", &value, doc.name)?;
Expand All @@ -40,14 +41,9 @@ pub async fn process(
// for now they wil be ordered
// select * from users where

let query_response = execute_query(
db_config.db_url.as_str(),
query.as_str(),
doc,
headers,
value.line_number(),
)
.await;
let db_path = config.root.join(&db_config.db_url);
let query_response =
execute_query(&db_path, query.as_str(), doc, headers, value.line_number()).await;

match query_response {
Ok(result) => result_to_value(Ok(result), kind, doc, &value, super::sql::STATUS_OK),
Expand Down Expand Up @@ -181,12 +177,13 @@ fn resolve_param(
.map(|v| Box::new(v) as Box<dyn rusqlite::ToSql>)
}

#[derive(Debug)]
#[derive(Debug, PartialEq)]
enum State {
OutsideParam,
InsideParam,
InsideStringLiteral,
InsideEscapeSequence(usize),
ConsumeEscapedChar,
StartTypeHint,
InsideTypeHint,
PushParam,
Expand Down Expand Up @@ -226,9 +223,16 @@ fn extract_named_parameters(
if c == '\\' {
state = State::InsideEscapeSequence(escape_count + 1);
} else {
state = State::InsideStringLiteral;
state = if escape_count % 2 == 0 {
State::InsideStringLiteral
} else {
State::ConsumeEscapedChar
};
}
}
State::ConsumeEscapedChar => {
state = State::InsideStringLiteral;
}
State::StartTypeHint => {
if c == ':' {
state = State::InsideTypeHint;
Expand Down Expand Up @@ -274,24 +278,23 @@ fn extract_named_parameters(
}

// Handle the last param if there was no trailing comma or space
if let State::PushParam = state {
if !param_name.is_empty() {
let param_value = resolve_param(&param_name, &param_type, doc, &headers, line_number)?;
params.push(Box::new(param_value) as Box<dyn rusqlite::ToSql>);
}
if state.eq(&State::PushParam) && !param_name.is_empty() {
let param_value = resolve_param(&param_name, &param_type, doc, &headers, line_number)?;
params.push(Box::new(param_value) as Box<dyn rusqlite::ToSql>);
}

Ok(params)
}

async fn execute_query(
database_path: &str,
database_path: &camino::Utf8PathBuf,
query: &str,
doc: &ftd::interpreter::TDoc<'_>,
headers: ftd::ast::HeaderValues,
line_number: usize,
) -> ftd::interpreter::Result<Vec<Vec<serde_json::Value>>> {
let doc_name = doc.name;

let conn = match rusqlite::Connection::open_with_flags(
database_path,
rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE,
Expand Down

0 comments on commit 45278e6

Please sign in to comment.