stoolap 0.4.0
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.
- checksums.yaml +7 -0
- data/Cargo.lock +1792 -0
- data/Cargo.toml +9 -0
- data/LICENSE +201 -0
- data/README.md +477 -0
- data/ext/stoolap/Cargo.toml +20 -0
- data/ext/stoolap/extconf.rb +6 -0
- data/ext/stoolap/src/database.rs +432 -0
- data/ext/stoolap/src/error.rs +53 -0
- data/ext/stoolap/src/lib.rs +103 -0
- data/ext/stoolap/src/statement.rs +193 -0
- data/ext/stoolap/src/transaction.rs +246 -0
- data/ext/stoolap/src/value.rs +296 -0
- data/lib/stoolap/version.rb +5 -0
- data/lib/stoolap.rb +86 -0
- metadata +145 -0
data/Cargo.toml
ADDED
data/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 Stoolap Contributors
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
data/README.md
ADDED
|
@@ -0,0 +1,477 @@
|
|
|
1
|
+
# stoolap-ruby
|
|
2
|
+
|
|
3
|
+
High-performance Ruby driver for [Stoolap](https://stoolap.io) embedded SQL database. Built with [Magnus](https://github.com/matsadler/magnus) + [rb-sys](https://github.com/oxidize-rb/rb-sys) for direct Rust bindings with no FFI overhead.
|
|
4
|
+
|
|
5
|
+
- Native Ruby extension gem (not an FFI wrapper).
|
|
6
|
+
- Sub-microsecond point queries on in-memory databases.
|
|
7
|
+
- MVCC transactions with snapshot isolation, parallel query execution, columnar cold volumes with zone maps, bloom filters, LZ4 compression.
|
|
8
|
+
- Full SQL: JOINs, window functions, CTEs, subqueries, GROUP BY / ROLLUP / CUBE / GROUPING SETS, HNSW vector search.
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
Add to your `Gemfile`:
|
|
13
|
+
|
|
14
|
+
```ruby
|
|
15
|
+
gem "stoolap"
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Or install directly:
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
gem install stoolap
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Requires Ruby `>= 3.3` and a stable Rust toolchain at install time (the native extension is built from source on your machine). Rust: <https://rustup.rs>.
|
|
25
|
+
|
|
26
|
+
## Quick Start
|
|
27
|
+
|
|
28
|
+
```ruby
|
|
29
|
+
require "stoolap"
|
|
30
|
+
|
|
31
|
+
# In-memory database
|
|
32
|
+
db = Stoolap::Database.open(":memory:")
|
|
33
|
+
|
|
34
|
+
# exec runs one or more DDL/DML statements (no parameters)
|
|
35
|
+
db.exec(<<~SQL)
|
|
36
|
+
CREATE TABLE users (
|
|
37
|
+
id INTEGER PRIMARY KEY,
|
|
38
|
+
name TEXT NOT NULL,
|
|
39
|
+
email TEXT
|
|
40
|
+
);
|
|
41
|
+
CREATE INDEX idx_users_name ON users(name);
|
|
42
|
+
SQL
|
|
43
|
+
|
|
44
|
+
# execute runs a single statement with parameters, returns rows affected
|
|
45
|
+
db.execute(
|
|
46
|
+
"INSERT INTO users (id, name, email) VALUES ($1, $2, $3)",
|
|
47
|
+
[1, "Alice", "alice@example.com"]
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
# Named parameters (:key) with either Symbol or String keys
|
|
51
|
+
db.execute(
|
|
52
|
+
"INSERT INTO users (id, name, email) VALUES (:id, :name, :email)",
|
|
53
|
+
{ id: 2, name: "Bob", email: "bob@example.com" }
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
# query returns an Array of Hashes with String keys
|
|
57
|
+
users = db.query("SELECT * FROM users ORDER BY id")
|
|
58
|
+
# => [{"id" => 1, "name" => "Alice", ...}, ...]
|
|
59
|
+
|
|
60
|
+
# query_one returns a single Hash or nil
|
|
61
|
+
user = db.query_one("SELECT * FROM users WHERE id = $1", [1])
|
|
62
|
+
# => {"id" => 1, "name" => "Alice", "email" => "alice@example.com"}
|
|
63
|
+
|
|
64
|
+
# query_raw returns columnar format (skip the per-row Hash allocation)
|
|
65
|
+
raw = db.query_raw("SELECT id, name FROM users ORDER BY id")
|
|
66
|
+
# => {"columns" => ["id", "name"], "rows" => [[1, "Alice"], [2, "Bob"]]}
|
|
67
|
+
|
|
68
|
+
db.close
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### Block form auto-closes
|
|
72
|
+
|
|
73
|
+
```ruby
|
|
74
|
+
Stoolap::Database.open(":memory:") do |db|
|
|
75
|
+
db.exec("CREATE TABLE t (id INTEGER PRIMARY KEY)")
|
|
76
|
+
db.execute("INSERT INTO t VALUES ($1)", [1])
|
|
77
|
+
end
|
|
78
|
+
# db.close already ran, even if the block raised
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Opening a Database
|
|
82
|
+
|
|
83
|
+
```ruby
|
|
84
|
+
# In-memory (three equivalent forms)
|
|
85
|
+
Stoolap::Database.open(":memory:")
|
|
86
|
+
Stoolap::Database.open("")
|
|
87
|
+
Stoolap::Database.open("memory://")
|
|
88
|
+
|
|
89
|
+
# File-backed (data persists across restarts)
|
|
90
|
+
Stoolap::Database.open("./mydata")
|
|
91
|
+
Stoolap::Database.open("file:///absolute/path/to/db")
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## Database Methods
|
|
95
|
+
|
|
96
|
+
| Method | Returns | Description |
|
|
97
|
+
|---|---|---|
|
|
98
|
+
| `execute(sql, params = nil)` | `Integer` | Execute DML, return rows affected |
|
|
99
|
+
| `exec(sql)` | `nil` | Execute one or more statements (no parameters) |
|
|
100
|
+
| `query(sql, params = nil)` | `Array<Hash>` | All rows as Array of Hashes |
|
|
101
|
+
| `query_one(sql, params = nil)` | `Hash, nil` | First row as Hash, or nil |
|
|
102
|
+
| `query_raw(sql, params = nil)` | `Hash` | `{"columns" => [...], "rows" => [[...], ...]}` |
|
|
103
|
+
| `execute_batch(sql, params_list)` | `Integer` | Same SQL, many param sets, auto-tx |
|
|
104
|
+
| `prepare(sql)` | `PreparedStatement` | Cache a parsed + planned statement |
|
|
105
|
+
| `begin_transaction` | `Transaction` | Start a manual transaction |
|
|
106
|
+
| `transaction { \|tx\| ... }` | block return | Auto-commit or rollback on raise |
|
|
107
|
+
| `close` | `nil` | Close the database |
|
|
108
|
+
|
|
109
|
+
## Parameters
|
|
110
|
+
|
|
111
|
+
All parameter-accepting methods take either an `Array` (positional, `$1, $2, ...`) or a `Hash` (named, `:key`):
|
|
112
|
+
|
|
113
|
+
```ruby
|
|
114
|
+
# Positional
|
|
115
|
+
db.query("SELECT * FROM users WHERE id = $1 AND name = $2", [1, "Alice"])
|
|
116
|
+
|
|
117
|
+
# Named with Symbol keys
|
|
118
|
+
db.query("SELECT * FROM users WHERE id = :id AND name = :name",
|
|
119
|
+
{ id: 1, name: "Alice" })
|
|
120
|
+
|
|
121
|
+
# Named with String keys
|
|
122
|
+
db.query("SELECT * FROM users WHERE id = :id", { "id" => 1 })
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Named-parameter keys can optionally carry a `:`, `@`, or `$` sigil. The driver strips it:
|
|
126
|
+
|
|
127
|
+
```ruby
|
|
128
|
+
db.query("SELECT * FROM users WHERE id = :id", { ":id" => 1 })
|
|
129
|
+
db.query("SELECT * FROM users WHERE id = :id", { "@id" => 1 })
|
|
130
|
+
db.query("SELECT * FROM users WHERE id = :id", { "$id" => 1 })
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## Raw Query Format
|
|
134
|
+
|
|
135
|
+
`query_raw` returns `{"columns" => [...], "rows" => [[...], ...]}` instead of an Array of Hashes. Use it when you are streaming large results and do not need named access to each row.
|
|
136
|
+
|
|
137
|
+
```ruby
|
|
138
|
+
raw = db.query_raw("SELECT id, name, email FROM users ORDER BY id")
|
|
139
|
+
raw["columns"] # => ["id", "name", "email"]
|
|
140
|
+
raw["rows"] # => [[1, "Alice", "alice@example.com"], ...]
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## Batch Execution
|
|
144
|
+
|
|
145
|
+
Execute the same statement with many parameter sets in one call. Automatically wrapped in a transaction:
|
|
146
|
+
|
|
147
|
+
```ruby
|
|
148
|
+
changes = db.execute_batch(
|
|
149
|
+
"INSERT INTO users (id, name, email) VALUES ($1, $2, $3)",
|
|
150
|
+
[
|
|
151
|
+
[1, "Alice", "alice@example.com"],
|
|
152
|
+
[2, "Bob", "bob@example.com"],
|
|
153
|
+
[3, "Charlie", "charlie@example.com"]
|
|
154
|
+
]
|
|
155
|
+
)
|
|
156
|
+
# changes => 3
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
`execute_batch` only supports positional parameters (Arrays). Hash parameter sets raise `Stoolap::Error`.
|
|
160
|
+
|
|
161
|
+
## Prepared Statements
|
|
162
|
+
|
|
163
|
+
A prepared statement parses SQL once and caches the execution plan. Column-key `String`s are also cached on the first query so repeated calls do not re-allocate them.
|
|
164
|
+
|
|
165
|
+
```ruby
|
|
166
|
+
insert = db.prepare("INSERT INTO users (id, name) VALUES ($1, $2)")
|
|
167
|
+
insert.execute([1, "Alice"])
|
|
168
|
+
insert.execute([2, "Bob"])
|
|
169
|
+
|
|
170
|
+
# Batch on a prepared statement (reuses the cached plan)
|
|
171
|
+
insert.execute_batch([
|
|
172
|
+
[3, "Charlie"],
|
|
173
|
+
[4, "Diana"]
|
|
174
|
+
])
|
|
175
|
+
|
|
176
|
+
# Prepared reads
|
|
177
|
+
lookup = db.prepare("SELECT * FROM users WHERE id = $1")
|
|
178
|
+
lookup.query_one([1]) # => {"id" => 1, "name" => "Alice"}
|
|
179
|
+
lookup.query([1]) # => [{"id" => 1, "name" => "Alice"}]
|
|
180
|
+
lookup.query_raw([1]) # => {"columns" => [...], "rows" => [[...]]}
|
|
181
|
+
|
|
182
|
+
# Named parameters work the same
|
|
183
|
+
lookup_named = db.prepare("SELECT * FROM users WHERE id = :id")
|
|
184
|
+
lookup_named.query_one({ id: 1 })
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
### PreparedStatement methods
|
|
188
|
+
|
|
189
|
+
| Method | Returns | Description |
|
|
190
|
+
|---|---|---|
|
|
191
|
+
| `execute(params = nil)` | `Integer` | Execute DML |
|
|
192
|
+
| `query(params = nil)` | `Array<Hash>` | All rows |
|
|
193
|
+
| `query_one(params = nil)` | `Hash, nil` | First row or nil |
|
|
194
|
+
| `query_raw(params = nil)` | `Hash` | Columnar format |
|
|
195
|
+
| `execute_batch(params_list)` | `Integer` | Many param sets, auto-tx |
|
|
196
|
+
| `sql` | `String` | The SQL text this statement was built from |
|
|
197
|
+
|
|
198
|
+
## Transactions
|
|
199
|
+
|
|
200
|
+
### Block form (recommended)
|
|
201
|
+
|
|
202
|
+
```ruby
|
|
203
|
+
db.transaction do |tx|
|
|
204
|
+
tx.execute("INSERT INTO users (id, name) VALUES ($1, $2)", [1, "Alice"])
|
|
205
|
+
tx.execute("INSERT INTO users (id, name) VALUES ($1, $2)", [2, "Bob"])
|
|
206
|
+
|
|
207
|
+
# Reads within the tx see its own uncommitted writes
|
|
208
|
+
rows = tx.query("SELECT * FROM users")
|
|
209
|
+
one = tx.query_one("SELECT * FROM users WHERE id = $1", [1])
|
|
210
|
+
raw = tx.query_raw("SELECT id, name FROM users")
|
|
211
|
+
end
|
|
212
|
+
# commit on clean exit, rollback on any raise
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
The block helper returns whatever the block returns:
|
|
216
|
+
|
|
217
|
+
```ruby
|
|
218
|
+
total = db.transaction do |tx|
|
|
219
|
+
tx.query_one("SELECT COUNT(*) AS c FROM users")["c"]
|
|
220
|
+
end
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
### Manual control
|
|
224
|
+
|
|
225
|
+
```ruby
|
|
226
|
+
tx = db.begin_transaction
|
|
227
|
+
begin
|
|
228
|
+
tx.execute("INSERT INTO users (id, name) VALUES ($1, $2)", [1, "Alice"])
|
|
229
|
+
tx.commit
|
|
230
|
+
rescue StandardError
|
|
231
|
+
tx.rollback
|
|
232
|
+
raise
|
|
233
|
+
end
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
Or the equivalent `Transaction#with_rollback` helper:
|
|
237
|
+
|
|
238
|
+
```ruby
|
|
239
|
+
tx = db.begin_transaction
|
|
240
|
+
tx.with_rollback do |t|
|
|
241
|
+
t.execute("INSERT INTO users (id, name) VALUES ($1, $2)", [1, "Alice"])
|
|
242
|
+
end
|
|
243
|
+
# commit on success, rollback on raise
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
### Transaction methods
|
|
247
|
+
|
|
248
|
+
| Method | Returns | Description |
|
|
249
|
+
|---|---|---|
|
|
250
|
+
| `execute(sql, params = nil)` | `Integer` | Execute DML |
|
|
251
|
+
| `query(sql, params = nil)` | `Array<Hash>` | All rows |
|
|
252
|
+
| `query_one(sql, params = nil)` | `Hash, nil` | First row or nil |
|
|
253
|
+
| `query_raw(sql, params = nil)` | `Hash` | Columnar format |
|
|
254
|
+
| `execute_batch(sql, params_list)` | `Integer` | Many param sets |
|
|
255
|
+
| `execute_prepared(stmt, params = nil)` | `Integer` | Run a `PreparedStatement` inside this tx |
|
|
256
|
+
| `query_prepared(stmt, params = nil)` | `Array<Hash>` | Query a `PreparedStatement` inside this tx |
|
|
257
|
+
| `query_one_prepared(stmt, params = nil)` | `Hash, nil` | First row from a prepared query |
|
|
258
|
+
| `query_raw_prepared(stmt, params = nil)` | `Hash` | Columnar result from a prepared query |
|
|
259
|
+
| `commit` | `nil` | Commit the transaction |
|
|
260
|
+
| `rollback` | `nil` | Roll back the transaction |
|
|
261
|
+
| `with_rollback { \|tx\| ... }` | block return | Commit on clean exit, rollback on raise |
|
|
262
|
+
|
|
263
|
+
Calling `execute` / `query` / `commit` / `rollback` on a committed or rolled-back transaction raises `Stoolap::Error`. DDL statements (`CREATE TABLE`, etc.) are not allowed inside explicit transactions; run them outside.
|
|
264
|
+
|
|
265
|
+
## Type Mapping
|
|
266
|
+
|
|
267
|
+
| Ruby | Stoolap | Notes |
|
|
268
|
+
|---|---|---|
|
|
269
|
+
| `Integer` | `INTEGER` | 64-bit signed (full `i64::MIN..=i64::MAX`) |
|
|
270
|
+
| `Float` | `FLOAT` | 64-bit double |
|
|
271
|
+
| `String` | `TEXT` | UTF-8, returned as UTF-8-encoded `String` |
|
|
272
|
+
| `true` / `false` | `BOOLEAN` | |
|
|
273
|
+
| `nil` | `NULL` | Any column type |
|
|
274
|
+
| `Time` | `TIMESTAMP` | Nanosecond precision; local times converted to UTC; returned as UTC `Time` |
|
|
275
|
+
| `Symbol` | `TEXT` | Converted to its string name |
|
|
276
|
+
| `Hash` | `JSON` | Serialized via `JSON.dump` (requires `require "json"`) |
|
|
277
|
+
| `Array` | `JSON` | Serialized via `JSON.dump` |
|
|
278
|
+
| `Stoolap::Vector` | `VECTOR(N)` | See below |
|
|
279
|
+
|
|
280
|
+
Any other type passed as a parameter raises `TypeError`.
|
|
281
|
+
|
|
282
|
+
## Vector Similarity Search
|
|
283
|
+
|
|
284
|
+
Stoolap has native `VECTOR(N)` columns and HNSW indexes. Wrap a Ruby numeric array in `Stoolap::Vector` to avoid the JSON encoding path:
|
|
285
|
+
|
|
286
|
+
```ruby
|
|
287
|
+
db.exec(<<~SQL)
|
|
288
|
+
CREATE TABLE documents (
|
|
289
|
+
id INTEGER PRIMARY KEY,
|
|
290
|
+
title TEXT,
|
|
291
|
+
embedding VECTOR(3)
|
|
292
|
+
);
|
|
293
|
+
CREATE INDEX idx_emb ON documents(embedding) USING HNSW WITH (metric = 'cosine');
|
|
294
|
+
SQL
|
|
295
|
+
|
|
296
|
+
db.execute(
|
|
297
|
+
"INSERT INTO documents VALUES ($1, $2, $3)",
|
|
298
|
+
[1, "Hello world", Stoolap::Vector.new([0.1, 0.2, 0.3])]
|
|
299
|
+
)
|
|
300
|
+
db.execute(
|
|
301
|
+
"INSERT INTO documents VALUES ($1, $2, $3)",
|
|
302
|
+
[2, "Goodbye world", Stoolap::Vector.new([0.9, 0.1, 0.0])]
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
# k-NN search: 5 nearest neighbours by cosine distance
|
|
306
|
+
results = db.query(<<~SQL)
|
|
307
|
+
SELECT id, title,
|
|
308
|
+
VEC_DISTANCE_COSINE(embedding, '[0.1, 0.2, 0.3]') AS dist
|
|
309
|
+
FROM documents
|
|
310
|
+
ORDER BY dist
|
|
311
|
+
LIMIT 5
|
|
312
|
+
SQL
|
|
313
|
+
|
|
314
|
+
# Read vectors back as Array<Float>
|
|
315
|
+
row = db.query_one("SELECT embedding FROM documents WHERE id = 1")
|
|
316
|
+
row["embedding"] # => [0.1, 0.2, 0.3]
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
### Vector class
|
|
320
|
+
|
|
321
|
+
| Method | Returns | Description |
|
|
322
|
+
|---|---|---|
|
|
323
|
+
| `Stoolap::Vector.new(array)` | `Vector` | Build from an `Array` of numbers (raises `TypeError` on non-numeric) |
|
|
324
|
+
| `#to_a` | `Array<Float>` | Copy to a plain Array |
|
|
325
|
+
| `#length` / `#size` | `Integer` | Dimension count |
|
|
326
|
+
| `#inspect` / `#to_s` | `String` | `#<Stoolap::Vector [0.1, 0.2, 0.3]>` |
|
|
327
|
+
|
|
328
|
+
### Vector distance functions
|
|
329
|
+
|
|
330
|
+
| Function | Description |
|
|
331
|
+
|---|---|
|
|
332
|
+
| `VEC_DISTANCE_L2(a, b)` | Euclidean distance |
|
|
333
|
+
| `VEC_DISTANCE_COSINE(a, b)` | Cosine distance (1 minus cosine similarity) |
|
|
334
|
+
| `VEC_DISTANCE_IP(a, b)` | Negative inner product |
|
|
335
|
+
|
|
336
|
+
### HNSW index options
|
|
337
|
+
|
|
338
|
+
```sql
|
|
339
|
+
CREATE INDEX idx ON documents(embedding) USING HNSW WITH (metric = 'cosine');
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
Supported metrics: `l2` (default), `cosine`, `ip`.
|
|
343
|
+
|
|
344
|
+
## Persistence and Configuration
|
|
345
|
+
|
|
346
|
+
File-backed databases persist data via Write-Ahead Logging and immutable columnar cold volumes. A background checkpoint cycle seals hot rows into volume files, compacts them, and truncates the WAL. Data survives process restarts.
|
|
347
|
+
|
|
348
|
+
```ruby
|
|
349
|
+
Stoolap::Database.open("./mydata") do |db|
|
|
350
|
+
db.exec("CREATE TABLE kv (key TEXT PRIMARY KEY, value TEXT)")
|
|
351
|
+
db.execute("INSERT INTO kv VALUES ($1, $2)", ["hello", "world"])
|
|
352
|
+
end
|
|
353
|
+
|
|
354
|
+
# Reopen: data is still there
|
|
355
|
+
Stoolap::Database.open("./mydata") do |db|
|
|
356
|
+
db.query_one("SELECT value FROM kv WHERE key = $1", ["hello"])
|
|
357
|
+
# => {"value" => "world"}
|
|
358
|
+
end
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
### DSN query parameters
|
|
362
|
+
|
|
363
|
+
Append options to the path as query parameters:
|
|
364
|
+
|
|
365
|
+
```ruby
|
|
366
|
+
# Maximum durability (fsync on every WAL write)
|
|
367
|
+
Stoolap::Database.open("./mydata?sync=full")
|
|
368
|
+
|
|
369
|
+
# High throughput (no fsync, larger buffers)
|
|
370
|
+
Stoolap::Database.open("./mydata?sync=none&wal_buffer_size=131072")
|
|
371
|
+
|
|
372
|
+
# Custom checkpoint interval with compression
|
|
373
|
+
Stoolap::Database.open("./mydata?checkpoint_interval=60&compression=on")
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
| Parameter | Default | Description |
|
|
377
|
+
|---|---|---|
|
|
378
|
+
| `sync` | `normal` | Sync mode: `none`, `normal`, `full` |
|
|
379
|
+
| `checkpoint_interval` | `60` | Seconds between automatic checkpoint cycles |
|
|
380
|
+
| `compact_threshold` | `4` | Sub-target volumes per table before merging |
|
|
381
|
+
| `keep_snapshots` | `3` | Backup snapshots retained per table |
|
|
382
|
+
| `wal_flush_trigger` | `32768` | WAL flush trigger in bytes (32 KB) |
|
|
383
|
+
| `wal_buffer_size` | `65536` | WAL buffer size in bytes (64 KB) |
|
|
384
|
+
| `wal_max_size` | `67108864` | Max WAL file size before rotation (64 MB) |
|
|
385
|
+
| `commit_batch_size` | `100` | Commits batched before syncing (normal mode) |
|
|
386
|
+
| `sync_interval_ms` | `1000` | Minimum ms between syncs (normal mode) |
|
|
387
|
+
| `wal_compression` | `on` | LZ4 compression for WAL entries |
|
|
388
|
+
| `volume_compression` | `on` | LZ4 compression for cold volume files |
|
|
389
|
+
| `compression` | -- | Alias that sets both `wal_compression` and `volume_compression` |
|
|
390
|
+
| `compression_threshold` | `64` | Minimum bytes before compressing an entry |
|
|
391
|
+
| `checkpoint_on_close` | `on` | Seal all hot rows to volumes on clean shutdown |
|
|
392
|
+
| `target_volume_rows` | `1048576` | Target rows per cold volume (min 65536) |
|
|
393
|
+
|
|
394
|
+
### Sync Modes
|
|
395
|
+
|
|
396
|
+
| Mode | Value | Description |
|
|
397
|
+
|---|---|---|
|
|
398
|
+
| `none` | `sync=none` | No fsync. Fastest, data may be lost on crash |
|
|
399
|
+
| `normal` | `sync=normal` | Fsync in commit batches (default) |
|
|
400
|
+
| `full` | `sync=full` | Fsync on every WAL write. Slowest, maximum durability |
|
|
401
|
+
|
|
402
|
+
### Same DSN shares one engine
|
|
403
|
+
|
|
404
|
+
Opening the same DSN twice in one process returns the same underlying engine. Closing one handle closes the engine for all handles. This prevents corruption and is why you should open a database once per process and pass the instance around.
|
|
405
|
+
|
|
406
|
+
## Error Handling
|
|
407
|
+
|
|
408
|
+
All database errors raise `Stoolap::Error`, which inherits from `StandardError`:
|
|
409
|
+
|
|
410
|
+
```ruby
|
|
411
|
+
begin
|
|
412
|
+
db.execute("SELEXT * FROM nothing")
|
|
413
|
+
rescue Stoolap::Error => e
|
|
414
|
+
warn "database error: #{e.message}"
|
|
415
|
+
end
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
Invalid parameter types raise `TypeError`:
|
|
419
|
+
|
|
420
|
+
```ruby
|
|
421
|
+
begin
|
|
422
|
+
db.execute("INSERT INTO t VALUES ($1)", [Object.new])
|
|
423
|
+
rescue TypeError => e
|
|
424
|
+
warn e.message
|
|
425
|
+
end
|
|
426
|
+
```
|
|
427
|
+
|
|
428
|
+
## Features
|
|
429
|
+
|
|
430
|
+
Stoolap is a full-featured embedded SQL database:
|
|
431
|
+
|
|
432
|
+
- **MVCC transactions** with snapshot isolation.
|
|
433
|
+
- **Cost-based query optimizer** with adaptive execution.
|
|
434
|
+
- **Parallel execution** for filter, join, sort, and distinct operators.
|
|
435
|
+
- **JOINs**: INNER, LEFT, RIGHT, FULL OUTER, CROSS, NATURAL.
|
|
436
|
+
- **Subqueries**: scalar, `EXISTS`, `IN`, `NOT IN`, `ANY`/`ALL`, correlated.
|
|
437
|
+
- **Window functions**: `ROW_NUMBER`, `RANK`, `DENSE_RANK`, `LAG`, `LEAD`, `NTILE`, plus frame specs.
|
|
438
|
+
- **CTEs**: `WITH` and `WITH RECURSIVE`.
|
|
439
|
+
- **Aggregations**: `GROUP BY`, `HAVING`, `ROLLUP`, `CUBE`, `GROUPING SETS`.
|
|
440
|
+
- **Vector similarity search** with HNSW indexes over `l2`, `cosine`, `ip`.
|
|
441
|
+
- **Indexes**: B-tree, hash, bitmap (auto-selected), HNSW, multi-column composite.
|
|
442
|
+
- **131 built-in functions**: string, math, date/time, JSON, vector, aggregate.
|
|
443
|
+
- **Immutable volume storage** with columnar format, zone maps, bloom filters, LZ4 compression.
|
|
444
|
+
- **WAL + checkpoint cycles** for crash recovery.
|
|
445
|
+
- **Aggregation pushdown** to cold volume statistics (`COUNT`, `SUM`, `MIN`, `MAX`).
|
|
446
|
+
- **Semantic query caching** with predicate subsumption.
|
|
447
|
+
|
|
448
|
+
See the [Stoolap documentation](https://stoolap.io/docs/) for SQL reference.
|
|
449
|
+
|
|
450
|
+
## Building from Source
|
|
451
|
+
|
|
452
|
+
Requires:
|
|
453
|
+
- [Rust](https://rustup.rs) (stable)
|
|
454
|
+
- Ruby `>= 3.3`
|
|
455
|
+
- A C toolchain for the Ruby header files
|
|
456
|
+
|
|
457
|
+
```sh
|
|
458
|
+
git clone https://github.com/stoolap/stoolap-ruby.git
|
|
459
|
+
cd stoolap-ruby
|
|
460
|
+
bundle install
|
|
461
|
+
bundle exec rake compile
|
|
462
|
+
bundle exec rake test
|
|
463
|
+
```
|
|
464
|
+
|
|
465
|
+
The `compile` task invokes `rb_sys/mkmf` which builds the Rust extension into `lib/stoolap/stoolap.<ext>` so the installed gem can `require` it.
|
|
466
|
+
|
|
467
|
+
## Running the test suite
|
|
468
|
+
|
|
469
|
+
```sh
|
|
470
|
+
bundle exec rake test
|
|
471
|
+
```
|
|
472
|
+
|
|
473
|
+
The suite runs against `lib/stoolap.rb` with 100% line coverage (SimpleCov). `lib/stoolap/version.rb` is filtered from the metric because Bundler loads it via the gemspec before SimpleCov can instrument it.
|
|
474
|
+
|
|
475
|
+
## License
|
|
476
|
+
|
|
477
|
+
Apache-2.0. See [LICENSE](LICENSE).
|