Skip to content
Open
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
1 change: 1 addition & 0 deletions src-tauri/src/ai_schema_context_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ fn column(name: &str, data_type: &str, is_pk: bool, is_nullable: bool) -> TableC
is_pk,
is_nullable,
is_auto_increment: false,
is_generated: false,
default_value: None,
character_maximum_length: None,
}
Expand Down
3 changes: 3 additions & 0 deletions src-tauri/src/drivers/mysql/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,7 @@ pub async fn get_columns(
is_pk: key == "PRI",
is_nullable: null_str == "YES",
is_auto_increment,
is_generated: false,
default_value,
character_maximum_length,
}
Expand Down Expand Up @@ -466,6 +467,7 @@ pub async fn get_all_columns_batch(
is_pk: key == "PRI",
is_nullable: null_str == "YES",
is_auto_increment,
is_generated: false,
default_value,
character_maximum_length,
};
Expand Down Expand Up @@ -1141,6 +1143,7 @@ pub async fn get_view_columns(
is_pk: key == "PRI",
is_nullable: null_str == "YES",
is_auto_increment,
is_generated: false,
default_value,
character_maximum_length,
}
Expand Down
4 changes: 4 additions & 0 deletions src-tauri/src/drivers/postgres/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ pub async fn get_columns(
is_pk,
is_nullable: null_str == "YES",
is_auto_increment: is_auto,
is_generated: false,
default_value,
character_maximum_length,
}
Expand Down Expand Up @@ -327,6 +328,7 @@ pub async fn get_all_columns_batch(
is_pk,
is_nullable: null_str == "YES",
is_auto_increment: is_auto,
is_generated: false,
default_value,
character_maximum_length,
};
Expand Down Expand Up @@ -1325,6 +1327,7 @@ pub async fn get_view_columns(
is_pk,
is_nullable: null_str == "YES",
is_auto_increment: is_auto,
is_generated: false,
default_value,
character_maximum_length,
}
Expand Down Expand Up @@ -1390,6 +1393,7 @@ pub async fn get_materialized_view_columns(
is_pk: false,
is_nullable: !r.try_get::<_, bool>("not_null").unwrap_or(false),
is_auto_increment: false,
is_generated: false,
default_value: None,
character_maximum_length: None,
})
Expand Down
109 changes: 48 additions & 61 deletions src-tauri/src/drivers/sqlite/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,35 @@ fn escape_identifier(name: &str) -> String {
name.replace('"', "\"\"")
}

fn sqlite_column_from_row(row: &sqlx::sqlite::SqliteRow) -> TableColumn {
let pk: i32 = row.try_get("pk").unwrap_or(0);
let notnull: i32 = row.try_get("notnull").unwrap_or(0);
let dflt_value: Option<String> = row.try_get("dflt_value").ok();
let hidden: i32 = row.try_get("hidden").unwrap_or(0);

TableColumn {
name: row.try_get("name").unwrap_or_default(),
data_type: row.try_get("type").unwrap_or_default(),
is_pk: pk > 0,
is_nullable: notnull == 0,
is_auto_increment: false,
is_generated: hidden == 2 || hidden == 3,
default_value: dflt_value,
character_maximum_length: None,
}
}

async fn is_generated_column(
params: &ConnectionParams,
table: &str,
column: &str,
) -> Result<bool, String> {
Ok(get_columns(params, table)
.await?
.iter()
.any(|col| col.name == column && col.is_generated))
}

pub async fn get_schemas(_params: &ConnectionParams) -> Result<Vec<String>, String> {
Ok(vec![])
}
Expand Down Expand Up @@ -61,37 +90,14 @@ pub async fn get_columns(
) -> Result<Vec<TableColumn>, String> {
let pool = get_sqlite_pool(params).await?;

// PRAGMA table_info doesn't explicitly say "AUTO_INCREMENT"
// But INTEGER PRIMARY KEY is implicitly so in sqlite.
// Also if 'pk' > 0 and type is INTEGER.
let query = format!("PRAGMA table_info('{}')", table_name);
let query = format!("PRAGMA table_xinfo('{}')", table_name);

let rows = sqlx::query(&query)
.fetch_all(&pool)
.await
.map_err(|e| e.to_string())?;

Ok(rows
.iter()
.map(|r| {
let pk: i32 = r.try_get("pk").unwrap_or(0);
let notnull: i32 = r.try_get("notnull").unwrap_or(0);
let dtype: String = r.try_get("type").unwrap_or_default();
let dflt_value: Option<String> = r.try_get("dflt_value").ok();

let _is_auto = pk > 0 && dtype.to_uppercase().contains("INT");

TableColumn {
name: r.try_get("name").unwrap_or_default(),
data_type: r.try_get("type").unwrap_or_default(),
is_pk: pk > 0,
is_nullable: notnull == 0,
is_auto_increment: false,
default_value: dflt_value,
character_maximum_length: None,
}
})
.collect())
Ok(rows.iter().map(sqlite_column_from_row).collect())
}

pub async fn get_routines(_params: &ConnectionParams) -> Result<Vec<RoutineInfo>, String> {
Expand Down Expand Up @@ -157,29 +163,13 @@ pub async fn get_all_columns_batch(
let mut result: HashMap<String, Vec<TableColumn>> = HashMap::new();

for table_name in table_names {
let query = format!("PRAGMA table_info('{}')", table_name);
let query = format!("PRAGMA table_xinfo('{}')", table_name);
let rows = sqlx::query(&query)
.fetch_all(&pool)
.await
.map_err(|e| e.to_string())?;

let columns: Vec<TableColumn> = rows
.iter()
.map(|r| {
let pk: i32 = r.try_get("pk").unwrap_or(0);
let notnull: i32 = r.try_get("notnull").unwrap_or(0);
let dflt_value: Option<String> = r.try_get("dflt_value").ok();
TableColumn {
name: r.try_get("name").unwrap_or_default(),
data_type: r.try_get("type").unwrap_or_default(),
is_pk: pk > 0,
is_nullable: notnull == 0,
is_auto_increment: false, // SQLite doesn't expose this via table_info easily, typically AUTOINCREMENT on INTEGER PRIMARY KEY
default_value: dflt_value,
character_maximum_length: None,
}
})
.collect();
let columns: Vec<TableColumn> = rows.iter().map(sqlite_column_from_row).collect();

result.insert(table_name.clone(), columns);
}
Expand Down Expand Up @@ -495,6 +485,10 @@ pub async fn update_record(
new_val: serde_json::Value,
max_blob_size: u64,
) -> Result<u64, String> {
if is_generated_column(params, table, col_name).await? {
return Err(format!("Cannot update generated column: {col_name}"));
}

let pool = get_sqlite_pool(params).await?;

let mut qb = sqlx::QueryBuilder::new(format!(
Expand Down Expand Up @@ -547,11 +541,20 @@ pub async fn insert_record(
max_blob_size: u64,
) -> Result<u64, String> {
let pool = get_sqlite_pool(params).await?;
let generated_columns: std::collections::HashSet<String> = get_columns(params, table)
.await?
.into_iter()
.filter(|col| col.is_generated)
.map(|col| col.name)
.collect();

let mut cols = Vec::new();
let mut vals = Vec::new();

for (k, v) in data {
if generated_columns.contains(&k) {
return Err(format!("Cannot insert into generated column: {k}"));
}
cols.push(format!("\"{}\"", k));
vals.push(v);
}
Expand Down Expand Up @@ -847,30 +850,14 @@ pub async fn get_view_columns(
) -> Result<Vec<TableColumn>, String> {
let pool = get_sqlite_pool(params).await?;

let query = format!("PRAGMA table_info('{}')", view_name);
let query = format!("PRAGMA table_xinfo('{}')", view_name);

let rows = sqlx::query(&query)
.fetch_all(&pool)
.await
.map_err(|e| e.to_string())?;

Ok(rows
.iter()
.map(|r| {
let pk: i32 = r.try_get("pk").unwrap_or(0);
let notnull: i32 = r.try_get("notnull").unwrap_or(0);
let dflt_value: Option<String> = r.try_get("dflt_value").ok();
TableColumn {
name: r.try_get("name").unwrap_or_default(),
data_type: r.try_get("type").unwrap_or_default(),
is_pk: pk > 0,
is_nullable: notnull == 0,
is_auto_increment: false,
default_value: dflt_value,
character_maximum_length: None,
}
})
.collect())
Ok(rows.iter().map(sqlite_column_from_row).collect())
}

pub async fn get_triggers(params: &ConnectionParams) -> Result<Vec<TriggerInfo>, String> {
Expand Down
50 changes: 48 additions & 2 deletions src-tauri/src/drivers/sqlite/tests.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::sqlite_push_pk_where;
use super::{
alter_view, create_view, drop_view, get_indexes, get_view_columns, get_view_definition,
get_views, parse_sqlite_index_columns,
alter_view, create_view, drop_view, get_all_columns_batch, get_columns, get_indexes,
get_view_columns, get_view_definition, get_views, parse_sqlite_index_columns,
};
use crate::models::{ConnectionParams, DatabaseSelection};
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
Expand Down Expand Up @@ -186,6 +186,52 @@ async fn test_view_lifecycle() {
crate::pool_manager::close_pool(&params).await;
}

#[tokio::test]
async fn test_get_columns_includes_generated_table_columns() {
let (params, _file) = setup_test_db().await;

let path = params.database.primary().to_string();
let options = SqliteConnectOptions::new().filename(&path);
let pool = SqlitePoolOptions::new()
.connect_with(options)
.await
.expect("connect to test DB");

sqlx::query(
"CREATE TABLE generated_dates (
udate INTEGER,
display_date TEXT GENERATED ALWAYS AS (date(udate, 'unixepoch', '+12:00')) STORED
)",
)
.execute(&pool)
.await
.expect("create generated column table");

pool.close().await;

let cols = get_columns(&params, "generated_dates")
.await
.expect("get table columns");

let generated = cols
.iter()
.find(|col| col.name == "display_date")
.expect("generated column should be visible through table metadata");
assert_eq!(generated.data_type, "TEXT");
assert!(generated.is_generated);

let batch = get_all_columns_batch(&params, &["generated_dates".to_string()])
.await
.expect("get batch columns");
let batch_generated = batch["generated_dates"]
.iter()
.find(|col| col.name == "display_date")
.expect("generated column should be visible through batch metadata");
assert!(batch_generated.is_generated);

crate::pool_manager::close_pool(&params).await;
}

mod sqlite_push_pk_where_tests {
use super::*;
use std::collections::HashMap;
Expand Down
2 changes: 2 additions & 0 deletions src-tauri/src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,8 @@ pub struct TableColumn {
pub is_pk: bool,
pub is_nullable: bool,
pub is_auto_increment: bool,
#[serde(default)]
pub is_generated: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub default_value: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
Expand Down
21 changes: 15 additions & 6 deletions src/components/modals/NewRowModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ interface TableColumn {
is_pk: boolean;
is_nullable: boolean;
is_auto_increment: boolean;
is_generated?: boolean;
}

interface NewRowModalProps {
Expand Down Expand Up @@ -187,6 +188,10 @@ export const NewRowModal = ({
const dataToSend: Record<string, unknown> = {};

for (const col of columns) {
if (col.is_generated) {
continue;
}

const rawVal = formData[col.name];

// Skip if auto-increment and empty (let database generate)
Expand Down Expand Up @@ -228,6 +233,7 @@ export const NewRowModal = ({
// First plain text field, skipping auto-increment/FK/geometry inputs.
const autoFocusColumn = columns.find(
(c) =>
!c.is_generated &&
!c.is_auto_increment &&
!foreignKeys.some((fk) => fk.column_name === c.name) &&
!isGeometricType(c.data_type),
Expand Down Expand Up @@ -270,16 +276,17 @@ export const NewRowModal = ({
{t("newRow.primaryKey")}
</span>
)}
{col.is_auto_increment && (
{(col.is_auto_increment || col.is_generated) && (
<span className="text-accent-info text-[10px]">
{t("newRow.auto")}
{col.is_generated ? t("newRow.autoGenerated") : t("newRow.auto")}
</span>
)}
</label>

{foreignKeys.find((fk) => fk.column_name === col.name) ? (
<div className="relative">
<select
disabled={col.is_generated}
value={String(formData[col.name] ?? "")}
onChange={(e) =>
handleInputChange(col.name, e.target.value)
Expand Down Expand Up @@ -327,34 +334,36 @@ export const NewRowModal = ({
dataType={col.data_type}
onChange={(val) => handleInputChange(col.name, val)}
placeholder={
col.is_auto_increment
col.is_auto_increment || col.is_generated
? t("newRow.autoGenerated")
: col.is_nullable
? "NULL"
: t("newRow.required")
}
disabled={col.is_generated}
className={`
w-full bg-elevated border rounded px-3 py-2 text-primary focus:outline-none focus:border-focus
${col.is_auto_increment ? "border-default text-secondary placeholder:text-muted" : "border-strong"}
${col.is_auto_increment || col.is_generated ? "border-default text-secondary placeholder:text-muted" : "border-strong"}
`}
/>
) : (
<input
disabled={col.is_generated}
value={String(formData[col.name] ?? "")}
onChange={(e) =>
handleInputChange(col.name, e.target.value)
}
autoFocus={col.name === autoFocusColumn}
placeholder={
col.is_auto_increment
col.is_auto_increment || col.is_generated
? t("newRow.autoGenerated")
: col.is_nullable
? "NULL"
: t("newRow.required")
}
className={`
w-full bg-elevated border rounded px-3 py-2 text-primary focus:outline-none focus:border-focus
${col.is_auto_increment ? "border-default text-secondary placeholder:text-muted" : "border-strong"}
${col.is_auto_increment || col.is_generated ? "border-default text-secondary placeholder:text-muted" : "border-strong"}
`}
/>
)}
Expand Down
Loading