Skip to content

Commit

Permalink
feat: add update mechanism
Browse files Browse the repository at this point in the history
  • Loading branch information
invm committed Jan 9, 2024
1 parent f000b90 commit 487db53
Show file tree
Hide file tree
Showing 17 changed files with 108 additions and 151 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"solid-form-handler": "^1.2.0",
"solid-js": "^1.7.7",
"split.js": "^1.6.5",
"sql-bricks": "^3.0.1",
"sql-formatter": "^12.2.3",
"tauri-plugin-store-api": "github:tauri-apps/tauri-plugin-store#v1",
"tauri-plugin-window-state-api": "github:tauri-apps/tauri-plugin-window-state#v1",
Expand Down
38 changes: 11 additions & 27 deletions pnpm-lock.yaml

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

8 changes: 1 addition & 7 deletions src-tauri/src/database/connections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,6 @@ pub struct InitiatedConnection {
pub schema: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PreparedStatement {
pub statement: String,
pub params: Vec<String>,
}

impl ConnectionConfig {
pub fn new(
dialect: Dialect,
Expand Down Expand Up @@ -396,7 +390,7 @@ impl InitiatedConnection {
}
}

pub async fn execute_tx(&self, queries: Vec<PreparedStatement>) -> Result<(), Error> {
pub async fn execute_tx(&self, queries: Vec<&str>) -> Result<(), Error> {
match &self.pool {
ConnectionPool::Mysql(pool) => engine::mysql::query::execute_tx(pool, queries),
ConnectionPool::Postgresql(pool) => {
Expand Down
7 changes: 3 additions & 4 deletions src-tauri/src/database/engine/mysql/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use mysql::{from_row, Pool, PooledConn, Row, TxOpts};
use serde_json::Value;
use tracing::info;

use crate::database::connections::{PreparedStatement, ResultSet, TableMetadata};
use crate::database::connections::{ResultSet, TableMetadata};
use crate::utils::error::Error;

use super::utils::row_to_object;
Expand Down Expand Up @@ -56,14 +56,13 @@ pub fn execute_query(pool: &Pool, query: &str) -> Result<ResultSet> {
});
}

pub fn execute_tx(pool: &Pool, queries: Vec<PreparedStatement>) -> Result<(), Error> {
pub fn execute_tx(pool: &Pool, queries: Vec<&str>) -> Result<(), Error> {
match pool
.start_transaction(TxOpts::default())
.and_then(|mut tx| {
let mut error = None;
for q in queries {
info!(?q.statement, ?q.params, "Executing query");
let success = tx.exec_iter(q.statement, q.params);
let success = tx.query_iter(q);
if success.is_err() {
error = Some(success.err().unwrap());
break;
Expand Down
31 changes: 6 additions & 25 deletions src-tauri/src/database/engine/postgresql/query.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use anyhow::Result;
use deadpool_postgres::{GenericClient, Pool};
use deadpool_postgres::Pool;
use futures::{pin_mut, TryStreamExt};
use serde_json::Value;
use tracing::debug;

use crate::{
database::connections::{PreparedStatement, ResultSet, TableMetadata},
database::connections::{ResultSet, TableMetadata},
utils::error::Error,
};

Expand Down Expand Up @@ -48,32 +48,13 @@ pub async fn execute_query(pool: &Pool, query: &str) -> Result<ResultSet> {
Ok(set)
}

pub async fn execute_tx(pool: &Pool, queries: Vec<PreparedStatement>) -> Result<(), Error> {
pub async fn execute_tx(pool: &Pool, queries: Vec<&str>) -> Result<(), Error> {
let mut conn = pool.get().await?;
let tx = conn.transaction().await?;
for q in queries {
debug!(?q.statement, ?q.params, "Executing query");
// replace each occurence of ? in string with $1, $2, $3, etc.
let mut i = 0;
let query = q
.statement
.clone()
.split("")
.enumerate()
.map(|(_, c)| {
if c == "?" {
i += 1;
format!("${}", i)
} else {
c.to_string()
}
})
.collect::<Vec<String>>()
.join("");

debug!(?query, "Executing query");

match tx.execute_raw(&query, &q.params).await {
debug!(?q, "Executing query");
let params: Vec<String> = vec![];
match tx.execute_raw(q, &params).await {
Ok(..) => {}
Err(e) => {
tx.rollback().await?;
Expand Down
10 changes: 7 additions & 3 deletions src-tauri/src/database/engine/postgresql/tables.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,16 @@ pub async fn get_constraints(
) -> Result<Vec<Value>> {
let schema = conn.get_schema();
let query = format!(
"SELECT CONSTRAINT_NAME, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, ORDINAL_POSITION
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = '{}'",
"SELECT c.column_name, c.table_name, tc.constraint_name, c.table_schema, c.ordinal_position
FROM information_schema.table_constraints tc
JOIN information_schema.constraint_column_usage AS ccu USING (constraint_schema, constraint_name)
JOIN information_schema.columns AS c ON c.table_schema = tc.constraint_schema
AND tc.table_name = c.table_name AND ccu.column_name = c.column_name
WHERE constraint_type = 'PRIMARY KEY' and c.table_schema = '{}'",
schema
);
let query = match table {
Some(table) => format!("{} AND TABLE_NAME = '{}'", query, table),
Some(table) => format!("{} AND c.table_name = '{}'", query, table),
None => format!("{};", query),
};
Ok(raw_query(pool.clone(), &query).await?)
Expand Down
7 changes: 3 additions & 4 deletions src-tauri/src/handlers/queries.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use std::fs::read_to_string;

use crate::{
database::connections::PreparedStatement,
queues::query::{QueryTask, QueryTaskEnqueueResult, QueryTaskStatus, TableQuery},
queues::query::{QueryTask, QueryTaskEnqueueResult, QueryTaskStatus},
state::{AsyncState, ServiceAccess},
utils::{
self,
Expand All @@ -26,7 +25,7 @@ pub async fn enqueue_query(
tab_idx: usize,
sql: &str,
auto_limit: bool,
table: Option<TableQuery>,
table: Option<String>,
) -> CommandResult<QueryTaskEnqueueResult> {
info!(sql, conn_id, tab_idx, "enqueue_query");
let conn = app_handle.acquire_connection(conn_id.clone());
Expand Down Expand Up @@ -103,7 +102,7 @@ pub async fn get_views(app_handle: AppHandle, conn_id: String) -> CommandResult<
pub async fn execute_tx(
app_handle: AppHandle,
conn_id: String,
queries: Vec<PreparedStatement>,
queries: Vec<&str>,
) -> CommandResult<()> {
let connection = app_handle.acquire_connection(conn_id);
connection.execute_tx(queries).await?;
Expand Down
16 changes: 5 additions & 11 deletions src-tauri/src/queues/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,6 @@ impl Default for QueryTaskStatus {
}
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableQuery {
pub table: String,
pub with_constraints: bool,
}

#[derive(Debug, Clone)]
pub struct QueryTask {
pub conn: InitiatedConnection,
Expand All @@ -47,7 +41,7 @@ pub struct QueryTask {
pub status: QueryTaskStatus,
pub tab_idx: usize,
pub query_idx: usize,
pub table: Option<TableQuery>,
pub table: Option<String>,
}

impl QueryTask {
Expand All @@ -57,7 +51,7 @@ impl QueryTask {
query_id: String,
tab_idx: usize,
query_idx: usize,
table: Option<TableQuery>,
table: Option<String>,
) -> Self {
QueryTask {
conn,
Expand Down Expand Up @@ -104,10 +98,10 @@ pub async fn async_process_model(
match task.conn.execute_query(&task.query).await {
Ok(mut result_set) => {
if let Some(table) = task.table {
let constraints = task.conn.get_constraints(&table.table).await?;
let columns = task.conn.get_columns(Some(&table.table)).await?;
let constraints = task.conn.get_constraints(&table).await?;
let columns = task.conn.get_columns(Some(&table)).await?;
result_set.table = TableMetadata {
table: table.table,
table,
constraints: Some(constraints),
columns: Some(columns),
}
Expand Down
2 changes: 1 addition & 1 deletion src-tauri/src/utils/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pub enum Error {
General(#[from] anyhow::Error),
#[error("Query results expired, please re-run the query.")]
QueryExpired,
#[error("Transaction failed: {0}")]
#[error("{0}")]
TxError(String),
}

Expand Down
Loading

0 comments on commit 487db53

Please sign in to comment.