refactor: convert to bun-workspaces monorepo (desktop/ + www/)

- Move the Tauri app (React frontend + Rust backend) into desktop/ via
  git mv — configs unchanged (relative paths: tauri.conf.json, vite.config.ts)
- Root package.json becomes a private bun workspace container with
  orchestration scripts; desktop package renamed gridline-desktop
- Scaffold www/ with Astro 7 + Tailwind v4 (hand-wired vite plugin,
  static output, ready for Dokploy)
- Update release.yml for the new layout: projectPath: desktop,
  desktop/src-tauri resource paths, rust-cache workspace path
- Update README + AGENTS.md structure trees and dev commands
- Verified: vitest (1074), cargo test (354), desktop build, tauri dev
  (window launches), tauri build (dmg + app bundles), Astro build
This commit is contained in:
2026-08-16 19:31:53 +08:00
parent d752642b4d
commit 6854d889c5
400 changed files with 857 additions and 149 deletions
+245
View File
@@ -0,0 +1,245 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BackupOptions {
pub format: String, // "plain" | "custom" | "tar" | "directory"
pub file_path: String,
pub schema: Option<String>,
pub tables: Option<Vec<String>>,
pub no_owner: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RestoreOptions {
pub format: String,
pub file_path: String,
pub clean: bool,
pub schema: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SyncOptions {
pub source_connection_id: String,
pub target_connection_id: String,
pub schema: Option<String>,
pub tables: Option<Vec<String>>,
#[serde(default = "default_sync_db_type")]
pub db_type: String,
}
fn default_sync_db_type() -> String {
"postgresql".into()
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PgToolStatus {
pub pg_dump_found: bool,
pub pg_restore_found: bool,
pub pg_dump_version: Option<String>,
pub pg_restore_version: Option<String>,
pub pg_dump_source: Option<String>, // "system" | "bundled" | None
pub pg_restore_source: Option<String>,
}
/// Resolved on-disk paths for the three client tools (system-first, bundled-fallback).
#[derive(Debug, Clone)]
pub struct PgToolPaths {
pub pg_dump: String,
pub pg_restore: String,
pub psql: String,
}
/// Connection params for a MySQL server (decoupled from store/keychain so the
/// dump/restore/sync core stays headless-testable). Mirrors `PgConnParams`.
#[derive(Debug, Clone)]
pub struct MySqlConnParams {
pub host: String,
pub port: i64,
pub username: String,
pub database: String,
pub password: String,
}
impl MySqlConnParams {
pub fn new(host: String, port: i64, username: String, database: String, password: String) -> Self {
Self { host, port, username, database, password }
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MySqlBackupOptions {
pub database: String,
pub file_path: String,
pub single_transaction: bool,
pub no_data: bool,
pub routines: bool,
pub triggers: bool,
pub events: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MySqlRestoreOptions {
pub database: String,
pub file_path: String,
pub clean: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SqliteBackupOptions {
pub file_path: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SqliteRestoreOptions {
pub file_path: String,
pub clean: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MySqlToolStatus {
pub mysqldump_found: bool,
pub mysql_found: bool,
pub mysqldump_version: Option<String>,
pub mysql_version: Option<String>,
pub mysqldump_source: Option<String>,
pub mysql_source: Option<String>,
}
#[derive(Debug, Clone)]
pub struct MySqlToolPaths {
pub mysqldump: String,
pub mysql: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackupJob {
pub id: String,
pub connection_id: String,
pub r#type: String, // "dump" | "restore" | "sync"
pub format: Option<String>,
pub file_path: Option<String>,
pub source_connection_id: Option<String>,
pub status: String,
pub error_message: Option<String>,
pub size_bytes: Option<i64>,
pub started_at: String,
pub completed_at: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct BackupProgressEvent {
pub job_id: String,
pub status: String,
pub progress: Option<f64>,
pub output_line: Option<String>,
pub error: Option<String>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn backup_options_serialization() {
let opts = BackupOptions {
format: "plain".into(),
file_path: "/tmp/dump.sql".into(),
schema: Some("public".into()),
tables: None,
no_owner: true,
};
let json = serde_json::to_string(&opts).unwrap();
assert!(json.contains("plain"));
assert!(json.contains("noOwner"));
}
#[test]
fn backup_job_serialization() {
let job = BackupJob {
id: "job-1".into(),
connection_id: "conn-1".into(),
r#type: "dump".into(),
format: Some("plain".into()),
file_path: Some("/tmp/dump.sql".into()),
source_connection_id: None,
status: "completed".into(),
error_message: None,
size_bytes: Some(1024),
started_at: "2025-07-28T10:00:00Z".into(),
completed_at: Some("2025-07-28T10:01:00Z".into()),
};
let json = serde_json::to_string(&job).unwrap();
assert!(json.contains("dump"));
assert!(json.contains("completed"));
}
#[test]
fn pg_tool_status_reports_source() {
let s = PgToolStatus { pg_dump_found: true, pg_restore_found: true,
pg_dump_version: Some("pg_dump 16".into()), pg_restore_version: Some("pg_restore 16".into()),
pg_dump_source: Some("system".into()), pg_restore_source: Some("bundled".into()) };
let json = serde_json::to_string(&s).unwrap();
assert!(json.contains("\"pg_dump_source\":\"system\""));
assert!(json.contains("\"pg_restore_source\":\"bundled\""));
}
#[test]
fn mysql_backup_options_serialize_camel_case() {
let opts = MySqlBackupOptions {
database: "shop".into(),
file_path: "/tmp/dump.sql".into(),
single_transaction: true,
no_data: false,
routines: true,
triggers: true,
events: false,
};
let json = serde_json::to_string(&opts).unwrap();
assert!(json.contains("\"singleTransaction\":true"));
assert!(json.contains("\"filePath\":\"/tmp/dump.sql\""));
assert!(!json.contains("no_owner"));
}
#[test]
fn sqlite_restore_options_serialize_camel_case() {
let opts = SqliteRestoreOptions { file_path: "/tmp/in.sql".into(), clean: true };
let json = serde_json::to_string(&opts).unwrap();
assert!(json.contains("\"filePath\":\"/tmp/in.sql\""));
assert!(json.contains("\"clean\":true"));
}
#[test]
fn mysql_tool_status_reports_source() {
let s = MySqlToolStatus {
mysqldump_found: true,
mysql_found: true,
mysqldump_version: Some("mariadb-dump 10.6".into()),
mysql_version: Some("mariadb 10.6".into()),
mysqldump_source: Some("bundled".into()),
mysql_source: Some("system".into()),
};
let json = serde_json::to_string(&s).unwrap();
assert!(json.contains("\"mysqldumpSource\":\"bundled\""));
}
#[test]
fn sync_options_carry_db_type() {
let s = SyncOptions {
source_connection_id: "a".into(),
target_connection_id: "b".into(),
schema: None,
tables: None,
db_type: "mysql".into(),
};
let json = serde_json::to_string(&s).unwrap();
assert!(json.contains("\"dbType\":\"mysql\""));
}
}
+211
View File
@@ -0,0 +1,211 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Connection {
pub id: String,
pub name: String,
pub db_type: String,
pub host: String,
pub port: Option<i64>,
pub username: Option<String>,
pub database: Option<String>,
pub folder_id: Option<String>,
pub keychain_ref: Option<String>,
pub environment: Option<String>,
pub favorite: bool,
pub ssh_host: Option<String>,
pub ssh_port: Option<i64>,
pub ssh_user: Option<String>,
pub ssh_auth_method: Option<String>,
pub ssh_private_key_path: Option<String>,
pub ssl_mode: Option<String>,
pub ssl_ca_path: Option<String>,
pub ssl_cert_path: Option<String>,
pub ssl_key_path: Option<String>,
pub tag_ids: Vec<String>,
pub use_keychain: bool,
pub created_at: String,
pub updated_at: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionInput {
pub name: String,
pub db_type: String,
pub host: String,
pub port: Option<i64>,
pub username: Option<String>,
pub folder_id: Option<String>,
pub tag_ids: Vec<String>,
pub password: Option<String>,
pub database: Option<String>,
pub environment: Option<String>,
pub ssh_host: Option<String>,
pub ssh_port: Option<i64>,
pub ssh_user: Option<String>,
pub ssh_auth_method: Option<String>,
pub ssh_private_key_path: Option<String>,
pub ssh_password: Option<String>,
pub ssh_passphrase: Option<String>,
pub ssl_mode: Option<String>,
pub ssl_ca_path: Option<String>,
pub ssl_cert_path: Option<String>,
pub ssl_key_path: Option<String>,
#[serde(default = "default_true")]
pub use_keychain: bool,
}
fn default_true() -> bool {
true
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn connection_input_roundtrip_with_all_fields() {
let input = ConnectionInput {
name: "Test DB".to_string(),
db_type: "PostgreSQL".to_string(),
host: "db.example.com".to_string(),
port: Some(5432),
username: Some("admin".to_string()),
folder_id: Some("folder1".to_string()),
tag_ids: vec!["tag1".to_string(), "tag2".to_string()],
use_keychain: true,
password: Some("secret123".to_string()),
database: Some("mydb".to_string()),
ssh_host: Some("jumphost.example.com".to_string()),
ssh_port: Some(2222),
ssh_user: Some("tunnel".to_string()),
ssh_auth_method: Some("Key".to_string()),
ssh_private_key_path: Some("/path/to/key".to_string()),
ssh_password: Some("ssh-pw".to_string()),
ssh_passphrase: Some("passphrase".to_string()),
ssl_mode: Some("require".to_string()),
ssl_ca_path: Some("/path/to/ca".to_string()),
ssl_cert_path: Some("/path/to/cert".to_string()),
ssl_key_path: Some("/path/to/key".to_string()),
environment: Some("production".to_string()),
};
let json = serde_json::to_string(&input).unwrap();
let deserialized: ConnectionInput = serde_json::from_str(&json).unwrap();
assert_eq!(deserialized.name, "Test DB");
assert_eq!(deserialized.db_type, "PostgreSQL");
assert_eq!(deserialized.host, "db.example.com");
assert_eq!(deserialized.port, Some(5432));
assert_eq!(deserialized.username, Some("admin".to_string()));
assert_eq!(deserialized.folder_id, Some("folder1".to_string()));
assert_eq!(
deserialized.tag_ids,
vec!["tag1".to_string(), "tag2".to_string()]
);
assert_eq!(deserialized.password, Some("secret123".to_string()));
assert_eq!(deserialized.database, Some("mydb".to_string()));
assert_eq!(
deserialized.ssh_host,
Some("jumphost.example.com".to_string())
);
assert_eq!(deserialized.ssh_port, Some(2222));
assert_eq!(deserialized.ssh_user, Some("tunnel".to_string()));
assert_eq!(deserialized.ssh_auth_method, Some("Key".to_string()));
assert_eq!(
deserialized.ssh_private_key_path,
Some("/path/to/key".to_string())
);
assert_eq!(deserialized.ssh_password, Some("ssh-pw".to_string()));
assert_eq!(deserialized.ssh_passphrase, Some("passphrase".to_string()));
assert_eq!(deserialized.ssl_mode, Some("require".to_string()));
assert_eq!(deserialized.ssl_ca_path, Some("/path/to/ca".to_string()));
assert_eq!(
deserialized.ssl_cert_path,
Some("/path/to/cert".to_string())
);
assert_eq!(deserialized.ssl_key_path, Some("/path/to/key".to_string()));
}
#[test]
fn connection_persisted_does_not_include_password() {
let conn = Connection {
id: "test-id".to_string(),
name: "Test".to_string(),
db_type: "PostgreSQL".to_string(),
host: "localhost".to_string(),
port: Some(5432),
username: Some("user".to_string()),
folder_id: Some("folder".to_string()),
keychain_ref: Some("keychain-ref".to_string()),
environment: None,
favorite: false,
tag_ids: vec![],
use_keychain: true,
created_at: "2024-01-01T00:00:00Z".to_string(),
updated_at: "2024-01-01T00:00:00Z".to_string(),
database: Some("mydb".to_string()),
ssh_host: Some("ssh-host".to_string()),
ssh_port: Some(2222),
ssh_user: Some("ssh-user".to_string()),
ssh_auth_method: Some("Key".to_string()),
ssh_private_key_path: Some("/path/to/key".to_string()),
ssl_mode: Some("require".to_string()),
ssl_ca_path: Some("/path/to/ca".to_string()),
ssl_cert_path: Some("/path/to/cert".to_string()),
ssl_key_path: Some("/path/to/key".to_string()),
};
let json = serde_json::to_string(&conn).unwrap();
assert!(
!json.contains("password"),
"Connection JSON should not contain password field"
);
}
#[test]
fn connection_serializes_favorite_field() {
let conn = Connection {
id: "x".into(),
name: "n".into(),
db_type: "postgresql".into(),
host: "h".into(),
port: Some(5432),
username: None,
database: None,
folder_id: None,
keychain_ref: None,
environment: None,
ssh_host: None,
ssh_port: None,
ssh_user: None,
ssh_auth_method: None,
ssh_private_key_path: None,
ssl_mode: None,
ssl_ca_path: None,
ssl_cert_path: None,
ssl_key_path: None,
tag_ids: vec![],
use_keychain: true,
favorite: true,
created_at: "2024-01-01T00:00:00Z".into(),
updated_at: "2024-01-01T00:00:00Z".into(),
};
let json = serde_json::to_string(&conn).unwrap();
assert!(json.contains("\"favorite\":true"));
}
#[test]
fn connection_input_use_keychain_defaults_true_when_absent() {
let json = r#"{"name":"n","db_type":"postgresql","host":"h","port":5432,"tag_ids":[]}"#;
let input: ConnectionInput = serde_json::from_str(json).unwrap();
assert!(input.use_keychain, "absent use_keychain defaults to true (opt-out)");
}
#[test]
fn connection_input_use_keychain_preserves_false() {
let json = r#"{"name":"n","db_type":"postgresql","host":"h","port":5432,"tag_ids":[],"use_keychain":false}"#;
let input: ConnectionInput = serde_json::from_str(json).unwrap();
assert!(!input.use_keychain);
}
}
+733
View File
@@ -0,0 +1,733 @@
use serde::{Deserialize, Serialize};
/// A single filter rule sent from the frontend.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FilterRule {
pub id: String,
pub column: String,
pub operator: String, // "eq" | "neq" | "contains" | "starts" | "ends" | "gt" | "lt" | "null" | "notnull"
pub value: String,
}
/// A single sort rule sent from the frontend.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SortRule {
pub id: String,
pub column: String,
pub order: String, // "asc" | "desc"
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableInfo {
pub name: String,
pub schema: String,
pub table_type: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ColumnInfo {
pub name: String,
pub data_type: String,
pub is_nullable: bool,
pub is_pk: bool,
pub is_fk: bool,
pub fk_ref: Option<(String, String)>,
pub default_value: Option<String>,
pub editable: bool,
pub is_generated: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexInfo {
pub name: String,
pub schema: String,
pub table: String,
pub definition: String,
pub is_unique: bool,
pub method: String,
pub columns: Vec<String>,
pub size_bytes: Option<i64>,
pub tablespace: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConstraintInfo {
pub name: String,
pub schema: String,
pub table: String,
pub contype: String, // "CHECK" | "UNIQUE" | "EXCLUSION"
pub definition: String,
pub deferrable: bool,
pub validated: bool,
pub columns: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryResult {
pub columns: Vec<ColumnInfo>,
pub rows: Vec<Vec<serde_json::Value>>,
pub total_rows: i64,
pub page: i64,
pub page_size: i64,
pub execution_time_ms: Option<i64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Pagination {
pub page: i64,
pub page_size: i64,
pub total_rows: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FunctionInfo {
pub name: String,
pub schema: String,
pub return_type: String,
pub argument_types: Vec<String>,
pub argument_names: Vec<String>,
pub argument_modes: Vec<String>,
pub language: String,
pub source: Option<String>,
pub kind: String, // 'f' = function, 'p' = procedure
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TriggerInfo {
pub name: String,
pub schema: String,
pub table_schema: String,
pub table_name: String,
pub event_manipulation: String,
pub action_timing: String,
pub action_orientation: String,
pub action_statement: String,
pub enabled: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SequenceInfo {
pub name: String,
pub schema: String,
pub start_value: String,
pub min_value: String,
pub max_value: String,
pub increment: String,
pub current_value: String,
pub cycle: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnumInfo {
pub name: String,
pub schema: String,
pub labels: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtensionInfo {
pub name: String,
pub schema: String,
pub version: String,
pub comment: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObjectSearchHit {
pub name: String,
pub schema: String,
pub object_type: String, // TABLE | VIEW | MATERIALIZED VIEW | FUNCTION | PROCEDURE | TRIGGER | SEQUENCE | ENUM | EXTENSION | INDEX | CONSTRAINT
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DependencyInfo {
pub deptype: String, // "n" (normal) | "a" (auto)
pub class: String, // pg_class | pg_proc | pg_trigger | pg_type | pg_constraint | pg_rewrite
pub name: String, // resolved dependent object name
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoleMembership {
pub role: String,
pub member: String,
pub grantor: String,
pub admin_option: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoleInfo {
pub name: String,
pub superuser: bool,
pub inherit: bool,
pub create_db: bool,
pub create_role: bool,
pub can_login: bool,
pub replication: bool,
pub bypass_rls: bool,
pub connection_limit: i64,
pub valid_until: Option<String>,
pub memberships: Vec<RoleMembership>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PrivilegeEntry {
pub object_class: String, // "table" | "sequence" | "routine" | "schema" | "database"
pub schema: Option<String>,
pub name: String,
pub privileges: Vec<String>,
pub grantable: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RebuildReadiness {
pub ok: bool,
pub reasons: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaintenanceResult {
pub duration_ms: i64,
pub message: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TablespaceInfo {
pub name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Change {
Update {
id: String,
schema: String,
table: String,
primary_key: String,
old_data: String,
new_data: String,
},
Insert {
id: String,
schema: String,
table: String,
data: String,
},
Delete {
id: String,
schema: String,
table: String,
primary_key: String,
},
AlterTable {
id: String,
schema: String,
table: String,
sql: String,
rollback_sql: String,
},
BulkInsert {
id: String,
schema: String,
table: String,
columns: Vec<String>,
rows: Vec<Vec<serde_json::Value>>,
},
DropTable {
id: String,
schema: String,
table: String,
},
EmptyTable {
id: String,
schema: String,
table: String,
},
Ddl {
id: String,
sql: String,
},
RebuildTable {
id: String,
sql: String,
},
}
impl Change {
pub fn id(&self) -> &str {
match self {
Change::Update { id, .. }
| Change::Insert { id, .. }
| Change::Delete { id, .. }
| Change::AlterTable { id, .. }
| Change::BulkInsert { id, .. }
| Change::DropTable { id, .. }
| Change::EmptyTable { id, .. }
| Change::Ddl { id, .. }
| Change::RebuildTable { id, .. } => id,
}
}
}
/// Complete schema graph for the ER diagram visualizer.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchemaGraph {
pub tables: Vec<TableNode>,
pub relationships: Vec<Relationship>,
}
/// A table node in the schema graph, including all columns.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableNode {
pub name: String,
pub schema: String,
pub table_type: String,
pub columns: Vec<GraphColumn>,
}
/// Column metadata for schema graph visualization.
///
/// Includes PK/FK/UNIQUE flags and an optional foreign-key reference
/// (referenced_schema, referenced_table, referenced_column).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GraphColumn {
pub name: String,
pub data_type: String,
pub is_pk: bool,
pub is_fk: bool,
pub is_unique: bool,
pub is_nullable: bool,
pub fk_ref: Option<(String, String, String)>,
}
/// A foreign-key relationship between two tables.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Relationship {
pub source_schema: String,
pub source_table: String,
pub source_column: String,
pub target_schema: String,
pub target_table: String,
pub target_column: String,
/// Inferred cardinality: "1:1", "1:N", or "N:M"
pub cardinality: String,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn table_info_serialization() {
let info = TableInfo {
name: "users".to_string(),
schema: "public".to_string(),
table_type: "TABLE".to_string(),
};
let json = serde_json::to_string(&info).unwrap();
assert!(json.contains("users"));
assert!(json.contains("public"));
assert!(json.contains("TABLE"));
}
#[test]
fn query_result_can_be_empty() {
let result = QueryResult {
columns: vec![],
rows: vec![],
total_rows: 0,
page: 1,
page_size: 100,
execution_time_ms: None,
};
let json = serde_json::to_string(&result).unwrap();
assert!(json.contains(r#""rows":[]"#));
}
#[test]
fn change_id_method() {
let update = Change::Update {
id: "chg-1".to_string(),
schema: "public".to_string(),
table: "users".to_string(),
primary_key: "{\"id\": 1}".to_string(),
old_data: "{\"name\": \"old\"}".to_string(),
new_data: "{\"name\": \"new\"}".to_string(),
};
assert_eq!(update.id(), "chg-1");
let inserted = Change::Insert {
id: "chg-2".to_string(),
schema: "public".to_string(),
table: "users".to_string(),
data: "{\"name\": \"alice\"}".to_string(),
};
assert_eq!(inserted.id(), "chg-2");
let deleted = Change::Delete {
id: "chg-3".to_string(),
schema: "public".to_string(),
table: "users".to_string(),
primary_key: "{\"id\": 2}".to_string(),
};
assert_eq!(deleted.id(), "chg-3");
let alter = Change::AlterTable {
id: "chg-4".to_string(),
schema: "public".to_string(),
table: "users".to_string(),
sql: "ALTER TABLE users ADD COLUMN age INT".to_string(),
rollback_sql: "ALTER TABLE users DROP COLUMN age".to_string(),
};
assert_eq!(alter.id(), "chg-4");
}
#[test]
fn change_serde_tag() {
let update = Change::Update {
id: "chg-1".to_string(),
schema: "public".to_string(),
table: "users".to_string(),
primary_key: "{\"id\": 1}".to_string(),
old_data: "{\"name\": \"old\"}".to_string(),
new_data: "{\"name\": \"new\"}".to_string(),
};
let json = serde_json::to_string(&update).unwrap();
assert!(
json.contains(r#""type":"update""#),
"serialized Change::Update should use snake_case tag 'update'; got: {}",
json
);
}
#[test]
fn change_bulk_insert_roundtrip() {
let json = serde_json::json!({
"type": "bulk_insert", "id": "x", "schema": "public", "table": "t",
"columns": ["a", "b"],
"rows": [[1, "y"], [2, "z"]]
});
let c: Change = serde_json::from_value(json).unwrap();
match c {
Change::BulkInsert { columns, rows, .. } => {
assert_eq!(columns, vec!["a".to_string(), "b".to_string()]);
assert_eq!(rows.len(), 2);
}
_ => panic!("expected BulkInsert"),
}
}
#[test]
fn change_drop_and_empty_roundtrip() {
let drop: Change = serde_json::from_value(serde_json::json!({
"type": "drop_table", "id": "d", "schema": "public", "table": "t"
}))
.unwrap();
assert_eq!(drop.id(), "d");
let empty: Change = serde_json::from_value(serde_json::json!({
"type": "empty_table", "id": "e", "schema": "public", "table": "t"
}))
.unwrap();
assert_eq!(empty.id(), "e");
}
#[test]
fn column_info_fk_ref() {
let col = ColumnInfo {
name: "user_id".to_string(),
data_type: "integer".to_string(),
is_nullable: true,
is_pk: false,
is_fk: true,
fk_ref: Some(("users".to_string(), "id".to_string())),
default_value: None,
editable: true,
is_generated: false,
};
let json = serde_json::to_string(&col).unwrap();
assert!(json.contains("user_id"));
assert!(json.contains("users"));
}
#[test]
fn column_info_has_editability_fields() {
let c = ColumnInfo {
name: "id".into(),
data_type: "integer".into(),
is_nullable: false,
is_pk: true,
is_fk: false,
fk_ref: None,
default_value: None,
editable: false,
is_generated: false,
};
let json = serde_json::to_string(&c).unwrap();
assert!(json.contains("\"editable\":false"));
assert!(json.contains("\"is_generated\":false"));
}
#[test]
fn pagination_serialization() {
let pagination = Pagination {
page: 2,
page_size: 50,
total_rows: 250,
};
let json = serde_json::to_string(&pagination).unwrap();
assert!(json.contains(r#""page":2"#));
assert!(json.contains(r#""page_size":50"#));
assert!(json.contains(r#""total_rows":250"#));
}
#[test]
fn function_info_serialization() {
let info = FunctionInfo {
name: "get_user".into(),
schema: "public".into(),
return_type: "TABLE(id integer, name text)".into(),
argument_types: vec!["integer".into()],
argument_names: vec!["p_id".into()],
argument_modes: vec!["IN".into()],
language: "plpgsql".into(),
source: Some("BEGIN RETURN; END;".into()),
kind: "f".into(),
};
let json = serde_json::to_string(&info).unwrap();
assert!(json.contains("get_user"));
assert!(json.contains("plpgsql"));
}
#[test]
fn trigger_info_serialization() {
let info = TriggerInfo {
name: "trg_audit".into(),
schema: "public".into(),
table_schema: "public".into(),
table_name: "users".into(),
event_manipulation: "INSERT".into(),
action_timing: "AFTER".into(),
action_orientation: "ROW".into(),
action_statement: "EXECUTE FUNCTION audit_log()".into(),
enabled: "O".into(),
};
let json = serde_json::to_string(&info).unwrap();
assert!(json.contains("trg_audit"));
}
#[test]
fn sequence_info_serialization() {
let info = SequenceInfo {
name: "users_id_seq".into(),
schema: "public".into(),
start_value: "1".into(),
min_value: "1".into(),
max_value: "9223372036854775807".into(),
increment: "1".into(),
current_value: "42".into(),
cycle: false,
};
let json = serde_json::to_string(&info).unwrap();
assert!(json.contains("users_id_seq"));
}
#[test]
fn enum_info_serialization() {
let info = EnumInfo {
name: "user_role".into(),
schema: "public".into(),
labels: vec!["admin".into(), "editor".into(), "viewer".into()],
};
let json = serde_json::to_string(&info).unwrap();
assert!(json.contains("admin"));
}
#[test]
fn extension_info_serialization() {
let info = ExtensionInfo {
name: "pg_stat_statements".into(),
schema: "public".into(),
version: "1.10".into(),
comment: Some("track SQL statistics".into()),
};
let json = serde_json::to_string(&info).unwrap();
assert!(json.contains("pg_stat_statements"));
}
#[test]
fn schema_graph_serialization() {
let graph = SchemaGraph {
tables: vec![TableNode {
name: "users".into(),
schema: "public".into(),
table_type: "TABLE".into(),
columns: vec![
GraphColumn {
name: "id".into(),
data_type: "integer".into(),
is_pk: true,
is_fk: false,
is_unique: true,
is_nullable: false,
fk_ref: None,
},
GraphColumn {
name: "email".into(),
data_type: "text".into(),
is_pk: false,
is_fk: false,
is_unique: true,
is_nullable: false,
fk_ref: None,
},
],
}],
relationships: vec![Relationship {
source_schema: "public".into(),
source_table: "orders".into(),
source_column: "user_id".into(),
target_schema: "public".into(),
target_table: "users".into(),
target_column: "id".into(),
cardinality: "1:N".into(),
}],
};
let json = serde_json::to_string(&graph).unwrap();
assert!(json.contains("users"), "should contain table name");
assert!(
json.contains("orders"),
"should contain relationship source table"
);
assert!(json.contains("1:N"), "should contain cardinality");
assert!(json.contains("is_pk"), "should contain is_pk field");
assert!(json.contains("is_fk"), "should contain is_fk field");
assert!(json.contains("is_unique"), "should contain is_unique field");
// Round-trip deserialization
let parsed: SchemaGraph = serde_json::from_str(&json).unwrap();
assert_eq!(parsed.tables.len(), 1);
assert_eq!(parsed.tables[0].columns.len(), 2);
assert_eq!(parsed.relationships.len(), 1);
assert_eq!(parsed.relationships[0].cardinality, "1:N");
}
#[test]
fn schema_graph_empty_is_valid() {
let graph = SchemaGraph {
tables: vec![],
relationships: vec![],
};
let json = serde_json::to_string(&graph).unwrap();
let parsed: SchemaGraph = serde_json::from_str(&json).unwrap();
assert!(parsed.tables.is_empty());
assert!(parsed.relationships.is_empty());
}
#[test]
fn graph_column_fk_ref_serialization() {
// fk_ref = None
let col_none = GraphColumn {
name: "name".into(),
data_type: "text".into(),
is_pk: false,
is_fk: false,
is_unique: false,
is_nullable: false,
fk_ref: None,
};
let json = serde_json::to_string(&col_none).unwrap();
assert!(
json.contains("null"),
"fk_ref=None should serialize as null"
);
// fk_ref = Some(...)
let col_some = GraphColumn {
name: "user_id".into(),
data_type: "integer".into(),
is_pk: false,
is_fk: true,
is_unique: false,
is_nullable: false,
fk_ref: Some(("public".into(), "users".into(), "id".into())),
};
let json = serde_json::to_string(&col_some).unwrap();
assert!(json.contains("public"), "should contain referenced schema");
assert!(json.contains("users"), "should contain referenced table");
assert!(json.contains("id"), "should contain referenced column");
}
#[test]
fn object_search_hit_tagged_roundtrip() {
let hit = ObjectSearchHit { name: "users".into(), schema: "public".into(), object_type: "TABLE".into() };
let json = serde_json::to_string(&hit).unwrap();
assert!(json.contains("\"object_type\":\"TABLE\""));
let back: ObjectSearchHit = serde_json::from_str(&json).unwrap();
assert_eq!(back.name, "users");
}
#[test]
fn dependency_info_roundtrip() {
let d = DependencyInfo { deptype: "n".into(), class: "pg_class".into(), name: "v_users".into() };
let json = serde_json::to_string(&d).unwrap();
assert!(json.contains("\"deptype\":\"n\""));
assert!(json.contains("v_users"));
}
#[test]
fn change_rebuild_table_serializes_with_snake_case_tag() {
let change = Change::RebuildTable {
id: "chg-rb1".to_string(),
sql: "CREATE TABLE _t ...".to_string(),
};
let json = serde_json::to_string(&change).unwrap();
assert!(
json.contains(r#""type":"rebuild_table""#),
"RebuildTable should serialize with tag 'rebuild_table'; got: {json}"
);
assert_eq!(change.id(), "chg-rb1");
}
#[test]
fn change_rebuild_table_roundtrip() {
let json = serde_json::json!({
"type": "rebuild_table", "id": "rb", "sql": "SELECT 1"
});
let c: Change = serde_json::from_value(json).unwrap();
match c {
Change::RebuildTable { sql, .. } => assert_eq!(sql, "SELECT 1"),
_ => panic!("expected RebuildTable"),
}
}
#[test]
fn role_info_roundtrip() {
let r = RoleInfo {
name: "app".into(), superuser: false, inherit: true, create_db: false,
create_role: false, can_login: true, replication: false, bypass_rls: false,
connection_limit: -1, valid_until: None, memberships: vec![RoleMembership {
role: "parent".into(), member: "app".into(), grantor: "admin".into(), admin_option: false,
}],
};
let json = serde_json::to_string(&r).unwrap();
assert!(json.contains(r#""name":"app""#));
assert!(json.contains(r#""can_login":true"#));
let back: RoleInfo = serde_json::from_str(&json).unwrap();
assert_eq!(back.memberships.len(), 1);
}
#[test]
fn privilege_entry_and_readiness_roundtrip() {
let pe = PrivilegeEntry {
object_class: "table".into(), schema: Some("public".into()), name: "users".into(),
privileges: vec!["SELECT".into(), "INSERT".into()], grantable: false,
};
assert!(serde_json::to_string(&pe).unwrap().contains(r#""object_class":"table""#));
let rr = RebuildReadiness { ok: false, reasons: vec!["has triggers".into()] };
assert!(serde_json::to_string(&rr).unwrap().contains(r#""ok":false"#));
let mr = MaintenanceResult { duration_ms: 42, message: "ok".into() };
assert!(serde_json::to_string(&mr).unwrap().contains(r#""duration_ms":42"#));
let ts = TablespaceInfo { name: "pg_default".into() };
assert!(serde_json::to_string(&ts).unwrap().contains("pg_default"));
}
}
+18
View File
@@ -0,0 +1,18 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Folder {
pub id: String,
pub name: String,
pub parent_id: Option<String>,
pub tag_ids: Vec<String>,
pub created_at: String,
pub updated_at: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FolderInput {
pub name: String,
pub parent_id: Option<String>,
pub tag_ids: Option<Vec<String>>,
}
+17
View File
@@ -0,0 +1,17 @@
pub mod backup;
pub mod connection;
pub mod db_viewer;
pub mod folder;
pub mod recent;
pub mod settings;
pub mod ssh;
pub mod tag;
pub use connection::{Connection, ConnectionInput};
#[allow(unused_imports)]
pub use db_viewer::{Change, ColumnInfo, FilterRule, MaintenanceResult, Pagination, PrivilegeEntry, QueryResult, RebuildReadiness, RoleInfo, RoleMembership, SortRule, TableInfo, TablespaceInfo};
pub use folder::{Folder, FolderInput};
pub use recent::RecentConnection;
pub use settings::Settings;
pub use ssh::SshConfig;
pub use tag::{Tag, TagInput};
+7
View File
@@ -0,0 +1,7 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecentConnection {
pub connection_id: String,
pub opened_at: String,
}
+29
View File
@@ -0,0 +1,29 @@
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Settings {
pub confirm_before_delete: bool,
pub default_folder_id: Option<String>,
pub theme: String,
pub font_size: String,
pub default_ports: HashMap<String, Option<i64>>,
pub tag_order: Option<String>,
pub table_refresh_rate: i64,
pub table_page_size: i64,
pub shortcuts: HashMap<String, String>,
pub accent_color: String,
// Editor (Plan A)
pub editor_font_size: i64,
pub editor_font_family: String,
pub editor_word_wrap: String,
pub editor_minimap: bool,
pub editor_tab_size: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SettingsExport {
pub schema_version: u32,
pub settings: Settings,
}
+39
View File
@@ -0,0 +1,39 @@
use serde::{Deserialize, Serialize};
/// SSH tunnel configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SshConfig {
pub host: String,
pub port: u16,
pub user: String,
/// "password" or "key"
pub auth_method: String,
pub password: Option<String>,
pub private_key_path: Option<String>,
pub passphrase: Option<String>,
}
impl SshConfig {
/// Create a new `SshConfig` with the required fields.
pub fn new(host: String, port: u16, user: String, auth_method: String) -> Self {
SshConfig {
host,
port,
user,
auth_method,
password: None,
private_key_path: None,
passphrase: None,
}
}
/// Validate SSH configuration.
///
/// Returns `true` if:
/// - `host` is not empty
/// - `port` is in range 1..=65535 (u16 guarantees <= 65535)
/// - `user` is not empty
pub fn is_valid(&self) -> bool {
!self.host.is_empty() && self.port >= 1 && !self.user.is_empty()
}
}
+15
View File
@@ -0,0 +1,15 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Tag {
pub id: String,
pub name: String,
pub color: String,
pub created_at: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TagInput {
pub name: String,
pub color: String,
}