Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add execute sql boiler impl #49

Merged
merged 4 commits into from
Jul 25, 2023
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
2 changes: 1 addition & 1 deletion Cargo.lock

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

5 changes: 3 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ edition = "2021"
[dependencies]
anyhow = "1.0"
bindle = { git = "https://github.com/fermyon/bindle", tag = "v0.8.2", default-features = false, features = [
"client",
"client",
] }
chrono = "0.4"
clap = { version = "3.2.24", features = ["derive", "env"] }
cloud = { path = "crates/cloud" }
cloud-openapi = { git = "https://github.com/fermyon/cloud-openapi", rev = "dbf4657ef4e70433aea17210a539202443e2ce96" }
cloud-openapi = { workspace = true }
dirs = "5.0"
dialoguer = "0.10"
tokio = { version = "1.23", features = ["full"] }
Expand Down Expand Up @@ -48,6 +48,7 @@ openssl = { version = "0.10" }

[workspace.dependencies]
tracing = { version = "0.1", features = ["log"] }
cloud-openapi = { git = "https://github.com/fermyon/cloud-openapi", rev = "c37c0f28c06a206ebe05a811c2b886290a5bab40" }

[build-dependencies]
vergen = { version = "^8.2.1", default-features = false, features = [
Expand Down
4 changes: 2 additions & 2 deletions crates/cloud/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ edition = { workspace = true }

[dependencies]
anyhow = "1.0"
cloud-openapi = { git = "https://github.com/fermyon/cloud-openapi", rev = "dbf4657ef4e70433aea17210a539202443e2ce96" }
cloud-openapi = { workspace = true }
mime_guess = { version = "2.0" }
reqwest = { version = "0.11", features = ["stream"] }
semver = "1.0"
serde = {version = "1.0", features = ["derive"]}
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = { version = "1.17", features = ["full"] }
tokio-util = { version = "0.7.3", features = ["codec"] }
Expand Down
26 changes: 21 additions & 5 deletions crates/cloud/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ use cloud_openapi::{
key_value_pairs_api::api_key_value_pairs_post,
revisions_api::{api_revisions_get, api_revisions_post},
sql_databases_api::{
api_sql_databases_delete, api_sql_databases_get, api_sql_databases_post,
api_sql_databases_create_post, api_sql_databases_delete,
api_sql_databases_execute_post, api_sql_databases_get,
},
variable_pairs_api::{
api_variable_pairs_delete, api_variable_pairs_get, api_variable_pairs_post,
Expand All @@ -24,9 +25,9 @@ use cloud_openapi::{
AppItemPage, ChannelItem, ChannelItemPage, ChannelRevisionSelectionStrategy,
CreateAppCommand, CreateChannelCommand, CreateDeviceCodeCommand, CreateKeyValuePairCommand,
CreateSqlDatabaseCommand, CreateVariablePairCommand, Database, DeleteSqlDatabaseCommand,
DeleteVariablePairCommand, DeviceCodeItem, EnvironmentVariableItem, GetChannelLogsVm,
GetSqlDatabasesQuery, GetVariablesQuery, RefreshTokenCommand, RegisterRevisionCommand,
RevisionItemPage, TokenInfo,
DeleteVariablePairCommand, DeviceCodeItem, EnvironmentVariableItem,
ExecuteSqlStatementCommand, GetChannelLogsVm, GetSqlDatabasesQuery, GetVariablesQuery,
RefreshTokenCommand, RegisterRevisionCommand, RevisionItemPage, TokenInfo,
},
};
use reqwest::header;
Expand Down Expand Up @@ -386,7 +387,7 @@ impl Client {
}

pub async fn create_database(&self, app_id: Option<Uuid>, name: String) -> anyhow::Result<()> {
api_sql_databases_post(
api_sql_databases_create_post(
&self.configuration,
CreateSqlDatabaseCommand {
name,
Expand All @@ -398,6 +399,21 @@ impl Client {
.map_err(format_response_error)
}

pub async fn execute_sql(&self, database: String, statement: String) -> anyhow::Result<()> {
api_sql_databases_execute_post(
&self.configuration,
ExecuteSqlStatementCommand {
database,
statement,
default: false,
},
None,
)
.await
.map_err(format_response_error)?;
Ok(())
}

pub async fn delete_database(&self, name: String) -> anyhow::Result<()> {
api_sql_databases_delete(&self.configuration, DeleteSqlDatabaseCommand { name }, None)
.await
Expand Down
25 changes: 5 additions & 20 deletions src/commands/deploy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@ use std::{
use url::Url;
use uuid::Uuid;

use crate::commands::variables::{get_variables, set_variables, Variable};
use crate::commands::{
get_app_id_cloud,
variables::{get_variables, set_variables, Variable},
};

use crate::{
commands::login::{LoginCommand, LoginConnection},
Expand Down Expand Up @@ -183,7 +186,7 @@ impl DeployCommand {
// Create or update app
// TODO: this process involves many calls to Cloud. Should be able to update the channel
// via only `add_revision` if bindle naming schema is updated so bindles can be deterministically ordered by Cloud.
let channel_id = match self.get_app_id_cloud(&client, name.clone()).await {
let channel_id = match get_app_id_cloud(&client, &name).await {
Ok(app_id) => {
if uses_default_db(&cfg) {
create_default_database_if_does_not_exist(&name, app_id, &client).await?;
Expand Down Expand Up @@ -396,15 +399,6 @@ impl DeployCommand {
Err(anyhow!("The application requires values for the following variable(s) which have not been set: {list_text}. Use the --variable flag to provide values."))
}

async fn get_app_id_cloud(&self, cloud_client: &CloudClient, name: String) -> Result<Uuid> {
let apps_vm = CloudClient::list_apps(cloud_client).await?;
let app = apps_vm.items.iter().find(|&x| x.name == name.clone());
match app {
Some(a) => Ok(a.id),
None => bail!("No app with name: {}", name),
}
}

async fn try_get_app_id_cloud(
&self,
cloud_client: &CloudClient,
Expand Down Expand Up @@ -845,15 +839,6 @@ pub async fn login_connection(deployment_env_id: Option<&str>) -> Result<LoginCo
Ok(login_connection)
}

pub async fn get_app_id_cloud(cloud_client: &CloudClient, name: &str) -> Result<Uuid> {
let apps_vm = CloudClient::list_apps(cloud_client).await?;
let app = apps_vm.items.iter().find(|&x| x.name == name);
match app {
Some(a) => Ok(a.id),
None => bail!("No app with name: {}", name),
}
}

// TODO: unify with login
pub fn config_file_path(deployment_env_id: Option<&str>) -> Result<PathBuf> {
let root = dirs::config_dir()
Expand Down
12 changes: 11 additions & 1 deletion src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ pub mod sqlite;
pub mod variables;

use crate::commands::deploy::login_connection;
use anyhow::Result;
use anyhow::{bail, Result};
use cloud::client::{Client as CloudClient, ConnectionConfig};
use uuid::Uuid;

pub(crate) async fn create_cloud_client(deployment_env_id: Option<&str>) -> Result<CloudClient> {
let login_connection = login_connection(deployment_env_id).await?;
Expand All @@ -16,3 +17,12 @@ pub(crate) async fn create_cloud_client(deployment_env_id: Option<&str>) -> Resu
};
Ok(CloudClient::new(connection_config))
}

pub(crate) async fn get_app_id_cloud(cloud_client: &CloudClient, name: &str) -> Result<Uuid> {
let apps_vm = CloudClient::list_apps(cloud_client).await?;
let app = apps_vm.items.iter().find(|&x| x.name == name);
match app {
Some(a) => Ok(a.id),
None => bail!("No app with name: {}", name),
}
}
35 changes: 35 additions & 0 deletions src/commands/sqlite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ use crate::opts::*;
pub enum SqliteCommand {
/// Delete a SQLite database
Delete(DeleteCommand),
/// Execute SQL against a SQLite database
Execute(ExecuteCommand),
/// List all SQLite databases of a user
List(ListCommand),
}
Expand All @@ -30,6 +32,27 @@ pub struct DeleteCommand {
common: CommonArgs,
}

#[derive(Parser, Debug)]
pub struct ExecuteCommand {
/// Name of database to execute against
#[clap(value_parser = clap::builder::ValueParser::new(disallow_empty))]
name: String,

///Statement to execute
#[clap(value_parser = clap::builder::ValueParser::new(disallow_empty))]
statement: String,

#[clap(flatten)]
common: CommonArgs,
}

fn disallow_empty(statement: &str) -> anyhow::Result<String> {
if statement.trim().is_empty() {
anyhow::bail!("cannot be empty");
}
return Ok(statement.trim().to_owned());
}

#[derive(Parser, Debug)]
pub struct ListCommand {
#[clap(flatten)]
Expand Down Expand Up @@ -67,6 +90,18 @@ impl SqliteCommand {
println!("Database \"{}\" deleted", cmd.name);
}
}
Self::Execute(cmd) => {
let client = create_cloud_client(cmd.common.deployment_env_id.as_deref()).await?;
let list = CloudClient::get_databases(&client, None)
.await
.context("Problem fetching databases")?;
if !list.iter().any(|d| d.name == cmd.name) {
anyhow::bail!("No database found with name \"{}\"", cmd.name);
}
CloudClient::execute_sql(&client, cmd.name, cmd.statement)
.await
.context("Problem executing SQL")?;
}
Self::List(cmd) => {
let client = create_cloud_client(cmd.common.deployment_env_id.as_deref()).await?;
let list = CloudClient::get_databases(&client, None)
Expand Down
2 changes: 1 addition & 1 deletion src/commands/variables.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use uuid::Uuid;

use crate::opts::*;

use crate::commands::{create_cloud_client, deploy::get_app_id_cloud};
use crate::commands::{create_cloud_client, get_app_id_cloud};

#[derive(Deserialize)]
pub(crate) struct Variable {
Expand Down
Loading