stoolap-python 0.4.2__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.
Files changed (27) hide show
  1. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/.github/workflows/ci.yml +3 -3
  2. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/.github/workflows/publish.yml +2 -1
  3. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/Cargo.lock +12 -209
  4. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/Cargo.toml +3 -3
  5. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/PKG-INFO +6 -2
  6. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/README.md +5 -1
  7. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/pyproject.toml +1 -1
  8. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/python/stoolap/__init__.py +3 -5
  9. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/python/stoolap/__init__.pyi +13 -0
  10. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/src/database.rs +39 -22
  11. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/src/statement.rs +21 -34
  12. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/src/transaction.rs +36 -39
  13. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/tests/test_async.py +28 -0
  14. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/tests/test_basic.py +35 -0
  15. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/tests/test_edge_cases.py +16 -0
  16. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/tests/test_named_params.py +14 -1
  17. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/tests/test_transactions.py +23 -0
  18. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/tests/test_types.py +10 -10
  19. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/.gitignore +0 -0
  20. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/LICENSE +0 -0
  21. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/benchmark.py +0 -0
  22. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/src/error.rs +0 -0
  23. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/src/lib.rs +0 -0
  24. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/src/value.rs +0 -0
  25. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/tests/test_persistence.py +0 -0
  26. {stoolap_python-0.4.2 → stoolap_python-0.5.0b2}/tests/test_prepared.py +0 -0
  27. {stoolap_python-0.4.2 → 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/*.whl
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') }}
@@ -39,12 +39,6 @@ dependencies = [
39
39
  "libc",
40
40
  ]
41
41
 
42
- [[package]]
43
- name = "anyhow"
44
- version = "1.0.102"
45
- source = "registry+https://github.com/rust-lang/crates.io-index"
46
- checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
47
-
48
42
  [[package]]
49
43
  name = "autocfg"
50
44
  version = "1.5.0"
@@ -84,12 +78,6 @@ version = "1.5.0"
84
78
  source = "registry+https://github.com/rust-lang/crates.io-index"
85
79
  checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
86
80
 
87
- [[package]]
88
- name = "bytes"
89
- version = "1.11.1"
90
- source = "registry+https://github.com/rust-lang/crates.io-index"
91
- checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
92
-
93
81
  [[package]]
94
82
  name = "cc"
95
83
  version = "1.2.56"
@@ -144,28 +132,6 @@ dependencies = [
144
132
  "cfg-if",
145
133
  ]
146
134
 
147
- [[package]]
148
- name = "crossbeam"
149
- version = "0.8.4"
150
- source = "registry+https://github.com/rust-lang/crates.io-index"
151
- checksum = "1137cd7e7fc0fb5d3c5a8678be38ec56e819125d8d7907411fe24ccb943faca8"
152
- dependencies = [
153
- "crossbeam-channel",
154
- "crossbeam-deque",
155
- "crossbeam-epoch",
156
- "crossbeam-queue",
157
- "crossbeam-utils",
158
- ]
159
-
160
- [[package]]
161
- name = "crossbeam-channel"
162
- version = "0.5.15"
163
- source = "registry+https://github.com/rust-lang/crates.io-index"
164
- checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2"
165
- dependencies = [
166
- "crossbeam-utils",
167
- ]
168
-
169
135
  [[package]]
170
136
  name = "crossbeam-deque"
171
137
  version = "0.8.6"
@@ -185,15 +151,6 @@ dependencies = [
185
151
  "crossbeam-utils",
186
152
  ]
187
153
 
188
- [[package]]
189
- name = "crossbeam-queue"
190
- version = "0.3.12"
191
- source = "registry+https://github.com/rust-lang/crates.io-index"
192
- checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115"
193
- dependencies = [
194
- "crossbeam-utils",
195
- ]
196
-
197
154
  [[package]]
198
155
  name = "crossbeam-utils"
199
156
  version = "0.8.21"
@@ -231,20 +188,6 @@ dependencies = [
231
188
  "memchr",
232
189
  ]
233
190
 
234
- [[package]]
235
- name = "dashmap"
236
- version = "6.1.0"
237
- source = "registry+https://github.com/rust-lang/crates.io-index"
238
- checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf"
239
- dependencies = [
240
- "cfg-if",
241
- "crossbeam-utils",
242
- "hashbrown 0.14.5",
243
- "lock_api",
244
- "once_cell",
245
- "parking_lot_core",
246
- ]
247
-
248
191
  [[package]]
249
192
  name = "digest"
250
193
  version = "0.10.7"
@@ -316,12 +259,6 @@ dependencies = [
316
259
  "wasm-bindgen",
317
260
  ]
318
261
 
319
- [[package]]
320
- name = "hashbrown"
321
- version = "0.14.5"
322
- source = "registry+https://github.com/rust-lang/crates.io-index"
323
- checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
324
-
325
262
  [[package]]
326
263
  name = "hashbrown"
327
264
  version = "0.16.1"
@@ -372,16 +309,6 @@ dependencies = [
372
309
  "cc",
373
310
  ]
374
311
 
375
- [[package]]
376
- name = "indexmap"
377
- version = "2.13.0"
378
- source = "registry+https://github.com/rust-lang/crates.io-index"
379
- checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"
380
- dependencies = [
381
- "equivalent",
382
- "hashbrown 0.16.1",
383
- ]
384
-
385
312
  [[package]]
386
313
  name = "indoc"
387
314
  version = "2.0.7"
@@ -407,12 +334,6 @@ dependencies = [
407
334
  "wasm-bindgen",
408
335
  ]
409
336
 
410
- [[package]]
411
- name = "lazy_static"
412
- version = "1.5.0"
413
- source = "registry+https://github.com/rust-lang/crates.io-index"
414
- checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
415
-
416
337
  [[package]]
417
338
  name = "libc"
418
339
  version = "0.2.183"
@@ -452,15 +373,6 @@ dependencies = [
452
373
  "twox-hash",
453
374
  ]
454
375
 
455
- [[package]]
456
- name = "matchers"
457
- version = "0.2.0"
458
- source = "registry+https://github.com/rust-lang/crates.io-index"
459
- checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
460
- dependencies = [
461
- "regex-automata",
462
- ]
463
-
464
376
  [[package]]
465
377
  name = "md-5"
466
378
  version = "0.10.6"
@@ -486,15 +398,6 @@ dependencies = [
486
398
  "autocfg",
487
399
  ]
488
400
 
489
- [[package]]
490
- name = "nu-ansi-term"
491
- version = "0.50.3"
492
- source = "registry+https://github.com/rust-lang/crates.io-index"
493
- checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
494
- dependencies = [
495
- "windows-sys",
496
- ]
497
-
498
401
  [[package]]
499
402
  name = "num-traits"
500
403
  version = "0.2.19"
@@ -510,15 +413,6 @@ version = "1.21.4"
510
413
  source = "registry+https://github.com/rust-lang/crates.io-index"
511
414
  checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
512
415
 
513
- [[package]]
514
- name = "ordered-float"
515
- version = "5.1.0"
516
- source = "registry+https://github.com/rust-lang/crates.io-index"
517
- checksum = "7f4779c6901a562440c3786d08192c6fbda7c1c2060edd10006b05ee35d10f2d"
518
- dependencies = [
519
- "num-traits",
520
- ]
521
-
522
416
  [[package]]
523
417
  name = "parking_lot"
524
418
  version = "0.12.5"
@@ -542,12 +436,6 @@ dependencies = [
542
436
  "windows-link",
543
437
  ]
544
438
 
545
- [[package]]
546
- name = "pin-project-lite"
547
- version = "0.2.17"
548
- source = "registry+https://github.com/rust-lang/crates.io-index"
549
- checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
550
-
551
439
  [[package]]
552
440
  name = "portable-atomic"
553
441
  version = "1.13.1"
@@ -597,6 +485,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
597
485
  checksum = "94f6cbe86ef3bf18998d9df6e0f3fc1050a8c5efa409bf712e661a4366e010fb"
598
486
  dependencies = [
599
487
  "once_cell",
488
+ "python3-dll-a",
600
489
  "target-lexicon",
601
490
  ]
602
491
 
@@ -635,6 +524,15 @@ dependencies = [
635
524
  "syn",
636
525
  ]
637
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
+
638
536
  [[package]]
639
537
  name = "quote"
640
538
  version = "1.0.45"
@@ -842,15 +740,6 @@ dependencies = [
842
740
  "digest",
843
741
  ]
844
742
 
845
- [[package]]
846
- name = "sharded-slab"
847
- version = "0.1.7"
848
- source = "registry+https://github.com/rust-lang/crates.io-index"
849
- checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
850
- dependencies = [
851
- "lazy_static",
852
- ]
853
-
854
743
  [[package]]
855
744
  name = "shlex"
856
745
  version = "1.3.0"
@@ -866,28 +755,20 @@ checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
866
755
  [[package]]
867
756
  name = "stoolap"
868
757
  version = "0.4.2"
869
- source = "registry+https://github.com/rust-lang/crates.io-index"
870
- checksum = "88932817e3bb9551486e091b0c6400323086409cca8c35a37c3a68afe089e083"
758
+ source = "git+https://github.com/stoolap/stoolap?branch=main#8fe13cf765ee1a0b4e2e438391296c2f78c3123a"
871
759
  dependencies = [
872
760
  "ahash",
873
- "anyhow",
874
- "bytes",
875
761
  "chrono",
876
762
  "crc32fast",
877
- "crossbeam",
878
763
  "csv",
879
- "dashmap",
880
764
  "getrandom 0.2.17",
881
765
  "getrandom 0.3.4",
882
766
  "hashbrown 0.16.1",
883
- "indexmap",
884
- "js-sys",
885
767
  "libc",
886
768
  "lru",
887
769
  "lz4_flex",
888
770
  "md-5",
889
771
  "memchr",
890
- "ordered-float",
891
772
  "parking_lot",
892
773
  "radsort",
893
774
  "rand",
@@ -901,8 +782,6 @@ dependencies = [
901
782
  "sha2",
902
783
  "smallvec",
903
784
  "thiserror",
904
- "tracing",
905
- "tracing-subscriber",
906
785
  "wasm-bindgen",
907
786
  "web-sys",
908
787
  "web-time",
@@ -911,7 +790,7 @@ dependencies = [
911
790
 
912
791
  [[package]]
913
792
  name = "stoolap-python"
914
- version = "0.4.2"
793
+ version = "0.5.0-beta.2"
915
794
  dependencies = [
916
795
  "chrono",
917
796
  "pyo3",
@@ -955,76 +834,6 @@ dependencies = [
955
834
  "syn",
956
835
  ]
957
836
 
958
- [[package]]
959
- name = "thread_local"
960
- version = "1.1.9"
961
- source = "registry+https://github.com/rust-lang/crates.io-index"
962
- checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185"
963
- dependencies = [
964
- "cfg-if",
965
- ]
966
-
967
- [[package]]
968
- name = "tracing"
969
- version = "0.1.44"
970
- source = "registry+https://github.com/rust-lang/crates.io-index"
971
- checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
972
- dependencies = [
973
- "pin-project-lite",
974
- "tracing-attributes",
975
- "tracing-core",
976
- ]
977
-
978
- [[package]]
979
- name = "tracing-attributes"
980
- version = "0.1.31"
981
- source = "registry+https://github.com/rust-lang/crates.io-index"
982
- checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
983
- dependencies = [
984
- "proc-macro2",
985
- "quote",
986
- "syn",
987
- ]
988
-
989
- [[package]]
990
- name = "tracing-core"
991
- version = "0.1.36"
992
- source = "registry+https://github.com/rust-lang/crates.io-index"
993
- checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
994
- dependencies = [
995
- "once_cell",
996
- "valuable",
997
- ]
998
-
999
- [[package]]
1000
- name = "tracing-log"
1001
- version = "0.2.0"
1002
- source = "registry+https://github.com/rust-lang/crates.io-index"
1003
- checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
1004
- dependencies = [
1005
- "log",
1006
- "once_cell",
1007
- "tracing-core",
1008
- ]
1009
-
1010
- [[package]]
1011
- name = "tracing-subscriber"
1012
- version = "0.3.22"
1013
- source = "registry+https://github.com/rust-lang/crates.io-index"
1014
- checksum = "2f30143827ddab0d256fd843b7a66d164e9f271cfa0dde49142c5ca0ca291f1e"
1015
- dependencies = [
1016
- "matchers",
1017
- "nu-ansi-term",
1018
- "once_cell",
1019
- "regex-automata",
1020
- "sharded-slab",
1021
- "smallvec",
1022
- "thread_local",
1023
- "tracing",
1024
- "tracing-core",
1025
- "tracing-log",
1026
- ]
1027
-
1028
837
  [[package]]
1029
838
  name = "twox-hash"
1030
839
  version = "2.1.2"
@@ -1049,12 +858,6 @@ version = "0.2.4"
1049
858
  source = "registry+https://github.com/rust-lang/crates.io-index"
1050
859
  checksum = "7264e107f553ccae879d21fbea1d6724ac785e8c3bfc762137959b5802826ef3"
1051
860
 
1052
- [[package]]
1053
- name = "valuable"
1054
- version = "0.1.1"
1055
- source = "registry+https://github.com/rust-lang/crates.io-index"
1056
- checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
1057
-
1058
861
  [[package]]
1059
862
  name = "version_check"
1060
863
  version = "0.9.5"
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "stoolap-python"
3
- version = "0.4.2"
3
+ version = "0.5.0-beta.2"
4
4
  edition = "2021"
5
5
  authors = ["Stoolap Contributors"]
6
6
  license = "Apache-2.0"
@@ -16,8 +16,8 @@ name = "_stoolap"
16
16
  crate-type = ["cdylib"]
17
17
 
18
18
  [dependencies]
19
- stoolap = { version = "0.4.2", default-features = false, features = ["parallel"] }
20
- pyo3 = { version = "0.23", features = ["extension-module"] }
19
+ stoolap = { git = "https://github.com/stoolap/stoolap", branch = "main", default-features = false, features = ["parallel"] }
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.4.2
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
 
@@ -4,7 +4,7 @@ build-backend = "maturin"
4
4
 
5
5
  [project]
6
6
  name = "stoolap-python"
7
- version = "0.4.2"
7
+ version = "0.5.0b2"
8
8
  description = "High-performance Python driver for Stoolap embedded SQL database"
9
9
  readme = "README.md"
10
10
  license = { text = "Apache-2.0" }
@@ -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
- if exc_type is not None:
148
- await self.rollback()
149
- else:
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://` for in-memory database
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
- fn open(path: &str) -> PyResult<Self> {
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<'_, PyList>,
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.iter() {
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),
@@ -157,19 +160,11 @@ impl Database {
157
160
 
158
161
  // Execute without GIL
159
162
  py.allow_threads(|| {
160
- use stoolap::parser::Parser;
161
- let mut parser = Parser::new(&sql);
162
- let program = parser.parse_program().map_err(|e| {
163
- crate::error::StoolapError::new_err(e.to_string())
164
- })?;
165
- let stmt = program.statements.first().ok_or_else(|| {
166
- crate::error::StoolapError::new_err("No SQL statement found")
167
- })?;
168
-
163
+ let stmt = self.db.prepare(&sql).map_err(to_py)?;
169
164
  let mut tx = self.db.begin().map_err(to_py)?;
170
165
  let mut total = 0i64;
171
166
  for params in all_params {
172
- total += tx.execute_prepared(stmt, params).map_err(to_py)?;
167
+ total += stmt.execute_in(&mut tx, params).map_err(to_py)?;
173
168
  }
174
169
  tx.commit().map_err(to_py)?;
175
170
  Ok(total)
@@ -179,14 +174,14 @@ impl Database {
179
174
  /// Create a prepared statement.
180
175
  ///
181
176
  /// Parses SQL once and caches the execution plan.
182
- fn prepare(&self, sql: &str) -> PyResult<PreparedStatement> {
183
- 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))
184
179
  }
185
180
 
186
181
  /// Begin a transaction.
187
182
  fn begin(&self, py: Python<'_>) -> PyResult<Transaction> {
188
183
  let tx = py.allow_threads(|| self.db.begin().map_err(to_py))?;
189
- Ok(Transaction::from_tx(tx))
184
+ Ok(Transaction::from_tx(tx, Arc::clone(&self.db)))
190
185
  }
191
186
 
192
187
  /// Close the database connection.
@@ -200,17 +195,39 @@ impl Database {
200
195
  }
201
196
 
202
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`.
203
203
  fn translate_path(path: &str) -> String {
204
+ static MEMORY_OPENS: AtomicU64 = AtomicU64::new(0);
205
+
204
206
  let trimmed = path.trim();
205
207
  if trimmed.is_empty() || trimmed == ":memory:" {
206
- "memory://".to_string()
207
- } else if trimmed.starts_with("memory://") || trimmed.starts_with("file://") {
208
+ let n = MEMORY_OPENS.fetch_add(1, Ordering::Relaxed);
209
+ format!("memory://py-{}-{n}", std::process::id())
210
+ } else if has_scheme(trimmed) {
208
211
  trimmed.to_string()
209
212
  } else {
210
213
  format!("file://{trimmed}")
211
214
  }
212
215
  }
213
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
+
214
231
  /// Convert named params to stoolap NamedParams.
215
232
  pub fn to_named_params(named: &[(String, stoolap::core::Value)]) -> stoolap::api::NamedParams {
216
233
  let mut np = stoolap::api::NamedParams::new();
@@ -13,11 +13,9 @@
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
- use stoolap::api::Database as ApiDatabase;
20
- use stoolap::CachedPlanRef;
18
+ use stoolap::api::{Database as ApiDatabase, Statement as ApiStatement};
21
19
 
22
20
  use crate::database::{first_row_to_dict, rows_to_dicts, rows_to_raw, to_named_params};
23
21
  use crate::error::to_py;
@@ -29,22 +27,17 @@ use crate::value::{parse_params, BindParams};
29
27
  #[pyclass]
30
28
  pub struct PreparedStatement {
31
29
  db: Arc<ApiDatabase>,
32
- sql_text: String,
33
- plan: CachedPlanRef,
30
+ stmt: ApiStatement,
34
31
  }
35
32
 
36
33
  impl PreparedStatement {
37
34
  pub fn new(db: Arc<ApiDatabase>, sql: &str) -> PyResult<Self> {
38
- let plan = db.cached_plan(sql).map_err(to_py)?;
39
- Ok(Self {
40
- db,
41
- sql_text: sql.to_string(),
42
- plan,
43
- })
35
+ let stmt = db.prepare(sql).map_err(to_py)?;
36
+ Ok(Self { db, stmt })
44
37
  }
45
38
 
46
- pub(crate) fn plan(&self) -> &CachedPlanRef {
47
- &self.plan
39
+ pub(crate) fn inner(&self) -> &ApiStatement {
40
+ &self.stmt
48
41
  }
49
42
  }
50
43
 
@@ -54,11 +47,10 @@ impl PreparedStatement {
54
47
  #[pyo3(signature = (params=None))]
55
48
  fn execute(&self, py: Python<'_>, params: Option<&Bound<'_, PyAny>>) -> PyResult<i64> {
56
49
  let bind = parse_params(params)?;
57
- let plan = self.plan.clone();
58
50
  py.allow_threads(|| match bind {
59
- BindParams::Positional(p) => self.db.execute_plan(&plan, p).map_err(to_py),
51
+ BindParams::Positional(p) => self.stmt.execute(p).map_err(to_py),
60
52
  BindParams::Named(named) => {
61
- self.db.execute_named_plan(&plan, to_named_params(&named)).map_err(to_py)
53
+ self.stmt.execute_named(to_named_params(&named)).map_err(to_py)
62
54
  }
63
55
  })
64
56
  }
@@ -67,11 +59,10 @@ impl PreparedStatement {
67
59
  #[pyo3(signature = (params=None))]
68
60
  fn query(&self, py: Python<'_>, params: Option<&Bound<'_, PyAny>>) -> PyResult<PyObject> {
69
61
  let bind = parse_params(params)?;
70
- let plan = self.plan.clone();
71
62
  let rows = py.allow_threads(|| match bind {
72
- BindParams::Positional(p) => self.db.query_plan(&plan, p).map_err(to_py),
63
+ BindParams::Positional(p) => self.stmt.query(p).map_err(to_py),
73
64
  BindParams::Named(named) => {
74
- self.db.query_named_plan(&plan, to_named_params(&named)).map_err(to_py)
65
+ self.stmt.query_named(to_named_params(&named)).map_err(to_py)
75
66
  }
76
67
  })?;
77
68
  rows_to_dicts(py, rows)
@@ -81,11 +72,10 @@ impl PreparedStatement {
81
72
  #[pyo3(signature = (params=None))]
82
73
  fn query_one(&self, py: Python<'_>, params: Option<&Bound<'_, PyAny>>) -> PyResult<PyObject> {
83
74
  let bind = parse_params(params)?;
84
- let plan = self.plan.clone();
85
75
  let rows = py.allow_threads(|| match bind {
86
- BindParams::Positional(p) => self.db.query_plan(&plan, p).map_err(to_py),
76
+ BindParams::Positional(p) => self.stmt.query(p).map_err(to_py),
87
77
  BindParams::Named(named) => {
88
- self.db.query_named_plan(&plan, to_named_params(&named)).map_err(to_py)
78
+ self.stmt.query_named(to_named_params(&named)).map_err(to_py)
89
79
  }
90
80
  })?;
91
81
  first_row_to_dict(py, rows)
@@ -95,11 +85,10 @@ impl PreparedStatement {
95
85
  #[pyo3(signature = (params=None))]
96
86
  fn query_raw(&self, py: Python<'_>, params: Option<&Bound<'_, PyAny>>) -> PyResult<PyObject> {
97
87
  let bind = parse_params(params)?;
98
- let plan = self.plan.clone();
99
88
  let rows = py.allow_threads(|| match bind {
100
- BindParams::Positional(p) => self.db.query_plan(&plan, p).map_err(to_py),
89
+ BindParams::Positional(p) => self.stmt.query(p).map_err(to_py),
101
90
  BindParams::Named(named) => {
102
- self.db.query_named_plan(&plan, to_named_params(&named)).map_err(to_py)
91
+ self.stmt.query_named(to_named_params(&named)).map_err(to_py)
103
92
  }
104
93
  })?;
105
94
  rows_to_raw(py, rows)
@@ -109,10 +98,11 @@ impl PreparedStatement {
109
98
  ///
110
99
  /// Auto-wraps in a transaction. Returns total rows affected.
111
100
  #[pyo3(signature = (params_list,))]
112
- fn execute_batch(&self, py: Python<'_>, params_list: &Bound<'_, PyList>) -> PyResult<i64> {
101
+ fn execute_batch(&self, py: Python<'_>, params_list: &Bound<'_, PyAny>) -> PyResult<i64> {
113
102
  // Parse all param sets while holding GIL
114
- let mut all_params = Vec::with_capacity(params_list.len());
115
- for item in params_list.iter() {
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?;
116
106
  let bind = parse_params(Some(&item))?;
117
107
  match bind {
118
108
  BindParams::Positional(p) => all_params.push(p),
@@ -124,15 +114,12 @@ impl PreparedStatement {
124
114
  }
125
115
  }
126
116
 
127
- let plan = self.plan.clone();
128
-
129
117
  // Execute without GIL
130
118
  py.allow_threads(|| {
131
- let stmt = plan.statement.as_ref();
132
119
  let mut tx = self.db.begin().map_err(to_py)?;
133
120
  let mut total = 0i64;
134
121
  for params in all_params {
135
- total += tx.execute_prepared(stmt, params).map_err(to_py)?;
122
+ total += self.stmt.execute_in(&mut tx, params).map_err(to_py)?;
136
123
  }
137
124
  tx.commit().map_err(to_py)?;
138
125
  Ok(total)
@@ -142,10 +129,10 @@ impl PreparedStatement {
142
129
  /// Get the SQL text of this prepared statement.
143
130
  #[getter]
144
131
  fn sql(&self) -> &str {
145
- &self.sql_text
132
+ self.stmt.sql()
146
133
  }
147
134
 
148
135
  fn __repr__(&self) -> String {
149
- format!("PreparedStatement({:?})", self.sql_text)
136
+ format!("PreparedStatement({:?})", self.stmt.sql())
150
137
  }
151
138
  }
@@ -13,10 +13,9 @@
13
13
  // limitations under the License.
14
14
 
15
15
  use pyo3::prelude::*;
16
- use pyo3::types::PyList;
17
- use std::sync::Mutex;
16
+ use std::sync::{Arc, Mutex};
18
17
 
19
- use stoolap::api::Transaction as ApiTransaction;
18
+ use stoolap::api::{Database as ApiDatabase, Transaction as ApiTransaction};
20
19
 
21
20
  use crate::database::{first_row_to_dict, rows_to_dicts, rows_to_raw, to_named_params};
22
21
  use crate::error::to_py;
@@ -34,12 +33,14 @@ use crate::value::{parse_params, BindParams};
34
33
  #[pyclass]
35
34
  pub struct Transaction {
36
35
  tx: Mutex<Option<ApiTransaction>>,
36
+ db: Arc<ApiDatabase>,
37
37
  }
38
38
 
39
39
  impl Transaction {
40
- pub fn from_tx(tx: ApiTransaction) -> Self {
40
+ pub fn from_tx(tx: ApiTransaction, db: Arc<ApiDatabase>) -> Self {
41
41
  Self {
42
42
  tx: Mutex::new(Some(tx)),
43
+ db,
43
44
  }
44
45
  }
45
46
 
@@ -143,13 +144,14 @@ impl Transaction {
143
144
  &self,
144
145
  py: Python<'_>,
145
146
  sql: &str,
146
- params_list: &Bound<'_, PyList>,
147
+ params_list: &Bound<'_, PyAny>,
147
148
  ) -> PyResult<i64> {
148
149
  let sql = sql.to_string();
149
150
 
150
151
  // Parse all param sets while holding GIL
151
- let mut all_params = Vec::with_capacity(params_list.len());
152
- for item in params_list.iter() {
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?;
153
155
  let bind = parse_params(Some(&item))?;
154
156
  match bind {
155
157
  BindParams::Positional(p) => all_params.push(p),
@@ -163,19 +165,11 @@ impl Transaction {
163
165
 
164
166
  // Execute without GIL
165
167
  py.allow_threads(|| {
166
- use stoolap::parser::Parser;
167
- let mut parser = Parser::new(&sql);
168
- let program = parser.parse_program().map_err(|e| {
169
- crate::error::StoolapError::new_err(e.to_string())
170
- })?;
171
- let stmt = program.statements.first().ok_or_else(|| {
172
- crate::error::StoolapError::new_err("No SQL statement found")
173
- })?;
174
-
168
+ let stmt = self.db.prepare(&sql).map_err(to_py)?;
175
169
  self.with_tx(|tx| {
176
170
  let mut total = 0i64;
177
171
  for params in all_params {
178
- total += tx.execute_prepared(stmt, params).map_err(to_py)?;
172
+ total += stmt.execute_in(tx, params).map_err(to_py)?;
179
173
  }
180
174
  Ok(total)
181
175
  })
@@ -191,13 +185,12 @@ impl Transaction {
191
185
  params: Option<&Bound<'_, PyAny>>,
192
186
  ) -> PyResult<i64> {
193
187
  let bind = parse_params(params)?;
194
- let plan = stmt.plan().clone();
188
+ let stmt = stmt.inner();
195
189
  py.allow_threads(|| {
196
- let statement = plan.statement.as_ref();
197
190
  self.with_tx(|tx| match bind {
198
- BindParams::Positional(p) => tx.execute_prepared(statement, p).map_err(to_py),
191
+ BindParams::Positional(p) => stmt.execute_in(tx, p).map_err(to_py),
199
192
  BindParams::Named(named) => {
200
- tx.execute_prepared_named(statement, to_named_params(&named)).map_err(to_py)
193
+ stmt.execute_named_in(tx, to_named_params(&named)).map_err(to_py)
201
194
  }
202
195
  })
203
196
  })
@@ -212,13 +205,12 @@ impl Transaction {
212
205
  params: Option<&Bound<'_, PyAny>>,
213
206
  ) -> PyResult<PyObject> {
214
207
  let bind = parse_params(params)?;
215
- let plan = stmt.plan().clone();
208
+ let stmt = stmt.inner();
216
209
  let rows = py.allow_threads(|| {
217
- let statement = plan.statement.as_ref();
218
210
  self.with_tx(|tx| match bind {
219
- BindParams::Positional(p) => tx.query_prepared(statement, p).map_err(to_py),
211
+ BindParams::Positional(p) => stmt.query_in(tx, p).map_err(to_py),
220
212
  BindParams::Named(named) => {
221
- tx.query_prepared_named(statement, to_named_params(&named)).map_err(to_py)
213
+ stmt.query_named_in(tx, to_named_params(&named)).map_err(to_py)
222
214
  }
223
215
  })
224
216
  })?;
@@ -234,13 +226,12 @@ impl Transaction {
234
226
  params: Option<&Bound<'_, PyAny>>,
235
227
  ) -> PyResult<PyObject> {
236
228
  let bind = parse_params(params)?;
237
- let plan = stmt.plan().clone();
229
+ let stmt = stmt.inner();
238
230
  let rows = py.allow_threads(|| {
239
- let statement = plan.statement.as_ref();
240
231
  self.with_tx(|tx| match bind {
241
- BindParams::Positional(p) => tx.query_prepared(statement, p).map_err(to_py),
232
+ BindParams::Positional(p) => stmt.query_in(tx, p).map_err(to_py),
242
233
  BindParams::Named(named) => {
243
- tx.query_prepared_named(statement, to_named_params(&named)).map_err(to_py)
234
+ stmt.query_named_in(tx, to_named_params(&named)).map_err(to_py)
244
235
  }
245
236
  })
246
237
  })?;
@@ -256,13 +247,12 @@ impl Transaction {
256
247
  params: Option<&Bound<'_, PyAny>>,
257
248
  ) -> PyResult<PyObject> {
258
249
  let bind = parse_params(params)?;
259
- let plan = stmt.plan().clone();
250
+ let stmt = stmt.inner();
260
251
  let rows = py.allow_threads(|| {
261
- let statement = plan.statement.as_ref();
262
252
  self.with_tx(|tx| match bind {
263
- BindParams::Positional(p) => tx.query_prepared(statement, p).map_err(to_py),
253
+ BindParams::Positional(p) => stmt.query_in(tx, p).map_err(to_py),
264
254
  BindParams::Named(named) => {
265
- tx.query_prepared_named(statement, to_named_params(&named)).map_err(to_py)
255
+ stmt.query_named_in(tx, to_named_params(&named)).map_err(to_py)
266
256
  }
267
257
  })
268
258
  })?;
@@ -270,30 +260,37 @@ impl Transaction {
270
260
  }
271
261
 
272
262
  /// Commit the transaction.
263
+ ///
264
+ /// On failure the transaction stays active so it can still be rolled back.
273
265
  fn commit(&self, py: Python<'_>) -> PyResult<()> {
274
266
  py.allow_threads(|| {
275
267
  let mut guard = self
276
268
  .tx
277
269
  .lock()
278
270
  .map_err(|_| crate::error::StoolapError::new_err("Transaction lock poisoned"))?;
279
- let mut tx = guard.take().ok_or_else(|| {
271
+ let tx = guard.as_mut().ok_or_else(|| {
280
272
  crate::error::StoolapError::new_err("Transaction is no longer active")
281
273
  })?;
282
- tx.commit().map_err(to_py)
274
+ tx.commit().map_err(to_py)?;
275
+ *guard = None;
276
+ Ok(())
283
277
  })
284
278
  }
285
279
 
286
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.
287
284
  fn rollback(&self, py: Python<'_>) -> PyResult<()> {
288
285
  py.allow_threads(|| {
289
286
  let mut guard = self
290
287
  .tx
291
288
  .lock()
292
289
  .map_err(|_| crate::error::StoolapError::new_err("Transaction lock poisoned"))?;
293
- let mut tx = guard.take().ok_or_else(|| {
294
- crate::error::StoolapError::new_err("Transaction is no longer active")
295
- })?;
296
- tx.rollback().map_err(to_py)
290
+ if let Some(mut tx) = guard.take() {
291
+ tx.rollback().map_err(to_py)?;
292
+ }
293
+ Ok(())
297
294
  })
298
295
  }
299
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()
@@ -15,7 +15,7 @@
15
15
  """Named parameter tests across all APIs."""
16
16
 
17
17
  import pytest
18
- from stoolap import Database, AsyncDatabase
18
+ from stoolap import Database, AsyncDatabase, StoolapError
19
19
 
20
20
 
21
21
  @pytest.fixture
@@ -277,6 +277,19 @@ def test_tx_prepared_query_named(db):
277
277
  assert raw["rows"][0][1] == "Alice"
278
278
 
279
279
 
280
+ def test_missing_named_param_is_an_error(db):
281
+ with pytest.raises(StoolapError, match="named parameter :id has no value"):
282
+ db.query("SELECT * FROM users WHERE id = :id", {})
283
+
284
+ stmt = db.prepare("SELECT * FROM users WHERE id = :id")
285
+ with pytest.raises(StoolapError, match="named parameter :id has no value"):
286
+ stmt.query({"name": "Alice"})
287
+
288
+ with db.begin() as tx:
289
+ with pytest.raises(StoolapError, match="named parameter :id has no value"):
290
+ tx.query_prepared(stmt, {})
291
+
292
+
280
293
  def test_tx_prepared_named_rollback(db):
281
294
  stmt = db.prepare("INSERT INTO users VALUES (:id, :name, :email)")
282
295
  with pytest.raises(RuntimeError):
@@ -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()
@@ -56,14 +56,14 @@ def test_float_types():
56
56
 
57
57
  def test_text_types():
58
58
  db = Database.open(":memory:")
59
- db.exec("CREATE TABLE t_text (val TEXT)")
59
+ db.exec("CREATE TABLE t_text (id INTEGER PRIMARY KEY, val TEXT)")
60
60
 
61
- db.execute("INSERT INTO t_text VALUES ($1)", [""])
62
- db.execute("INSERT INTO t_text VALUES ($1)", ["hello world"])
63
- db.execute("INSERT INTO t_text VALUES ($1)", ["unicode: \u00e9\u00e0\u00fc\u00f1"])
64
- db.execute("INSERT INTO t_text VALUES ($1)", ["emoji: \U0001f600"])
61
+ db.execute("INSERT INTO t_text VALUES ($1, $2)", [1, ""])
62
+ db.execute("INSERT INTO t_text VALUES ($1, $2)", [2, "hello world"])
63
+ db.execute("INSERT INTO t_text VALUES ($1, $2)", [3, "unicode: \u00e9\u00e0\u00fc\u00f1"])
64
+ db.execute("INSERT INTO t_text VALUES ($1, $2)", [4, "emoji: \U0001f600"])
65
65
 
66
- rows = db.query("SELECT val FROM t_text ORDER BY rowid")
66
+ rows = db.query("SELECT val FROM t_text ORDER BY id")
67
67
  assert rows[0]["val"] == ""
68
68
  assert rows[1]["val"] == "hello world"
69
69
  assert rows[2]["val"] == "unicode: \u00e9\u00e0\u00fc\u00f1"
@@ -73,12 +73,12 @@ def test_text_types():
73
73
 
74
74
  def test_boolean_type():
75
75
  db = Database.open(":memory:")
76
- db.exec("CREATE TABLE t_bool (val BOOLEAN)")
76
+ db.exec("CREATE TABLE t_bool (id INTEGER PRIMARY KEY, val BOOLEAN)")
77
77
 
78
- db.execute("INSERT INTO t_bool VALUES ($1)", [True])
79
- db.execute("INSERT INTO t_bool VALUES ($1)", [False])
78
+ db.execute("INSERT INTO t_bool VALUES ($1, $2)", [1, True])
79
+ db.execute("INSERT INTO t_bool VALUES ($1, $2)", [2, False])
80
80
 
81
- rows = db.query("SELECT val FROM t_bool ORDER BY rowid")
81
+ rows = db.query("SELECT val FROM t_bool ORDER BY id")
82
82
  assert rows[0]["val"] is True
83
83
  assert rows[1]["val"] is False
84
84
  db.close()
File without changes