1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
use crate::{
Turso, TursoColumn, TursoConnection, TursoQueryResult, TursoRow, TursoStatement, TursoTypeInfo,
error::{engine_error, unsupported},
};
use either::Either;
use futures_core::{future::BoxFuture, stream::BoxStream};
use futures_util::{TryStreamExt, stream};
use sqlx_core::{
error::Error,
executor::{Execute, Executor},
logger::QueryLogger,
sql_str::SqlStr,
};
impl<'c> Executor<'c> for &'c mut TursoConnection {
type Database = Turso;
fn fetch_many<'e, 'q: 'e, E>(
self,
query: E,
) -> BoxStream<'e, Result<Either<TursoQueryResult, TursoRow>, Error>>
where
'c: 'e,
E: 'q + Execute<'q, Turso>,
{
// The stream owns the mutable connection borrow, not a public clone.
// Turso prepare ignores trailing statements, so reject batches before
// preparing or executing anything, using its own parser and byte offset.
Box::pin(stream::try_unfold(
(self, Some(query), None),
|(conn, query, active)| async move {
let (statement, mut rows, names, mut logger) = match active {
Some(active) => active,
None => {
let Some(mut query) = query else {
return Ok(None);
};
conn.ready().await?;
let arguments = query
.take_arguments()
.map_err(Error::Encode)?
.unwrap_or_default();
let sql = query.sql();
let logger = QueryLogger::new(sql.clone(), conn.log_settings.clone());
validate_single_statement(
sql.as_str(),
conn.transaction_state == crate::transaction::TransactionState::Active,
)?;
let mut statement = conn
.inner
.prepare(sql.as_str())
.await
.map_err(engine_error)?;
let names = statement.column_names();
// Only an internal statement handle is cloned, not a
// physical connection for another executor/transaction.
// Keep it across every query/step await, including errors.
conn.pending_statement = Some(statement.clone());
let rows = statement
.query(arguments.values)
.await
.map_err(engine_error)?;
(statement, rows, names, logger)
}
};
if let Some(row) = rows.next().await.map_err(engine_error)? {
let row = TursoRow::from_engine(row, &names)?;
logger.increment_rows_returned();
Ok(Some((
Either::Right(row),
(conn, None, Some((statement, rows, names, logger))),
)))
} else {
// Pinned core Statement::n_change is per-statement, not the
// connection's changes(). Read it only after completion, for
// writes with RETURNING as well as non-row-returning writes.
let rows_affected = statement.n_change();
logger.increase_rows_affected(rows_affected);
drop(rows);
drop(statement);
conn.clear_pending_statement()?;
Ok(Some((
Either::Left(TursoQueryResult { rows_affected }),
(conn, None, None),
)))
}
},
))
}
fn fetch_optional<'e, 'q: 'e, E>(
self,
query: E,
) -> BoxFuture<'e, Result<Option<TursoRow>, Error>>
where
'c: 'e,
E: 'q + Execute<'q, Turso>,
{
Box::pin(
self.fetch_many(query)
.try_fold(None, |first, result| async move {
// Drain the engine to completion even after the first row: stopping
// early can otherwise roll back a row-returning write in Turso.
Ok(match (first, result) {
(None, Either::Right(row)) => Some(row),
(first, _) => first,
})
}),
)
}
fn prepare_with<'e>(
self,
sql: SqlStr,
parameters: &'e [TursoTypeInfo],
) -> BoxFuture<'e, Result<TursoStatement, Error>>
where
'c: 'e,
{
Box::pin(async move {
self.ready().await?;
if !parameters.is_empty() {
return Err(unsupported("parameter type hints"));
}
validate_single_statement(
sql.as_str(),
self.transaction_state == crate::transaction::TransactionState::Active,
)?;
let prepared = self
.inner
.prepare(sql.as_str())
.await
.map_err(engine_error)?;
let columns = prepared
.columns()
.into_iter()
.enumerate()
.map(|(ordinal, column)| TursoColumn {
ordinal,
name: column.name().to_owned(),
type_info: TursoTypeInfo::from_decl_type(column.decl_type()),
})
.collect();
Ok(TursoStatement { sql, columns })
})
}
}
fn validate_single_statement(sql: &str, owned_transaction: bool) -> Result<(), Error> {
use turso_parser::ast::{Cmd, Stmt};
let parse_error =
|error: turso::core::LimboError| engine_error(turso::Error::Error(error.to_string()));
let (command, end) = turso::core::dialect::sqlite::parse(sql).map_err(parse_error)?;
// Match actual commands, including END/ROLLBACK TO aliases, not text in
// comments/literals. Public statements also pass here when re-prepared.
if owned_transaction
&& matches!(
command,
Some(Cmd::Stmt(
Stmt::Begin { .. }
| Stmt::Commit { .. }
| Stmt::Rollback { .. }
| Stmt::Savepoint { .. }
| Stmt::Release { .. }
| Stmt::Attach { .. }
| Stmt::Detach { .. }
| Stmt::Pragma { .. }
| Stmt::Vacuum { .. }
))
)
{
return Err(unsupported(
"transaction-escaping SQL inside a SQLx transaction",
));
}
let (trailing, _) = turso::core::dialect::sqlite::parse(&sql[end..]).map_err(parse_error)?;
if trailing.is_some() {
return Err(unsupported("multiple SQL statements"));
}
Ok(())
}