Skip to content

Commit 3d7dc80

Browse files
committed
fix(postgres): retain all script result sets safely
1 parent fe708cb commit 3d7dc80

15 files changed

Lines changed: 640 additions & 95 deletions

File tree

‎DESIGN.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,7 @@ Interactive components must cover default, hover, focus-visible, active / select
233233

234234
### SQL editor and result grids
235235

236+
- Keep the result-set selector inside the existing result toolbar. Collapse secondary export actions into a menu at narrow panel widths to preserve a single toolbar row.
236237
- Keep Monaco's theme integration (currently `vs / vs-dark`) and user font-size settings. Syntax highlighting is outside the application decoration color budget; reducing colors must not damage syntax recognition.
237238
- Keep data central: neutral headers, subtle hover, stable selection, and clear sorting / filtering indicators. Preserve virtual scrolling; do not rebuild the whole grid for animation.
238239
- Distinguish `NULL`, empty strings, and booleans. Show true / false or equivalent text / symbols; do not default to red / green boolean mapping.
@@ -306,7 +307,7 @@ Check each affected surface. Documentation-only changes need source, link, and i
306307
| --- | --- | --- |
307308
| P1 | Existing foreground pairs such as success / destructive need individual verification | Check contrast on actual backgrounds; adjust semantic pairs when needed while retaining the blue brand |
308309
| P1 | Success / warning in `ui/badge` and notifications still use fixed palettes; a global warning token is missing | Add light/dark semantic tokens and mappings first, then migrate shared components and check all consumers |
309-
| P2 | Some `QueriesPage.vue` toolbar buttons use purple / orange; `QueryResultPanel.vue` assigns sky / amber / green by format | Use neutral toolbars and primary for the main action |
310+
| P2 | Some `QueriesPage.vue` toolbar buttons use purple / orange | Use neutral toolbars and primary for the main action |
310311
| P2 | `grid/FilterBar.vue` assigns colors to operators; grid booleans and some attributes use red / green / amber | Use neutral text, symbols, and attribute icons; color only actual status |
311312
| P2 | `AppHeader.vue` uses red for ordinary task counts; some connection-page icon containers use multiple colors | Make counts neutral; distinguish connection cards by name / engine icon / actual status |
312313
| P2 | Shared Badge defaults to solid primary; some close buttons appear only on hover | Explicitly select neutral variants for non-interactive badges and make close buttons visible on keyboard focus |

‎src-tauri/src/database/jdbc_bridge/adapter.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ impl JdbcBridgeAdapter {
141141
rows_affected: qr.rows_affected,
142142
execution_time_ms: None,
143143
truncated: false,
144+
result_sets: Vec::new(),
144145
})
145146
}
146147

@@ -236,6 +237,7 @@ impl DatabaseAdapter for JdbcBridgeAdapter {
236237
rows_affected: Some(0),
237238
execution_time_ms: None,
238239
truncated: false,
240+
result_sets: Vec::new(),
239241
});
240242
}
241243
// Execute each statement individually. Many JDBC drivers (notably
@@ -258,6 +260,7 @@ impl DatabaseAdapter for JdbcBridgeAdapter {
258260
rows_affected: Some(0),
259261
execution_time_ms: None,
260262
truncated: false,
263+
result_sets: Vec::new(),
261264
};
262265
for stmt in &statements {
263266
let data = Self::send_request(

‎src-tauri/src/database/postgres.rs‎

Lines changed: 79 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,32 @@ pub struct PostgresPool {
177177
pool: Pool,
178178
}
179179

180+
/// Only return a query connection to the pool after execution completes successfully.
181+
struct QueryClient(Option<deadpool_postgres::Object>);
182+
183+
impl std::ops::Deref for QueryClient {
184+
type Target = deadpool_postgres::Object;
185+
186+
fn deref(&self) -> &Self::Target {
187+
self.0.as_ref().unwrap()
188+
}
189+
}
190+
191+
impl QueryClient {
192+
fn release(mut self) {
193+
drop(self.0.take());
194+
}
195+
}
196+
197+
impl Drop for QueryClient {
198+
fn drop(&mut self) {
199+
if let Some(client) = self.0.take() {
200+
// Detach before closing, including when an outer timeout drops this future.
201+
drop(deadpool_postgres::Object::take(client));
202+
}
203+
}
204+
}
205+
180206
#[async_trait]
181207
impl ConnectionPool for PostgresPool {
182208
type Connection = Client;
@@ -365,6 +391,9 @@ impl PostgresAdapter {
365391

366392
// Add additional options
367393
for (key, value) in &self.config.options {
394+
if key == "statement_timeout" {
395+
continue;
396+
}
368397
// The keyword side cannot be quoted: reject keys with
369398
// syntax-meaningful characters instead of interpolating them.
370399
if !key
@@ -592,15 +621,21 @@ impl PostgresAdapter {
592621
None
593622
};
594623

624+
let builder = ClientConfig::builder_with_provider(Arc::new(
625+
rustls::crypto::aws_lc_rs::default_provider(),
626+
))
627+
.with_safe_default_protocol_versions()
628+
.map_err(|e| DbError::Configuration(format!("Failed to configure TLS: {}", e)))?;
629+
595630
if skip_verification {
596631
let config = if let Some((certs, key)) = client_auth {
597-
ClientConfig::builder()
632+
builder
598633
.dangerous()
599634
.with_custom_certificate_verifier(Arc::new(NoVerification))
600635
.with_client_auth_cert(certs, key)
601636
.map_err(|e| DbError::Connection(format!("Failed to set client auth: {}", e)))?
602637
} else {
603-
ClientConfig::builder()
638+
builder
604639
.dangerous()
605640
.with_custom_certificate_verifier(Arc::new(NoVerification))
606641
.with_no_client_auth()
@@ -640,15 +675,15 @@ impl PostgresAdapter {
640675

641676
if !verify_hostname {
642677
let config = if let Some((certs, key)) = client_auth {
643-
ClientConfig::builder()
678+
builder
644679
.dangerous()
645680
.with_custom_certificate_verifier(Arc::new(ChainOnlyVerifier {
646681
root_store: Arc::new(root_store),
647682
}))
648683
.with_client_auth_cert(certs, key)
649684
.map_err(|e| DbError::Connection(format!("Failed to set client auth: {}", e)))?
650685
} else {
651-
ClientConfig::builder()
686+
builder
652687
.dangerous()
653688
.with_custom_certificate_verifier(Arc::new(ChainOnlyVerifier {
654689
root_store: Arc::new(root_store),
@@ -659,12 +694,12 @@ impl PostgresAdapter {
659694
}
660695

661696
let config = if let Some((certs, key)) = client_auth {
662-
ClientConfig::builder()
697+
builder
663698
.with_root_certificates(root_store)
664699
.with_client_auth_cert(certs, key)
665700
.map_err(|e| DbError::Connection(format!("Failed to set client auth: {}", e)))?
666701
} else {
667-
ClientConfig::builder()
702+
builder
668703
.with_root_certificates(root_store)
669704
.with_no_client_auth()
670705
};
@@ -1174,6 +1209,7 @@ impl DatabaseAdapter for PostgresAdapter {
11741209
.get()
11751210
.await
11761211
.map_err(|e| DbError::Connection(format!("Failed to get connection: {}", e)))?;
1212+
let client = QueryClient(Some(client));
11771213

11781214
let start = Instant::now();
11791215

@@ -1186,9 +1222,11 @@ impl DatabaseAdapter for PostgresAdapter {
11861222
.map(Duration::from_millis);
11871223

11881224
let execute = async {
1189-
let mut result = QueryResult::affected(0);
1225+
let statements = split_postgres_statements(query);
1226+
let is_script = statements.len() > 1;
1227+
let mut result_sets = Vec::new();
11901228
let mut affected = 0;
1191-
for sql in split_postgres_statements(query) {
1229+
for sql in statements {
11921230
let statement = client
11931231
.prepare(sql)
11941232
.await
@@ -1239,10 +1277,14 @@ impl DatabaseAdapter for PostgresAdapter {
12391277
current.add_row(Self::row_to_query_row(&row)?);
12401278
}
12411279
}
1242-
result = current;
1280+
result_sets.push(current);
12431281
}
1244-
if result.columns.is_empty() {
1245-
result.rows_affected = Some(affected);
1282+
let mut result = result_sets
1283+
.last()
1284+
.cloned()
1285+
.unwrap_or_else(|| QueryResult::affected(affected));
1286+
if is_script {
1287+
result.result_sets = result_sets;
12461288
}
12471289
Ok::<_, DbError>(result)
12481290
};
@@ -1253,6 +1295,7 @@ impl DatabaseAdapter for PostgresAdapter {
12531295
} else {
12541296
execute.await?
12551297
};
1298+
client.release();
12561299
Ok(result.with_execution_time(start.elapsed().as_millis() as u64))
12571300
}
12581301

@@ -2662,6 +2705,31 @@ mod tests {
26622705
use super::*;
26632706
use crate::database::DatabaseType;
26642707

2708+
#[test]
2709+
fn tls_configuration_selects_an_explicit_crypto_provider() {
2710+
let adapter = PostgresAdapter::new(ConnectionConfig::new(
2711+
DatabaseType::PostgreSQL,
2712+
"localhost",
2713+
5432,
2714+
"postgres",
2715+
));
2716+
assert!(adapter.build_rustls_config(true, true).is_ok());
2717+
assert!(adapter.build_rustls_config(false, false).is_ok());
2718+
assert!(adapter.build_rustls_config(false, true).is_ok());
2719+
}
2720+
2721+
#[test]
2722+
fn execution_timeout_is_not_forwarded_as_a_connection_keyword() {
2723+
let config = ConnectionConfig::new(DatabaseType::PostgreSQL, "localhost", 5432, "postgres")
2724+
.with_option("statement_timeout", "1000")
2725+
.with_option("application_name", "sqlkit");
2726+
let connection_string = PostgresAdapter::new(config)
2727+
.build_connection_string()
2728+
.unwrap();
2729+
assert!(!connection_string.contains("statement_timeout"));
2730+
assert!(connection_string.contains("application_name='sqlkit'"));
2731+
}
2732+
26652733
#[test]
26662734
fn split_preserves_quoted_blocks_comments_and_unicode() {
26672735
let sql =

‎src-tauri/src/database/sqlite.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -421,6 +421,7 @@ impl SQLiteAdapter {
421421
rows_affected: None,
422422
execution_time_ms: None,
423423
truncated: false,
424+
result_sets: Vec::new(),
424425
})
425426
} else {
426427
// For non-SELECT queries (INSERT, UPDATE, DELETE, etc.)
@@ -438,6 +439,7 @@ impl SQLiteAdapter {
438439
rows_affected: Some(rows_affected as u64),
439440
execution_time_ms: None,
440441
truncated: false,
442+
result_sets: Vec::new(),
441443
})
442444
}
443445
}

‎src-tauri/src/database/types.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,9 @@ pub struct QueryResult {
113113
/// Whether the result was truncated (e.g., due to row limit).
114114
#[serde(default)]
115115
pub truncated: bool,
116+
/// Row-producing results in script order. Empty for single statements.
117+
#[serde(default, skip_serializing_if = "Vec::is_empty")]
118+
pub result_sets: Vec<QueryResult>,
116119
}
117120

118121
impl QueryResult {
@@ -125,6 +128,7 @@ impl QueryResult {
125128
rows_affected: None,
126129
execution_time_ms: None,
127130
truncated: false,
131+
result_sets: Vec::new(),
128132
}
129133
}
130134

@@ -137,6 +141,7 @@ impl QueryResult {
137141
rows_affected: None,
138142
execution_time_ms: None,
139143
truncated: false,
144+
result_sets: Vec::new(),
140145
}
141146
}
142147

@@ -149,6 +154,7 @@ impl QueryResult {
149154
rows_affected: Some(rows_affected),
150155
execution_time_ms: None,
151156
truncated: false,
157+
result_sets: Vec::new(),
152158
}
153159
}
154160

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
-- Run the complete script on one connection. All values are synthetic test data.
2+
BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY;
3+
4+
-- A doubled quote and Unicode must survive statement splitting.
5+
SELECT
6+
set_config('script_test.email', 'o''connor测试@example.com', true) AS email,
7+
set_config('script_test.unit', 'USD', true) AS unit,
8+
set_config('script_test.request_id', '', true) AS request_id,
9+
set_config('script_test.external_ref', '', true) AS external_ref;
10+
11+
SELECT current_database() AS database_name,
12+
current_setting('transaction_read_only') AS transaction_read_only,
13+
now() AS checked_at;
14+
15+
SELECT u.id AS customer_id, u.email, b.label, b.state, b.score,
16+
b.region, b.profile_type, b.display_name,
17+
b.reference_code, b.contact_email
18+
FROM sample_customers u LEFT JOIN sample_profiles b ON b.customer_id = u.id
19+
WHERE u.email = current_setting('script_test.email');
20+
21+
SELECT l.id, l.customer_id, l.state, l.unit, l.amount, l.source,
22+
l.external_ref, l.source_ref, l.match_key, l.created_at
23+
FROM sample_events l JOIN sample_customers u ON u.id = l.customer_id
24+
WHERE u.email = current_setting('script_test.email') AND l.type = 'credit'
25+
AND (current_setting('script_test.external_ref') = ''
26+
OR l.external_ref = current_setting('script_test.external_ref'))
27+
ORDER BY l.created_at DESC LIMIT 100;
28+
29+
SELECT t.id, t.customer_id, t.category, t.state, t.amount, t.unit,
30+
t.payload, t.outcome, t.owner_id, t.created_at, t.completed_at
31+
FROM sample_requests t JOIN sample_customers u ON u.id = t.customer_id
32+
WHERE u.email = current_setting('script_test.email')
33+
AND (current_setting('script_test.request_id') = ''
34+
OR t.id::text = current_setting('script_test.request_id'))
35+
ORDER BY t.created_at DESC LIMIT 100;
36+
37+
SELECT current_setting('script_test.unit') AS unit,
38+
COALESCE(SUM(l.amount), 0) AS total_amount
39+
FROM sample_events l JOIN sample_customers u ON u.id = l.customer_id
40+
WHERE u.email = current_setting('script_test.email')
41+
AND l.unit = current_setting('script_test.unit')
42+
AND l.state = 'success' AND l.type <> 'excluded';
43+
44+
SELECT l.id, l.customer_id, l.type, l.state, l.amount, l.unit, l.match_key
45+
FROM sample_events l JOIN sample_customers u ON u.id = l.customer_id
46+
WHERE u.email = current_setting('script_test.email')
47+
AND current_setting('script_test.request_id') <> ''
48+
AND l.match_key = 'request:' || current_setting('script_test.request_id');
49+
50+
SELECT current_setting('script_test.request_id') AS request_id,
51+
current_setting('script_test.unit') AS unit,
52+
COUNT(*) AS matched_rows,
53+
COALESCE(SUM(l.amount), 0) AS matched_amount
54+
FROM sample_events l JOIN sample_customers u ON u.id = l.customer_id
55+
WHERE u.email = current_setting('script_test.email')
56+
AND current_setting('script_test.request_id') <> ''
57+
AND l.match_key = 'request:' || current_setting('script_test.request_id')
58+
AND l.type = 'adjustment' AND l.state = 'success'
59+
AND l.unit = current_setting('script_test.unit');
60+
61+
COMMIT;

0 commit comments

Comments
 (0)