stoolap-python 0.5.0b1__tar.gz → 0.5.0b2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/.github/workflows/ci.yml +3 -3
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/.github/workflows/publish.yml +2 -1
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/Cargo.lock +11 -1
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/Cargo.toml +2 -2
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/PKG-INFO +6 -2
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/README.md +5 -1
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/pyproject.toml +1 -1
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/python/stoolap/__init__.py +3 -5
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/python/stoolap/__init__.pyi +13 -0
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/src/database.rs +36 -11
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/src/statement.rs +4 -4
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/src/transaction.rs +17 -10
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/tests/test_async.py +28 -0
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/tests/test_basic.py +35 -0
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/tests/test_edge_cases.py +16 -0
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/tests/test_transactions.py +23 -0
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/.gitignore +0 -0
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/LICENSE +0 -0
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/benchmark.py +0 -0
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/src/error.rs +0 -0
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/src/lib.rs +0 -0
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/src/value.rs +0 -0
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/tests/test_named_params.py +0 -0
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/tests/test_persistence.py +0 -0
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/tests/test_prepared.py +0 -0
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/tests/test_types.py +0 -0
- {stoolap_python-0.5.0b1 → stoolap_python-0.5.0b2}/tests/test_vector.py +0 -0
|
@@ -52,7 +52,7 @@ jobs:
|
|
|
52
52
|
uses: PyO3/maturin-action@v1
|
|
53
53
|
with:
|
|
54
54
|
target: ${{ matrix.target }}
|
|
55
|
-
args: --release --out dist -i python3.12
|
|
55
|
+
args: --release --out dist -i python3.9 python3.10 python3.11 python3.12 python3.13
|
|
56
56
|
manylinux: auto
|
|
57
57
|
|
|
58
58
|
- name: Upload wheels
|
|
@@ -69,7 +69,7 @@ jobs:
|
|
|
69
69
|
fail-fast: false
|
|
70
70
|
matrix:
|
|
71
71
|
os: [ubuntu-latest, macos-latest, windows-latest]
|
|
72
|
-
python: ['3.12']
|
|
72
|
+
python: ['3.9', '3.12', '3.13']
|
|
73
73
|
runs-on: ${{ matrix.os }}
|
|
74
74
|
steps:
|
|
75
75
|
- uses: actions/checkout@v4
|
|
@@ -99,7 +99,7 @@ jobs:
|
|
|
99
99
|
- name: Install wheel and test dependencies
|
|
100
100
|
shell: bash
|
|
101
101
|
run: |
|
|
102
|
-
pip install dist
|
|
102
|
+
pip install --no-index --find-links dist stoolap-python
|
|
103
103
|
pip install pytest pytest-asyncio
|
|
104
104
|
|
|
105
105
|
- name: Run tests
|
|
@@ -49,7 +49,7 @@ jobs:
|
|
|
49
49
|
uses: PyO3/maturin-action@v1
|
|
50
50
|
with:
|
|
51
51
|
target: ${{ matrix.target }}
|
|
52
|
-
args: --release --out dist -i python3.12
|
|
52
|
+
args: --release --out dist -i python3.9 python3.10 python3.11 python3.12 python3.13
|
|
53
53
|
manylinux: auto
|
|
54
54
|
|
|
55
55
|
- name: Upload wheels
|
|
@@ -110,3 +110,4 @@ jobs:
|
|
|
110
110
|
uses: softprops/action-gh-release@v2
|
|
111
111
|
with:
|
|
112
112
|
generate_release_notes: true
|
|
113
|
+
prerelease: ${{ contains(github.ref_name, 'a') || contains(github.ref_name, 'b') || contains(github.ref_name, 'rc') }}
|
|
@@ -485,6 +485,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
|
485
485
|
checksum = "94f6cbe86ef3bf18998d9df6e0f3fc1050a8c5efa409bf712e661a4366e010fb"
|
|
486
486
|
dependencies = [
|
|
487
487
|
"once_cell",
|
|
488
|
+
"python3-dll-a",
|
|
488
489
|
"target-lexicon",
|
|
489
490
|
]
|
|
490
491
|
|
|
@@ -523,6 +524,15 @@ dependencies = [
|
|
|
523
524
|
"syn",
|
|
524
525
|
]
|
|
525
526
|
|
|
527
|
+
[[package]]
|
|
528
|
+
name = "python3-dll-a"
|
|
529
|
+
version = "0.2.15"
|
|
530
|
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
531
|
+
checksum = "d80ba7540edb18890d444c5aa8e1f1f99b1bdf26fb26ae383135325f4a36042b"
|
|
532
|
+
dependencies = [
|
|
533
|
+
"cc",
|
|
534
|
+
]
|
|
535
|
+
|
|
526
536
|
[[package]]
|
|
527
537
|
name = "quote"
|
|
528
538
|
version = "1.0.45"
|
|
@@ -780,7 +790,7 @@ dependencies = [
|
|
|
780
790
|
|
|
781
791
|
[[package]]
|
|
782
792
|
name = "stoolap-python"
|
|
783
|
-
version = "0.5.0-beta.
|
|
793
|
+
version = "0.5.0-beta.2"
|
|
784
794
|
dependencies = [
|
|
785
795
|
"chrono",
|
|
786
796
|
"pyo3",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[package]
|
|
2
2
|
name = "stoolap-python"
|
|
3
|
-
version = "0.5.0-beta.
|
|
3
|
+
version = "0.5.0-beta.2"
|
|
4
4
|
edition = "2021"
|
|
5
5
|
authors = ["Stoolap Contributors"]
|
|
6
6
|
license = "Apache-2.0"
|
|
@@ -17,7 +17,7 @@ crate-type = ["cdylib"]
|
|
|
17
17
|
|
|
18
18
|
[dependencies]
|
|
19
19
|
stoolap = { git = "https://github.com/stoolap/stoolap", branch = "main", default-features = false, features = ["parallel"] }
|
|
20
|
-
pyo3 = { version = "0.23", features = ["extension-module"] }
|
|
20
|
+
pyo3 = { version = "0.23", features = ["extension-module", "generate-import-lib"] }
|
|
21
21
|
chrono = "0.4"
|
|
22
22
|
|
|
23
23
|
[profile.release]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: stoolap-python
|
|
3
|
-
Version: 0.5.
|
|
3
|
+
Version: 0.5.0b2
|
|
4
4
|
Classifier: Development Status :: 4 - Beta
|
|
5
5
|
Classifier: Intended Audience :: Developers
|
|
6
6
|
Classifier: License :: OSI Approved :: Apache Software License
|
|
@@ -84,6 +84,10 @@ raw = db.query_raw("SELECT id, name FROM users ORDER BY id")
|
|
|
84
84
|
db.close()
|
|
85
85
|
```
|
|
86
86
|
|
|
87
|
+
Each `Database.open(":memory:")` is a private database. To share one in-memory database between opens in the same process, give it a name: `Database.open("memory://name")`.
|
|
88
|
+
|
|
89
|
+
`query()` and `query_one()` key each row by column name, so two result columns with the same name (for example `a.id` and `b.id` in a join) collapse into one key. Alias them, or use `query_raw()`, when that matters.
|
|
90
|
+
|
|
87
91
|
## Prepared Statements
|
|
88
92
|
|
|
89
93
|
Parse SQL once, execute many times with different parameters:
|
|
@@ -128,7 +132,7 @@ except:
|
|
|
128
132
|
raise
|
|
129
133
|
```
|
|
130
134
|
|
|
131
|
-
Transactions support `execute()`, `query()`, `query_one()`, `query_raw()`, and `execute_batch()` with both positional (`$1, $2`) and named (`:key`) parameters.
|
|
135
|
+
Transactions support `execute()`, `query()`, `query_one()`, `query_raw()`, and `execute_batch()` with both positional (`$1, $2`) and named (`:key`) parameters. A statement prepared on the database runs inside a transaction with `execute_prepared(stmt, params)`, `query_prepared`, `query_one_prepared` and `query_raw_prepared`. `rollback()` is a no-op once the transaction has ended, so the handler above never hides the original error.
|
|
132
136
|
|
|
133
137
|
## Batch Execution
|
|
134
138
|
|
|
@@ -55,6 +55,10 @@ raw = db.query_raw("SELECT id, name FROM users ORDER BY id")
|
|
|
55
55
|
db.close()
|
|
56
56
|
```
|
|
57
57
|
|
|
58
|
+
Each `Database.open(":memory:")` is a private database. To share one in-memory database between opens in the same process, give it a name: `Database.open("memory://name")`.
|
|
59
|
+
|
|
60
|
+
`query()` and `query_one()` key each row by column name, so two result columns with the same name (for example `a.id` and `b.id` in a join) collapse into one key. Alias them, or use `query_raw()`, when that matters.
|
|
61
|
+
|
|
58
62
|
## Prepared Statements
|
|
59
63
|
|
|
60
64
|
Parse SQL once, execute many times with different parameters:
|
|
@@ -99,7 +103,7 @@ except:
|
|
|
99
103
|
raise
|
|
100
104
|
```
|
|
101
105
|
|
|
102
|
-
Transactions support `execute()`, `query()`, `query_one()`, `query_raw()`, and `execute_batch()` with both positional (`$1, $2`) and named (`:key`) parameters.
|
|
106
|
+
Transactions support `execute()`, `query()`, `query_one()`, `query_raw()`, and `execute_batch()` with both positional (`$1, $2`) and named (`:key`) parameters. A statement prepared on the database runs inside a transaction with `execute_prepared(stmt, params)`, `query_prepared`, `query_one_prepared` and `query_raw_prepared`. `rollback()` is a no-op once the transaction has ended, so the handler above never hides the original error.
|
|
103
107
|
|
|
104
108
|
## Batch Execution
|
|
105
109
|
|
|
@@ -144,11 +144,9 @@ class AsyncTransaction:
|
|
|
144
144
|
return self
|
|
145
145
|
|
|
146
146
|
async def __aexit__(self, exc_type, exc_val, exc_tb) -> bool:
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
await self.commit()
|
|
151
|
-
return False
|
|
147
|
+
# Same rules as the sync context manager: commit on clean exit,
|
|
148
|
+
# rollback on exception, no-op if the block already ended the tx.
|
|
149
|
+
return await asyncio.to_thread(self._tx.__exit__, exc_type, exc_val, exc_tb)
|
|
152
150
|
|
|
153
151
|
def __repr__(self) -> str:
|
|
154
152
|
return repr(self._tx)
|
|
@@ -21,6 +21,11 @@ __all__: list[str]
|
|
|
21
21
|
|
|
22
22
|
class StoolapError(RuntimeError): ...
|
|
23
23
|
|
|
24
|
+
class Vector:
|
|
25
|
+
def __init__(self, data: Sequence[float]) -> None: ...
|
|
26
|
+
def to_list(self) -> List[float]: ...
|
|
27
|
+
def __len__(self) -> int: ...
|
|
28
|
+
|
|
24
29
|
class Database:
|
|
25
30
|
@staticmethod
|
|
26
31
|
def open(path: str = ":memory:") -> "Database": ...
|
|
@@ -40,6 +45,10 @@ class Transaction:
|
|
|
40
45
|
def query_one(self, sql: str, params: Params = None) -> Optional[Dict[str, Any]]: ...
|
|
41
46
|
def query_raw(self, sql: str, params: Params = None) -> Dict[str, Any]: ...
|
|
42
47
|
def execute_batch(self, sql: str, params_list: Sequence[ParamSet]) -> int: ...
|
|
48
|
+
def execute_prepared(self, stmt: "PreparedStatement", params: Params = None) -> int: ...
|
|
49
|
+
def query_prepared(self, stmt: "PreparedStatement", params: Params = None) -> List[Dict[str, Any]]: ...
|
|
50
|
+
def query_one_prepared(self, stmt: "PreparedStatement", params: Params = None) -> Optional[Dict[str, Any]]: ...
|
|
51
|
+
def query_raw_prepared(self, stmt: "PreparedStatement", params: Params = None) -> Dict[str, Any]: ...
|
|
43
52
|
def commit(self) -> None: ...
|
|
44
53
|
def rollback(self) -> None: ...
|
|
45
54
|
def __enter__(self) -> "Transaction": ...
|
|
@@ -73,6 +82,10 @@ class AsyncTransaction:
|
|
|
73
82
|
async def query_one(self, sql: str, params: Params = None) -> Optional[Dict[str, Any]]: ...
|
|
74
83
|
async def query_raw(self, sql: str, params: Params = None) -> Dict[str, Any]: ...
|
|
75
84
|
async def execute_batch(self, sql: str, params_list: Sequence[ParamSet]) -> int: ...
|
|
85
|
+
async def execute_prepared(self, stmt: Union["AsyncPreparedStatement", PreparedStatement], params: Params = None) -> int: ...
|
|
86
|
+
async def query_prepared(self, stmt: Union["AsyncPreparedStatement", PreparedStatement], params: Params = None) -> List[Dict[str, Any]]: ...
|
|
87
|
+
async def query_one_prepared(self, stmt: Union["AsyncPreparedStatement", PreparedStatement], params: Params = None) -> Optional[Dict[str, Any]]: ...
|
|
88
|
+
async def query_raw_prepared(self, stmt: Union["AsyncPreparedStatement", PreparedStatement], params: Params = None) -> Dict[str, Any]: ...
|
|
76
89
|
async def commit(self) -> None: ...
|
|
77
90
|
async def rollback(self) -> None: ...
|
|
78
91
|
async def __aenter__(self) -> "AsyncTransaction": ...
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
|
|
15
15
|
use pyo3::prelude::*;
|
|
16
16
|
use pyo3::types::{PyDict, PyList, PyString};
|
|
17
|
+
use std::sync::atomic::{AtomicU64, Ordering};
|
|
17
18
|
use std::sync::Arc;
|
|
18
19
|
|
|
19
20
|
use stoolap::api::Database as ApiDatabase;
|
|
@@ -36,13 +37,14 @@ impl Database {
|
|
|
36
37
|
/// Open a database connection.
|
|
37
38
|
///
|
|
38
39
|
/// Accepts:
|
|
39
|
-
/// - `:memory:` or empty string for in-memory database
|
|
40
|
-
/// - `memory
|
|
40
|
+
/// - `:memory:` or empty string for a private in-memory database
|
|
41
|
+
/// - `memory://name` for an in-memory database shared by every open of that name
|
|
41
42
|
/// - `./mydb` or `file:///path/to/db` for file-based database
|
|
42
43
|
#[staticmethod]
|
|
43
|
-
|
|
44
|
+
#[pyo3(signature = (path=":memory:"))]
|
|
45
|
+
fn open(py: Python<'_>, path: &str) -> PyResult<Self> {
|
|
44
46
|
let dsn = translate_path(path);
|
|
45
|
-
let db = ApiDatabase::open(&dsn).map_err(to_py)?;
|
|
47
|
+
let db = py.allow_threads(|| ApiDatabase::open(&dsn)).map_err(to_py)?;
|
|
46
48
|
Ok(Self { db: Arc::new(db) })
|
|
47
49
|
}
|
|
48
50
|
|
|
@@ -137,13 +139,14 @@ impl Database {
|
|
|
137
139
|
&self,
|
|
138
140
|
py: Python<'_>,
|
|
139
141
|
sql: &str,
|
|
140
|
-
params_list: &Bound<'_,
|
|
142
|
+
params_list: &Bound<'_, PyAny>,
|
|
141
143
|
) -> PyResult<i64> {
|
|
142
144
|
let sql = sql.to_string();
|
|
143
145
|
|
|
144
146
|
// Parse all param sets on the Python thread (need GIL)
|
|
145
|
-
let mut all_params = Vec::with_capacity(params_list.len());
|
|
146
|
-
for item in params_list.
|
|
147
|
+
let mut all_params = Vec::with_capacity(params_list.len().unwrap_or(0));
|
|
148
|
+
for item in params_list.try_iter()? {
|
|
149
|
+
let item = item?;
|
|
147
150
|
let bind = parse_params(Some(&item))?;
|
|
148
151
|
match bind {
|
|
149
152
|
BindParams::Positional(p) => all_params.push(p),
|
|
@@ -171,8 +174,8 @@ impl Database {
|
|
|
171
174
|
/// Create a prepared statement.
|
|
172
175
|
///
|
|
173
176
|
/// Parses SQL once and caches the execution plan.
|
|
174
|
-
fn prepare(&self, sql: &str) -> PyResult<PreparedStatement> {
|
|
175
|
-
PreparedStatement::new(Arc::clone(&self.db), sql)
|
|
177
|
+
fn prepare(&self, py: Python<'_>, sql: &str) -> PyResult<PreparedStatement> {
|
|
178
|
+
py.allow_threads(|| PreparedStatement::new(Arc::clone(&self.db), sql))
|
|
176
179
|
}
|
|
177
180
|
|
|
178
181
|
/// Begin a transaction.
|
|
@@ -192,17 +195,39 @@ impl Database {
|
|
|
192
195
|
}
|
|
193
196
|
|
|
194
197
|
/// Translate user-friendly paths to Stoolap DSN format.
|
|
198
|
+
///
|
|
199
|
+
/// `:memory:` gets a DSN unique to this open, so two `:memory:` databases in
|
|
200
|
+
/// one process never share tables and closing one leaves the other open.
|
|
201
|
+
/// Anything that already carries a scheme is passed through untouched and
|
|
202
|
+
/// left to the engine to validate; a bare path becomes `file://path`.
|
|
195
203
|
fn translate_path(path: &str) -> String {
|
|
204
|
+
static MEMORY_OPENS: AtomicU64 = AtomicU64::new(0);
|
|
205
|
+
|
|
196
206
|
let trimmed = path.trim();
|
|
197
207
|
if trimmed.is_empty() || trimmed == ":memory:" {
|
|
198
|
-
|
|
199
|
-
|
|
208
|
+
let n = MEMORY_OPENS.fetch_add(1, Ordering::Relaxed);
|
|
209
|
+
format!("memory://py-{}-{n}", std::process::id())
|
|
210
|
+
} else if has_scheme(trimmed) {
|
|
200
211
|
trimmed.to_string()
|
|
201
212
|
} else {
|
|
202
213
|
format!("file://{trimmed}")
|
|
203
214
|
}
|
|
204
215
|
}
|
|
205
216
|
|
|
217
|
+
/// True when `s` starts with an RFC 3986 scheme followed by `://`.
|
|
218
|
+
fn has_scheme(s: &str) -> bool {
|
|
219
|
+
match s.find("://") {
|
|
220
|
+
Some(idx) if idx > 0 => {
|
|
221
|
+
let scheme = &s[..idx];
|
|
222
|
+
scheme.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
|
|
223
|
+
&& scheme
|
|
224
|
+
.chars()
|
|
225
|
+
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
|
|
226
|
+
}
|
|
227
|
+
_ => false,
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
206
231
|
/// Convert named params to stoolap NamedParams.
|
|
207
232
|
pub fn to_named_params(named: &[(String, stoolap::core::Value)]) -> stoolap::api::NamedParams {
|
|
208
233
|
let mut np = stoolap::api::NamedParams::new();
|
|
@@ -13,7 +13,6 @@
|
|
|
13
13
|
// limitations under the License.
|
|
14
14
|
|
|
15
15
|
use pyo3::prelude::*;
|
|
16
|
-
use pyo3::types::PyList;
|
|
17
16
|
use std::sync::Arc;
|
|
18
17
|
|
|
19
18
|
use stoolap::api::{Database as ApiDatabase, Statement as ApiStatement};
|
|
@@ -99,10 +98,11 @@ impl PreparedStatement {
|
|
|
99
98
|
///
|
|
100
99
|
/// Auto-wraps in a transaction. Returns total rows affected.
|
|
101
100
|
#[pyo3(signature = (params_list,))]
|
|
102
|
-
fn execute_batch(&self, py: Python<'_>, params_list: &Bound<'_,
|
|
101
|
+
fn execute_batch(&self, py: Python<'_>, params_list: &Bound<'_, PyAny>) -> PyResult<i64> {
|
|
103
102
|
// Parse all param sets while holding GIL
|
|
104
|
-
let mut all_params = Vec::with_capacity(params_list.len());
|
|
105
|
-
for item in params_list.
|
|
103
|
+
let mut all_params = Vec::with_capacity(params_list.len().unwrap_or(0));
|
|
104
|
+
for item in params_list.try_iter()? {
|
|
105
|
+
let item = item?;
|
|
106
106
|
let bind = parse_params(Some(&item))?;
|
|
107
107
|
match bind {
|
|
108
108
|
BindParams::Positional(p) => all_params.push(p),
|
|
@@ -13,7 +13,6 @@
|
|
|
13
13
|
// limitations under the License.
|
|
14
14
|
|
|
15
15
|
use pyo3::prelude::*;
|
|
16
|
-
use pyo3::types::PyList;
|
|
17
16
|
use std::sync::{Arc, Mutex};
|
|
18
17
|
|
|
19
18
|
use stoolap::api::{Database as ApiDatabase, Transaction as ApiTransaction};
|
|
@@ -145,13 +144,14 @@ impl Transaction {
|
|
|
145
144
|
&self,
|
|
146
145
|
py: Python<'_>,
|
|
147
146
|
sql: &str,
|
|
148
|
-
params_list: &Bound<'_,
|
|
147
|
+
params_list: &Bound<'_, PyAny>,
|
|
149
148
|
) -> PyResult<i64> {
|
|
150
149
|
let sql = sql.to_string();
|
|
151
150
|
|
|
152
151
|
// Parse all param sets while holding GIL
|
|
153
|
-
let mut all_params = Vec::with_capacity(params_list.len());
|
|
154
|
-
for item in params_list.
|
|
152
|
+
let mut all_params = Vec::with_capacity(params_list.len().unwrap_or(0));
|
|
153
|
+
for item in params_list.try_iter()? {
|
|
154
|
+
let item = item?;
|
|
155
155
|
let bind = parse_params(Some(&item))?;
|
|
156
156
|
match bind {
|
|
157
157
|
BindParams::Positional(p) => all_params.push(p),
|
|
@@ -260,30 +260,37 @@ impl Transaction {
|
|
|
260
260
|
}
|
|
261
261
|
|
|
262
262
|
/// Commit the transaction.
|
|
263
|
+
///
|
|
264
|
+
/// On failure the transaction stays active so it can still be rolled back.
|
|
263
265
|
fn commit(&self, py: Python<'_>) -> PyResult<()> {
|
|
264
266
|
py.allow_threads(|| {
|
|
265
267
|
let mut guard = self
|
|
266
268
|
.tx
|
|
267
269
|
.lock()
|
|
268
270
|
.map_err(|_| crate::error::StoolapError::new_err("Transaction lock poisoned"))?;
|
|
269
|
-
let
|
|
271
|
+
let tx = guard.as_mut().ok_or_else(|| {
|
|
270
272
|
crate::error::StoolapError::new_err("Transaction is no longer active")
|
|
271
273
|
})?;
|
|
272
|
-
tx.commit().map_err(to_py)
|
|
274
|
+
tx.commit().map_err(to_py)?;
|
|
275
|
+
*guard = None;
|
|
276
|
+
Ok(())
|
|
273
277
|
})
|
|
274
278
|
}
|
|
275
279
|
|
|
276
280
|
/// Rollback the transaction.
|
|
281
|
+
///
|
|
282
|
+
/// A no-op once the transaction has been committed or rolled back, so an
|
|
283
|
+
/// `except: tx.rollback(); raise` handler never hides the original error.
|
|
277
284
|
fn rollback(&self, py: Python<'_>) -> PyResult<()> {
|
|
278
285
|
py.allow_threads(|| {
|
|
279
286
|
let mut guard = self
|
|
280
287
|
.tx
|
|
281
288
|
.lock()
|
|
282
289
|
.map_err(|_| crate::error::StoolapError::new_err("Transaction lock poisoned"))?;
|
|
283
|
-
let mut tx = guard.take()
|
|
284
|
-
|
|
285
|
-
}
|
|
286
|
-
|
|
290
|
+
if let Some(mut tx) = guard.take() {
|
|
291
|
+
tx.rollback().map_err(to_py)?;
|
|
292
|
+
}
|
|
293
|
+
Ok(())
|
|
287
294
|
})
|
|
288
295
|
}
|
|
289
296
|
|
|
@@ -131,3 +131,31 @@ async def test_async_execute_batch():
|
|
|
131
131
|
rows = await db.query("SELECT * FROM users ORDER BY id")
|
|
132
132
|
assert len(rows) == 3
|
|
133
133
|
await db.close()
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@pytest.mark.asyncio
|
|
137
|
+
async def test_async_manual_commit_inside_context():
|
|
138
|
+
db = await AsyncDatabase.open(":memory:")
|
|
139
|
+
await db.exec("CREATE TABLE t (id INTEGER PRIMARY KEY)")
|
|
140
|
+
|
|
141
|
+
async with await db.begin() as tx:
|
|
142
|
+
await tx.execute("INSERT INTO t VALUES ($1)", [1])
|
|
143
|
+
await tx.commit() # leaving the block afterwards must not raise
|
|
144
|
+
|
|
145
|
+
assert len(await db.query("SELECT * FROM t")) == 1
|
|
146
|
+
await db.close()
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@pytest.mark.asyncio
|
|
150
|
+
async def test_async_rollback_then_raise_keeps_original_error():
|
|
151
|
+
db = await AsyncDatabase.open(":memory:")
|
|
152
|
+
await db.exec("CREATE TABLE t (id INTEGER PRIMARY KEY)")
|
|
153
|
+
|
|
154
|
+
with pytest.raises(ValueError, match="boom"):
|
|
155
|
+
async with await db.begin() as tx:
|
|
156
|
+
await tx.execute("INSERT INTO t VALUES ($1)", [1])
|
|
157
|
+
await tx.rollback()
|
|
158
|
+
raise ValueError("boom")
|
|
159
|
+
|
|
160
|
+
assert await db.query("SELECT * FROM t") == []
|
|
161
|
+
await db.close()
|
|
@@ -24,6 +24,41 @@ def test_open_memory():
|
|
|
24
24
|
db.close()
|
|
25
25
|
|
|
26
26
|
|
|
27
|
+
def test_open_defaults_to_memory():
|
|
28
|
+
db = Database.open()
|
|
29
|
+
db.exec("CREATE TABLE t (id INTEGER PRIMARY KEY)")
|
|
30
|
+
assert db.query("SELECT * FROM t") == []
|
|
31
|
+
db.close()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_memory_databases_are_private():
|
|
35
|
+
a = Database.open(":memory:")
|
|
36
|
+
b = Database.open(":memory:")
|
|
37
|
+
a.exec("CREATE TABLE only_in_a (id INTEGER PRIMARY KEY)")
|
|
38
|
+
|
|
39
|
+
with pytest.raises(StoolapError):
|
|
40
|
+
b.query("SELECT * FROM only_in_a")
|
|
41
|
+
|
|
42
|
+
b.close()
|
|
43
|
+
assert a.query("SELECT * FROM only_in_a") == [] # a outlives b.close()
|
|
44
|
+
a.close()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def test_named_memory_database_is_shared():
|
|
48
|
+
a = Database.open("memory://shared-by-name")
|
|
49
|
+
b = Database.open("memory://shared-by-name")
|
|
50
|
+
a.exec("CREATE TABLE shared (id INTEGER PRIMARY KEY)")
|
|
51
|
+
assert b.query("SELECT * FROM shared") == []
|
|
52
|
+
a.close()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_unknown_scheme_is_rejected(tmp_path, monkeypatch):
|
|
56
|
+
monkeypatch.chdir(tmp_path)
|
|
57
|
+
with pytest.raises(StoolapError, match="Unsupported scheme"):
|
|
58
|
+
Database.open("sqlite:///tmp/x")
|
|
59
|
+
assert list(tmp_path.iterdir()) == [] # no 'sqlite:' directory created
|
|
60
|
+
|
|
61
|
+
|
|
27
62
|
def test_open_empty_string():
|
|
28
63
|
db = Database.open("")
|
|
29
64
|
assert db is not None
|
|
@@ -287,3 +287,19 @@ async def test_async_tx_rollback_on_exception():
|
|
|
287
287
|
rows = await db.query("SELECT * FROM t")
|
|
288
288
|
assert len(rows) == 0
|
|
289
289
|
await db.close()
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def test_execute_batch_accepts_any_iterable():
|
|
293
|
+
db = Database.open(":memory:")
|
|
294
|
+
db.exec("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)")
|
|
295
|
+
|
|
296
|
+
assert db.execute_batch("INSERT INTO t VALUES ($1, $2)", ((1, "a"), (2, "b"))) == 2
|
|
297
|
+
|
|
298
|
+
stmt = db.prepare("INSERT INTO t VALUES ($1, $2)")
|
|
299
|
+
assert stmt.execute_batch(row for row in [(3, "c"), (4, "d")]) == 2
|
|
300
|
+
|
|
301
|
+
with db.begin() as tx:
|
|
302
|
+
assert tx.execute_batch("INSERT INTO t VALUES ($1, $2)", ((5, "e"),)) == 1
|
|
303
|
+
|
|
304
|
+
assert len(db.query("SELECT * FROM t")) == 5
|
|
305
|
+
db.close()
|
|
@@ -126,3 +126,26 @@ def test_tx_positional_params():
|
|
|
126
126
|
assert rows[0]["name"] == "Alice"
|
|
127
127
|
assert rows[1]["name"] == "Bob"
|
|
128
128
|
db.close()
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def test_rollback_is_idempotent():
|
|
132
|
+
db = Database.open(":memory:")
|
|
133
|
+
db.exec("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
|
|
134
|
+
|
|
135
|
+
tx = db.begin()
|
|
136
|
+
tx.execute("INSERT INTO users VALUES ($1, $2)", [1, "Alice"])
|
|
137
|
+
tx.rollback()
|
|
138
|
+
tx.rollback() # second rollback is a no-op
|
|
139
|
+
assert db.query("SELECT * FROM users") == []
|
|
140
|
+
|
|
141
|
+
# rollback after commit is a no-op too, so the documented
|
|
142
|
+
# `except: tx.rollback(); raise` pattern never hides the real error
|
|
143
|
+
tx = db.begin()
|
|
144
|
+
tx.execute("INSERT INTO users VALUES ($1, $2)", [1, "Alice"])
|
|
145
|
+
tx.commit()
|
|
146
|
+
tx.rollback()
|
|
147
|
+
assert len(db.query("SELECT * FROM users")) == 1
|
|
148
|
+
|
|
149
|
+
with pytest.raises(StoolapError, match="no longer active"):
|
|
150
|
+
tx.commit()
|
|
151
|
+
db.close()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|