Skip to main content

nz_rust/
blocking.rs

1// Copyright 2026 Krzysztof Duśko.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Blocking client with the same query semantics as the native async client.
16
17use crate::config::NzConnectionConfig;
18#[cfg(feature = "compat")]
19use crate::connection::NzConnection;
20use crate::connection::{QueryResult, Row};
21#[cfg(feature = "compat")]
22use crate::connection::{QueryStreamSink, StreamSummary};
23use crate::error::{NzError, NzResult};
24#[cfg(feature = "compat")]
25use crate::types::value::NzValue;
26use crate::types::value::ToSql;
27
28/// Synchronous counterpart of [`crate::native_async::Client`].
29#[cfg(feature = "compat")]
30pub struct BlockingClient {
31    inner: NzConnection,
32}
33
34#[cfg(feature = "compat")]
35impl BlockingClient {
36    pub fn connect(config: &NzConnectionConfig) -> NzResult<Self> {
37        Ok(Self {
38            inner: NzConnection::connect(config)?,
39        })
40    }
41
42    pub fn connect_with_str(connection_string: &str) -> NzResult<Self> {
43        let config = crate::parse_connection_string(connection_string)?;
44        Self::connect(&config)
45    }
46
47    pub fn query_multi(
48        &mut self,
49        sql: &str,
50        params: &[&(dyn ToSql + Sync)],
51    ) -> NzResult<QueryResult> {
52        let values: Vec<NzValue> = params.iter().map(|value| value.to_nz_value()).collect();
53        self.inner.query_values(sql, &values)
54    }
55
56    pub fn query(&mut self, sql: &str, params: &[&(dyn ToSql + Sync)]) -> NzResult<Vec<Row>> {
57        let result = self.query_multi(sql, params)?;
58        if result.result_sets.len() > 1 {
59            return Err(NzError::Config(
60                "query returned multiple result sets; use query_multi".into(),
61            ));
62        }
63        Ok(result
64            .result_sets
65            .into_iter()
66            .next()
67            .map(|set| set.rows)
68            .unwrap_or_default())
69    }
70
71    pub fn query_one(&mut self, sql: &str, params: &[&(dyn ToSql + Sync)]) -> NzResult<Row> {
72        let rows = self.query(sql, params)?;
73        if rows.len() != 1 {
74            return Err(NzError::Config(format!(
75                "query_one: expected one row, got {}",
76                rows.len()
77            )));
78        }
79        Ok(rows.into_iter().next().expect("one row checked above"))
80    }
81
82    pub fn query_opt(
83        &mut self,
84        sql: &str,
85        params: &[&(dyn ToSql + Sync)],
86    ) -> NzResult<Option<Row>> {
87        let rows = self.query(sql, params)?;
88        match rows.len() {
89            0 => Ok(None),
90            1 => Ok(rows.into_iter().next()),
91            count => Err(NzError::Config(format!(
92                "query_opt: expected at most one row, got {count}"
93            ))),
94        }
95    }
96
97    pub fn execute(&mut self, sql: &str, params: &[&(dyn ToSql + Sync)]) -> NzResult<i64> {
98        let values: Vec<NzValue> = params.iter().map(|value| value.to_nz_value()).collect();
99        self.inner.execute_values(sql, &values)
100    }
101
102    pub fn batch_execute(&mut self, sql: &str) -> NzResult<()> {
103        self.inner.batch_execute(sql)
104    }
105
106    pub fn execute_stream<S: QueryStreamSink>(
107        &mut self,
108        sql: &str,
109        params: &[&(dyn ToSql + Sync)],
110        sink: &mut S,
111    ) -> NzResult<StreamSummary> {
112        let values: Vec<NzValue> = params.iter().map(|value| value.to_nz_value()).collect();
113        self.inner.execute_stream_values(sql, &values, sink)
114    }
115
116    /// Run a closure in a transaction with rollback-on-error semantics.
117    pub fn transaction<T>(&mut self, body: impl FnOnce(&mut Self) -> NzResult<T>) -> NzResult<T> {
118        self.batch_execute("BEGIN")?;
119        match body(self) {
120            Ok(value) => {
121                self.batch_execute("COMMIT")?;
122                Ok(value)
123            }
124            Err(error) => {
125                let _ = self.batch_execute("ROLLBACK");
126                Err(error)
127            }
128        }
129    }
130
131    pub fn close(&mut self) {
132        self.inner.close();
133    }
134
135    pub fn inner(&self) -> &NzConnection {
136        &self.inner
137    }
138
139    pub fn inner_mut(&mut self) -> &mut NzConnection {
140        &mut self.inner
141    }
142}
143
144/// A transaction exclusively borrowing the blocking client. Drop rolls back.
145#[cfg(feature = "compat")]
146pub struct LegacyTransaction<'a> {
147    client: &'a mut BlockingClient,
148    finished: bool,
149}
150#[cfg(feature = "compat")]
151impl BlockingClient {
152    pub fn begin_transaction(&mut self) -> NzResult<LegacyTransaction<'_>> {
153        if self.inner.in_transaction() {
154            return Err(NzError::Config("nested transaction is unsupported".into()));
155        }
156        self.batch_execute("BEGIN")?;
157        Ok(LegacyTransaction {
158            client: self,
159            finished: false,
160        })
161    }
162}
163#[cfg(feature = "compat")]
164impl LegacyTransaction<'_> {
165    pub fn commit(mut self) -> NzResult<()> {
166        self.client.batch_execute("COMMIT")?;
167        self.finished = true;
168        Ok(())
169    }
170    pub fn rollback(mut self) -> NzResult<()> {
171        self.client.batch_execute("ROLLBACK")?;
172        self.finished = true;
173        Ok(())
174    }
175}
176#[cfg(feature = "compat")]
177impl std::ops::Deref for LegacyTransaction<'_> {
178    type Target = BlockingClient;
179    fn deref(&self) -> &Self::Target {
180        self.client
181    }
182}
183#[cfg(feature = "compat")]
184impl std::ops::DerefMut for LegacyTransaction<'_> {
185    fn deref_mut(&mut self) -> &mut Self::Target {
186        self.client
187    }
188}
189#[cfg(feature = "compat")]
190impl Drop for LegacyTransaction<'_> {
191    fn drop(&mut self) {
192        if !self.finished
193            && self
194                .client
195                .inner
196                .execute_values_with_timeout(
197                    "ROLLBACK",
198                    &[],
199                    Some(std::time::Duration::from_secs(5)),
200                )
201                .is_err()
202        {
203            self.client.close();
204        }
205    }
206}
207
208/// Blocking client using the same bounded protocol driver as [`crate::Client`].
209/// Use outside a Tokio runtime; asynchronous callers should use `crate::Client`.
210pub struct Client {
211    runtime: std::sync::Arc<tokio::runtime::Runtime>,
212    client: crate::Client,
213}
214impl Client {
215    pub fn connect(config: &NzConnectionConfig) -> NzResult<Self> {
216        let runtime = std::sync::Arc::new(
217            tokio::runtime::Builder::new_multi_thread()
218                .worker_threads(1)
219                .enable_all()
220                .build()?,
221        );
222        let client = runtime.block_on(crate::Client::connect(config))?;
223        Ok(Self { runtime, client })
224    }
225    pub fn connect_with_str(uri: &str) -> NzResult<Self> {
226        Self::connect(&crate::parse_connection_string(uri)?)
227    }
228    pub fn query(&mut self, sql: &str, params: &[&(dyn ToSql + Sync)]) -> NzResult<Vec<Row>> {
229        self.runtime.block_on(self.client.query(sql, params))
230    }
231    pub fn query_multi(
232        &mut self,
233        sql: &str,
234        params: &[&(dyn ToSql + Sync)],
235    ) -> NzResult<QueryResult> {
236        self.runtime.block_on(self.client.query_multi(sql, params))
237    }
238    pub fn query_one(&mut self, sql: &str, params: &[&(dyn ToSql + Sync)]) -> NzResult<Row> {
239        self.runtime.block_on(self.client.query_one(sql, params))
240    }
241    pub fn query_opt(
242        &mut self,
243        sql: &str,
244        params: &[&(dyn ToSql + Sync)],
245    ) -> NzResult<Option<Row>> {
246        self.runtime.block_on(self.client.query_opt(sql, params))
247    }
248    pub fn execute(&mut self, sql: &str, params: &[&(dyn ToSql + Sync)]) -> NzResult<i64> {
249        self.runtime.block_on(self.client.execute(sql, params))
250    }
251    pub fn batch_execute(&mut self, sql: &str) -> NzResult<()> {
252        self.runtime.block_on(self.client.batch_execute(sql))
253    }
254    pub fn query_with_options(
255        &mut self,
256        sql: &str,
257        params: &[&(dyn ToSql + Sync)],
258        options: crate::QueryOptions,
259    ) -> NzResult<Vec<Row>> {
260        self.runtime
261            .block_on(self.client.query_with_options(sql, params, options))
262    }
263    /// Iterator keeps the session exclusively borrowed; drop cancels and drains.
264    pub fn query_iter(
265        &mut self,
266        sql: &str,
267        params: &[&(dyn ToSql + Sync)],
268    ) -> NzResult<RowIter<'_>> {
269        let stream = self
270            .runtime
271            .block_on(self.client.query_stream(sql, params))?;
272        Ok(RowIter {
273            stream: Some(stream),
274            runtime: self.runtime.clone(),
275            client: &self.client,
276        })
277    }
278    pub fn transaction(&mut self) -> NzResult<Transaction<'_>> {
279        let transaction = self.runtime.block_on(self.client.transaction())?;
280        Ok(Transaction {
281            transaction: Some(transaction),
282            client: self,
283        })
284    }
285    pub fn is_closed(&self) -> bool {
286        self.client.is_closed()
287    }
288    pub fn close(&mut self) -> NzResult<()> {
289        self.runtime.block_on(self.client.close())
290    }
291}
292impl Drop for Client {
293    fn drop(&mut self) {
294        let _ = self.runtime.block_on(self.client.close());
295    }
296}
297
298/// Bounded synchronous row iterator, including checked terminal errors.
299pub struct RowIter<'a> {
300    stream: Option<crate::RowStream>,
301    runtime: std::sync::Arc<tokio::runtime::Runtime>,
302    client: &'a crate::Client,
303}
304impl Iterator for RowIter<'_> {
305    type Item = NzResult<Row>;
306    fn next(&mut self) -> Option<Self::Item> {
307        use futures_core::Stream;
308        let stream = self.stream.as_mut()?;
309        self.runtime.block_on(std::future::poll_fn(|cx| {
310            std::pin::Pin::new(&mut *stream).poll_next(cx)
311        }))
312    }
313}
314impl Drop for RowIter<'_> {
315    fn drop(&mut self) {
316        self.stream.take();
317        let result = self.runtime.block_on(tokio_cleanup_barrier(self.client));
318        if result.is_err() {
319            self.client.stop();
320        }
321    }
322}
323async fn tokio_cleanup_barrier(client: &crate::Client) -> NzResult<()> {
324    tokio::time::timeout(std::time::Duration::from_secs(5), client.batch_execute(""))
325        .await
326        .map_err(|_| NzError::Timeout("blocking cleanup timeout".into()))?
327}
328
329/// Transaction sharing the native driver's exclusive guard and rollback semantics.
330pub struct Transaction<'a> {
331    transaction: Option<crate::Transaction>,
332    client: &'a mut Client,
333}
334impl Transaction<'_> {
335    pub fn query(&mut self, sql: &str, params: &[&(dyn ToSql + Sync)]) -> NzResult<Vec<Row>> {
336        self.client.runtime.block_on(
337            self.transaction
338                .as_ref()
339                .expect("active transaction")
340                .query(sql, params),
341        )
342    }
343    pub fn query_multi(
344        &mut self,
345        sql: &str,
346        params: &[&(dyn ToSql + Sync)],
347    ) -> NzResult<QueryResult> {
348        self.client.runtime.block_on(
349            self.transaction
350                .as_ref()
351                .expect("active transaction")
352                .query_multi(sql, params),
353        )
354    }
355    pub fn execute(&mut self, sql: &str, params: &[&(dyn ToSql + Sync)]) -> NzResult<i64> {
356        self.client.runtime.block_on(
357            self.transaction
358                .as_ref()
359                .expect("active transaction")
360                .execute(sql, params),
361        )
362    }
363    pub fn batch_execute(&mut self, sql: &str) -> NzResult<()> {
364        self.client.runtime.block_on(
365            self.transaction
366                .as_ref()
367                .expect("active transaction")
368                .batch_execute(sql),
369        )
370    }
371    pub fn commit(mut self) -> NzResult<()> {
372        self.client.runtime.block_on(
373            self.transaction
374                .take()
375                .expect("active transaction")
376                .commit(),
377        )
378    }
379    pub fn rollback(mut self) -> NzResult<()> {
380        self.client.runtime.block_on(
381            self.transaction
382                .take()
383                .expect("active transaction")
384                .rollback(),
385        )
386    }
387}
388impl Drop for Transaction<'_> {
389    fn drop(&mut self) {
390        let entered = self.client.runtime.enter();
391        let transaction = self.transaction.take();
392        let active = transaction.is_some();
393        drop(transaction);
394        drop(entered);
395        if active
396            && self
397                .client
398                .runtime
399                .block_on(tokio_cleanup_barrier(&self.client.client))
400                .is_err()
401        {
402            self.client.client.stop();
403        }
404    }
405}
406
407/// Blocking pool sharing the native semaphore and cancellation-safe lease cleanup.
408pub struct Pool {
409    runtime: std::sync::Arc<tokio::runtime::Runtime>,
410    pool: crate::Pool,
411}
412pub type PoolConfig = crate::PoolConfig;
413impl Pool {
414    pub fn connect(config: PoolConfig) -> NzResult<Self> {
415        let runtime = std::sync::Arc::new(
416            tokio::runtime::Builder::new_multi_thread()
417                .worker_threads(1)
418                .enable_all()
419                .build()?,
420        );
421        let pool = runtime.block_on(crate::Pool::connect(config))?;
422        Ok(Self { runtime, pool })
423    }
424    pub fn get(&self) -> NzResult<PooledConnection> {
425        let lease = self.runtime.block_on(self.pool.get())?;
426        Ok(PooledConnection {
427            runtime: self.runtime.clone(),
428            lease: Some(lease),
429        })
430    }
431    pub fn query(&self, sql: &str, params: &[&dyn ToSql]) -> NzResult<Vec<Row>> {
432        self.runtime.block_on(self.pool.query(sql, params))
433    }
434    pub fn query_multi(&self, sql: &str, params: &[&dyn ToSql]) -> NzResult<QueryResult> {
435        self.runtime.block_on(self.pool.query_multi(sql, params))
436    }
437    pub fn execute(&self, sql: &str, params: &[&dyn ToSql]) -> NzResult<i64> {
438        self.runtime.block_on(self.pool.execute(sql, params))
439    }
440    pub fn close(&self) {
441        self.runtime.block_on(self.pool.close());
442    }
443    pub fn total_count(&self) -> usize {
444        self.runtime.block_on(self.pool.total_count())
445    }
446    pub fn idle_count(&self) -> usize {
447        self.runtime.block_on(self.pool.idle_count())
448    }
449}
450impl Drop for Pool {
451    fn drop(&mut self) {
452        self.close();
453    }
454}
455/// Exclusive blocking pool lease. Drop schedules cleanup on its owning runtime.
456pub struct PooledConnection {
457    runtime: std::sync::Arc<tokio::runtime::Runtime>,
458    lease: Option<crate::async_pool::AsyncPooledConnection>,
459}
460impl PooledConnection {
461    pub fn query(&mut self, sql: &str, params: &[&dyn ToSql]) -> NzResult<Vec<Row>> {
462        self.runtime.block_on(
463            self.lease
464                .as_ref()
465                .expect("active lease")
466                .query(sql, params),
467        )
468    }
469    pub fn query_multi(&mut self, sql: &str, params: &[&dyn ToSql]) -> NzResult<QueryResult> {
470        self.runtime.block_on(
471            self.lease
472                .as_ref()
473                .expect("active lease")
474                .query_multi(sql, params),
475        )
476    }
477    pub fn execute(&mut self, sql: &str, params: &[&dyn ToSql]) -> NzResult<i64> {
478        self.runtime.block_on(
479            self.lease
480                .as_ref()
481                .expect("active lease")
482                .execute(sql, params),
483        )
484    }
485    pub fn batch_execute(&mut self, sql: &str) -> NzResult<()> {
486        self.runtime.block_on(
487            self.lease
488                .as_ref()
489                .expect("active lease")
490                .batch_execute(sql),
491        )
492    }
493    pub fn release(mut self) {
494        if let Some(lease) = self.lease.take() {
495            self.runtime.block_on(lease.release());
496        }
497    }
498}
499impl Drop for PooledConnection {
500    fn drop(&mut self) {
501        let _entered = self.runtime.enter();
502        self.lease.take();
503    }
504}