sqlite3ttl 0.2.0__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.
- sqlite3ttl-0.2.0/LICENSE +202 -0
- sqlite3ttl-0.2.0/MANIFEST.in +12 -0
- sqlite3ttl-0.2.0/Makefile +22 -0
- sqlite3ttl-0.2.0/PKG-INFO +380 -0
- sqlite3ttl-0.2.0/README.md +361 -0
- sqlite3ttl-0.2.0/benchmark.py +112 -0
- sqlite3ttl-0.2.0/demo.py +61 -0
- sqlite3ttl-0.2.0/pyproject.toml +31 -0
- sqlite3ttl-0.2.0/setup.cfg +4 -0
- sqlite3ttl-0.2.0/setup.py +96 -0
- sqlite3ttl-0.2.0/sqlite3ttl/__init__.py +73 -0
- sqlite3ttl-0.2.0/sqlite3ttl/__main__.py +87 -0
- sqlite3ttl-0.2.0/sqlite3ttl/guard.py +172 -0
- sqlite3ttl-0.2.0/sqlite3ttl.egg-info/PKG-INFO +380 -0
- sqlite3ttl-0.2.0/sqlite3ttl.egg-info/SOURCES.txt +24 -0
- sqlite3ttl-0.2.0/sqlite3ttl.egg-info/dependency_links.txt +1 -0
- sqlite3ttl-0.2.0/sqlite3ttl.egg-info/entry_points.txt +2 -0
- sqlite3ttl-0.2.0/sqlite3ttl.egg-info/top_level.txt +1 -0
- sqlite3ttl-0.2.0/sqlite_ttl.c +517 -0
- sqlite3ttl-0.2.0/test_guard.py +141 -0
- sqlite3ttl-0.2.0/test_packaging.py +60 -0
- sqlite3ttl-0.2.0/test_ttl.py +361 -0
- sqlite3ttl-0.2.0/ttl_platform.h +88 -0
- sqlite3ttl-0.2.0/vendor/README.md +12 -0
- sqlite3ttl-0.2.0/vendor/sqlite3.h +13257 -0
- sqlite3ttl-0.2.0/vendor/sqlite3ext.h +719 -0
sqlite3ttl-0.2.0/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
include sqlite_ttl.c
|
|
2
|
+
include ttl_platform.h
|
|
3
|
+
include README.md
|
|
4
|
+
include Makefile
|
|
5
|
+
include demo.py
|
|
6
|
+
include benchmark.py
|
|
7
|
+
include test_ttl.py
|
|
8
|
+
include test_guard.py
|
|
9
|
+
include test_packaging.py
|
|
10
|
+
recursive-include vendor *.h *.md
|
|
11
|
+
global-exclude *.dylib *.so *.dll
|
|
12
|
+
include LICENSE
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
CC ?= cc
|
|
2
|
+
CFLAGS ?= -O2 -g -Wall -Wextra -Werror
|
|
3
|
+
PYTHON ?= python3
|
|
4
|
+
UNAME := $(shell uname -s)
|
|
5
|
+
ifeq ($(UNAME),Darwin)
|
|
6
|
+
EXT := dylib
|
|
7
|
+
SHARED := -dynamiclib
|
|
8
|
+
else
|
|
9
|
+
EXT := so
|
|
10
|
+
SHARED := -shared
|
|
11
|
+
endif
|
|
12
|
+
|
|
13
|
+
.PHONY: all demo test clean
|
|
14
|
+
all: sqlite-ttl.$(EXT)
|
|
15
|
+
sqlite-ttl.$(EXT): sqlite_ttl.c ttl_platform.h
|
|
16
|
+
$(CC) $(CPPFLAGS) $(CFLAGS) -std=c11 -fPIC $(SHARED) -pthread -o $@ $<
|
|
17
|
+
demo: all
|
|
18
|
+
$(PYTHON) demo.py
|
|
19
|
+
test: all
|
|
20
|
+
$(PYTHON) -m unittest -v test_ttl
|
|
21
|
+
clean:
|
|
22
|
+
rm -f sqlite-ttl.dylib sqlite-ttl.so
|
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sqlite3ttl
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Automatic row expiration for ordinary SQLite tables
|
|
5
|
+
Author: Grant Jenks
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Repository, https://github.com/grantjenks/sqlite-ttl
|
|
8
|
+
Classifier: Development Status :: 4 - Beta
|
|
9
|
+
Classifier: Programming Language :: C
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Operating System :: MacOS :: MacOS X
|
|
12
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
13
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
14
|
+
Classifier: Topic :: Database
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# SQLite TTL
|
|
21
|
+
|
|
22
|
+
Automatic expiration for rows in ordinary SQLite tables.
|
|
23
|
+
|
|
24
|
+
SQLite is an excellent embedded database. I'd like to be able to take any existing table, specify a time to live (TTL) for some of its rows, and have SQLite delete them when they expire. I don't want to change how I query the table, rebuild its indexes, or remember to run a cleanup job.
|
|
25
|
+
|
|
26
|
+
The idea is to make expiration work more like auto-vacuum: configure it once and let maintenance happen automatically.
|
|
27
|
+
|
|
28
|
+
**Status:** v0.2.0 beta. Native C maintenance, Python installation helpers, a guarded connection and a standalone maintenance command. The extension is not intended for production-critical data or hard security deadlines yet.
|
|
29
|
+
|
|
30
|
+
## Quickstart
|
|
31
|
+
|
|
32
|
+
Install the beta package containing the native SQLite extension:
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
pip install sqlite3ttl
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Then register the extension once in the Python process:
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
import sqlite3
|
|
42
|
+
import sqlite3ttl
|
|
43
|
+
import time
|
|
44
|
+
|
|
45
|
+
sqlite3ttl.install()
|
|
46
|
+
|
|
47
|
+
db = sqlite3.connect("example.db")
|
|
48
|
+
db.execute("CREATE TABLE IF NOT EXISTS sessions (id INTEGER PRIMARY KEY, data TEXT)")
|
|
49
|
+
db.execute("SELECT ttl_enable('sessions')")
|
|
50
|
+
|
|
51
|
+
with db:
|
|
52
|
+
db.execute("INSERT OR REPLACE INTO sessions (id, data) VALUES (42, 'temporary')")
|
|
53
|
+
db.execute("SELECT ttl_set('sessions', 42, 2)")
|
|
54
|
+
|
|
55
|
+
print(db.execute("SELECT * FROM sessions").fetchall())
|
|
56
|
+
# [(42, 'temporary')]
|
|
57
|
+
|
|
58
|
+
time.sleep(3)
|
|
59
|
+
|
|
60
|
+
print(db.execute("SELECT * FROM sessions").fetchall())
|
|
61
|
+
# []
|
|
62
|
+
|
|
63
|
+
db.close()
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
The Python code never runs a cleanup job. The native extension does that automatically, even while Python sleeps. There is no replacement SQLite adapter and no changes to ordinary SQL queries.
|
|
67
|
+
|
|
68
|
+
This is an early beta-quality release distributed as the normal package version `0.2.0`. If the PyPI upload is still pending, download a wheel or source distribution from the [GitHub release](https://github.com/grantjenks/sqlite-ttl/releases).
|
|
69
|
+
|
|
70
|
+
## UUID Primary Keys
|
|
71
|
+
|
|
72
|
+
A TTL table can use an INTEGER, TEXT, or BLOB primary key. For example, use a compact UUID:
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
import uuid
|
|
76
|
+
|
|
77
|
+
db.execute("""
|
|
78
|
+
CREATE TABLE jobs (
|
|
79
|
+
id BLOB PRIMARY KEY NOT NULL,
|
|
80
|
+
payload TEXT
|
|
81
|
+
) WITHOUT ROWID
|
|
82
|
+
""")
|
|
83
|
+
db.execute("SELECT ttl_enable('jobs')")
|
|
84
|
+
|
|
85
|
+
id = uuid.uuid4().bytes
|
|
86
|
+
|
|
87
|
+
with db:
|
|
88
|
+
db.execute("INSERT INTO jobs VALUES (?, ?)", (id, "temporary job"))
|
|
89
|
+
db.execute("SELECT ttl_set('jobs', ?, 60)", (id,))
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
For a textual UUID, declare `id TEXT PRIMARY KEY NOT NULL` and use `str(uuid.uuid4())`. The extension stores the actual SQLite primary-key value, including the storage class. Numeric-looking strings such as `"001"` and `"1"` remain distinct. TTL scheduling resolves the actual key using the target table's collation, and deletion or a change of key clears its expiration.
|
|
93
|
+
|
|
94
|
+
## Working Python Demo
|
|
95
|
+
|
|
96
|
+
You can also build the shared library and load it directly using Python's standard SQLite adapter. This is the same behavior with the installation steps exposed:
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
import sqlite3
|
|
100
|
+
import tempfile
|
|
101
|
+
import time
|
|
102
|
+
from pathlib import Path
|
|
103
|
+
|
|
104
|
+
extension = Path("sqlite-ttl.dylib").resolve() # .so on Linux, .dll on Windows
|
|
105
|
+
|
|
106
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
107
|
+
path = Path(tmp) / "example.db"
|
|
108
|
+
db = sqlite3.connect(path)
|
|
109
|
+
|
|
110
|
+
db.enable_load_extension(True)
|
|
111
|
+
try:
|
|
112
|
+
db.load_extension(str(extension))
|
|
113
|
+
finally:
|
|
114
|
+
db.enable_load_extension(False)
|
|
115
|
+
|
|
116
|
+
db.execute("SELECT ttl_auto_register()")
|
|
117
|
+
db.execute("CREATE TABLE sessions (id INTEGER PRIMARY KEY, data TEXT)")
|
|
118
|
+
db.execute("SELECT ttl_enable('sessions')")
|
|
119
|
+
|
|
120
|
+
with db:
|
|
121
|
+
db.executemany(
|
|
122
|
+
"INSERT INTO sessions VALUES (?, ?)",
|
|
123
|
+
[(1, "temporary"), (2, "permanent")],
|
|
124
|
+
)
|
|
125
|
+
db.execute("SELECT ttl_set('sessions', 1, 2)")
|
|
126
|
+
|
|
127
|
+
print(db.execute("SELECT * FROM sessions").fetchall())
|
|
128
|
+
# [(1, 'temporary'), (2, 'permanent')]
|
|
129
|
+
|
|
130
|
+
time.sleep(3)
|
|
131
|
+
|
|
132
|
+
print(db.execute("SELECT * FROM sessions").fetchall())
|
|
133
|
+
# [(2, 'permanent')]
|
|
134
|
+
|
|
135
|
+
db.close()
|
|
136
|
+
|
|
137
|
+
# Registered automatically: no need to load the extension again.
|
|
138
|
+
db = sqlite3.connect(path)
|
|
139
|
+
print(db.execute("SELECT ttl_status()").fetchone())
|
|
140
|
+
db.close()
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
See [demo.py](demo.py) for the tested demonstration, which also verifies shutdown on the last connection close and automatic catch-up on reopening.
|
|
144
|
+
|
|
145
|
+
## Python Packaging
|
|
146
|
+
|
|
147
|
+
I'd like `sqlite3ttl` to be primarily distributed as a Python package, while keeping the extension itself usable independently of Python.
|
|
148
|
+
|
|
149
|
+
The package:
|
|
150
|
+
|
|
151
|
+
- Ship precompiled native SQLite loadable extensions in platform-specific wheels for Linux, macOS, and Windows.
|
|
152
|
+
- Build the extension from C when installing from source.
|
|
153
|
+
- Locate the bundled shared library using Python's package resources.
|
|
154
|
+
- Offer `sqlite3ttl.install()` to register the native extension once for all future connections opened by the standard `sqlite3` module. Internally, it can load the bundled library on a temporary bootstrap connection, invoke `ttl_auto_register()`, then close that connection.
|
|
155
|
+
- Offer `sqlite3ttl.load(connection)` for applications that want to enable TTL on an existing connection without process-wide registration.
|
|
156
|
+
- Keep loading explicit rather than silently modifying process-wide SQLite behavior on import. An import alone can expose the helpers; one call to `install()` opts in automatically for future connections.
|
|
157
|
+
- Disable native extension loading after loading the bundled library (the Python adapter has no getter for the previous policy). Report a clear error if the installed adapter does not support native extension loading.
|
|
158
|
+
|
|
159
|
+
No Python maintenance thread, Python callbacks, monkey-patching, or custom connection wrapper should be necessary for ordinary maintenance. The Python package is a small distribution and initialization layer, not the implementation. The native extension should use SQLite's extension API rather than linking a second copy of SQLite into the application.
|
|
160
|
+
|
|
161
|
+
## Build and Run
|
|
162
|
+
|
|
163
|
+
On Linux, install a C compiler, pthreads, and SQLite development headers:
|
|
164
|
+
|
|
165
|
+
```sh
|
|
166
|
+
make
|
|
167
|
+
make demo
|
|
168
|
+
make test
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
On macOS, the SDK SQLite header disables extension loading. Use the vendored upstream SQLite development headers and a Python build that supports SQLite extensions. Tested on Apple Silicon with MacPorts headers and CPython 3.14 managed by uv:
|
|
172
|
+
|
|
173
|
+
```sh
|
|
174
|
+
make CPPFLAGS=-Ivendor
|
|
175
|
+
make demo test PYTHON='uv run --no-project --python 3.14 python'
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
On Windows, build from source with a Visual Studio C/C++ compiler toolchain using `python -m pip install .` (the package builds the native DLL).
|
|
179
|
+
|
|
180
|
+
The beta polls every 100 ms and deletes at most 100 rows per transaction by default; both are configurable. Time is whole Unix seconds. Implemented SQL APIs: `ttl_enable(table)`, `ttl_set(table, id, integer_seconds)`, `ttl_clear(table, id)`, `ttl_status()`, `ttl_auto_register()`, and `ttl_config(name[, value])`.
|
|
181
|
+
|
|
182
|
+
This is soft TTL: an expired row remains visible until maintenance deletes it. The beta supports ordinary writable file databases, a single explicit INTEGER, TEXT, or BLOB PRIMARY KEY, native platform threads, schemas without connection-specific custom functions or collations, and trusted application-managed databases. Python ≥3.9 with SQLite ≥3.31 and extension loading enabled is required; the Windows wheel matrix tests CPython 3.11–3.14. Linux, macOS, and Windows are supported targets; Windows normally requires official CPython 3.11 or later for loadable SQLite extension support. On Unix, do not fork after loading the extension; use spawn or exec and fresh connections in the child. Do not rename or replace a live database file, and configure TTL before opening multiple participating connections. Connection-specific custom functions and collations are not supported. An expired row blocked by a constraint or trigger retains its deadline and may delay later expirations; health status reports the failure.
|
|
183
|
+
|
|
184
|
+
## Why Not Virtual Tables?
|
|
185
|
+
|
|
186
|
+
My original idea was a virtual table backed by a normal SQLite table with an expiration predicate implicitly added to every query. That would provide hard TTL semantics, but we'd need to recreate a fair amount of SQLite's table interface, including index selection and conflict handling. Virtual tables also don't support some ordinary SQL features, such as UPSERT.
|
|
187
|
+
|
|
188
|
+
I think soft TTL is a useful alternative in its own right:
|
|
189
|
+
|
|
190
|
+
- Existing tables and indexes stay as they are.
|
|
191
|
+
- Normal reads use SQLite's normal query planner, without an extra predicate or join.
|
|
192
|
+
- Foreign keys, triggers, constraints, and UPSERT retain their ordinary semantics.
|
|
193
|
+
- Rows without TTL need no expiration metadata.
|
|
194
|
+
- The application doesn't need to schedule cleanup itself.
|
|
195
|
+
|
|
196
|
+
The cost is that an expired row remains a real row until it is deleted. For many caches and retention policies, that's a reasonable tradeoff. This is not suitable for enforcing an exact authorization or security deadline.
|
|
197
|
+
|
|
198
|
+
## Expiration Metadata
|
|
199
|
+
|
|
200
|
+
Keep a separate ordinary table of scheduled expirations, managed by the extension.
|
|
201
|
+
|
|
202
|
+
```sql
|
|
203
|
+
CREATE TABLE _ttl_entries (
|
|
204
|
+
table_id INTEGER NOT NULL,
|
|
205
|
+
row_id BLOB NOT NULL,
|
|
206
|
+
set_at INTEGER NOT NULL,
|
|
207
|
+
ttl_seconds INTEGER NOT NULL,
|
|
208
|
+
expires_at INTEGER NOT NULL,
|
|
209
|
+
PRIMARY KEY (table_id, row_id)
|
|
210
|
+
);
|
|
211
|
+
|
|
212
|
+
CREATE INDEX _ttl_due ON _ttl_entries (expires_at, table_id, row_id);
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
A separate registry maps table IDs to registered table names and primary-key columns. Initially, require an explicitly declared INTEGER, TEXT, or BLOB PRIMARY KEY, rather than an anonymous rowid or arbitrary composite key.
|
|
216
|
+
|
|
217
|
+
The metadata key uses BLOB affinity (no coercion) regardless of the target primary key type. Databases created by the initial integer-only prototype keep working for integer keys; for non-integer keys, create a fresh prototype database until a metadata migration is implemented.
|
|
218
|
+
|
|
219
|
+
The indexed absolute deadline makes finding the next expiration cheap. The original time and TTL are useful for inspection. A later version could use a generated column for the deadline.
|
|
220
|
+
|
|
221
|
+
`ttl_set(table, id, seconds)` sets or replaces a deadline for an existing row. `ttl_clear(table, id)` removes it. No TTL entry means the row never expires. Setting an expiration in the past makes it immediately eligible for cleanup. The metadata is part of the enclosing transaction, including rollback and savepoints.
|
|
222
|
+
|
|
223
|
+
## Automatic Maintenance
|
|
224
|
+
|
|
225
|
+
Maintenance is the interesting part of the project. I'd like to make it difficult for a user to accidentally stop expiring rows.
|
|
226
|
+
|
|
227
|
+
### A Background Worker
|
|
228
|
+
|
|
229
|
+
The extension automatically starts a worker thread inside the application process, using its own SQLite connection to the same database file. It checks the indexed expiration queue on a configurable interval without taking the write lock when nothing is due.
|
|
230
|
+
|
|
231
|
+
When there are due rows, it runs a small write transaction:
|
|
232
|
+
|
|
233
|
+
1. Acquire the write transaction before selecting due entries.
|
|
234
|
+
2. Select a bounded batch in deadline order.
|
|
235
|
+
3. Revalidate the current metadata and registered table identity.
|
|
236
|
+
4. Delete the corresponding rows using parameterized primary-key lookups.
|
|
237
|
+
5. Remove the corresponding expiration entries and commit.
|
|
238
|
+
|
|
239
|
+
The actual deletion and metadata changes must be atomic. A crash or rollback should leave both unchanged. Expiration renewal and clearing must serialize with cleanup through SQLite's normal write locking.
|
|
240
|
+
|
|
241
|
+
Keep transactions short and use bounded busy handling and retry with backoff. If there's a backlog, process additional batches without monopolizing the database. Report foreign-key restrictions or trigger failures rather than silently discarding scheduled expirations.
|
|
242
|
+
|
|
243
|
+
A worker connection must enable foreign-key enforcement and any other required connection settings, functions or collations. If it cannot reproduce the database's required behavior, it must report an error rather than deleting unsafely.
|
|
244
|
+
|
|
245
|
+
### Startup and Shutdown
|
|
246
|
+
|
|
247
|
+
The desired lifecycle is automatic: opening the first participating connection to a configured database starts maintenance, and closing the last participating connection stops it.
|
|
248
|
+
|
|
249
|
+
- Register the extension once in the application process with [sqlite3_auto_extension()](https://sqlite.org/c3ref/auto_extension.html), or load it explicitly on each connection. Dynamic automatic registration requires keeping the extension library resident (see [persistent loadable extensions](https://sqlite.org/loadext.html)).
|
|
250
|
+
- On initialization, inspect the database for persisted TTL configuration. Start maintenance when TTL is enabled; enabling it for the first time on an existing connection should also start maintenance.
|
|
251
|
+
- Share one worker per supported database file per process, with a reference count of participating application connections. Exclude internal worker connections from automatic worker registration to prevent recursive startup.
|
|
252
|
+
- Tie each participating connection's reference to an extension-owned SQL function registered using [sqlite3_create_function_v2()](https://sqlite.org/c3ref/create_function.html), whose destructor releases that reference when the connection is destroyed. Account for function replacement, initialization failures and deferred destruction with sqlite3_close_v2().
|
|
253
|
+
- When the final reference is released, cancel pending waits and stop the worker promptly. Ensure shutdown cannot deadlock on locks held by a closing connection; verify worker lifetime, cancellation and library unload behavior before relying on this mechanism.
|
|
254
|
+
- Catch up after downtime or application restart. Coordinate competing processes with ordinary SQLite write transactions.
|
|
255
|
+
- A standalone maintenance executable is optional for databases that must expire rows even while the application is stopped.
|
|
256
|
+
|
|
257
|
+
The database file cannot load native code by itself; applications must explicitly load or register the extension. Once registered, no user-installed timer, cleanup hook, or repeated start call should be necessary. SQLite must support threaded use. The worker uses pthreads on Unix and native Windows threads, SRW locks and condition variables on Windows. Initially limit support to normal writable file databases.
|
|
258
|
+
|
|
259
|
+
### Why Not a Commit Hook?
|
|
260
|
+
|
|
261
|
+
SQLite's full [auto-vacuum](https://sqlite.org/pragma.html#pragma_auto_vacuum) runs at commit. That is the experience I'd like, but SQLite's [commit hook](https://sqlite.org/c3ref/commit_hook.html) cannot execute changes on the connection that invoked it. The progress handler has similar restrictions.
|
|
262
|
+
|
|
263
|
+
A WAL hook can perform post-commit maintenance, but that introduces callback ownership, recursion and checkpoint coordination, and misses idle databases. An auto-vacuum callback only controls page reclamation. Neither is needed for the initial design if the worker lifecycle is automatic.
|
|
264
|
+
|
|
265
|
+
## Fail-Safe Maintenance
|
|
266
|
+
|
|
267
|
+
Could we block queries when maintenance has fallen too far behind? I think that's worth exploring.
|
|
268
|
+
|
|
269
|
+
The important measurement is not merely whether a worker is alive. It's whether maintenance is actually keeping up with expirations.
|
|
270
|
+
|
|
271
|
+
Record and expose:
|
|
272
|
+
|
|
273
|
+
- The last successful maintenance check, including checks that found nothing due.
|
|
274
|
+
- The earliest outstanding expiration and its age.
|
|
275
|
+
- The number of overdue entries (optionally measured on demand).
|
|
276
|
+
- The last maintenance error, retry count, and whether the worker is running.
|
|
277
|
+
- The time through which the worker has verified that all due entries have been processed.
|
|
278
|
+
|
|
279
|
+
A heartbeat alone is insufficient. A worker could be checking the database every second while repeatedly failing to delete an overdue row. Conversely, an idle database with no pending expirations is not necessarily unhealthy.
|
|
280
|
+
|
|
281
|
+
### Maintenance Policies
|
|
282
|
+
|
|
283
|
+
The following native settings are persisted per database after registering a TTL table:
|
|
284
|
+
|
|
285
|
+
```sql
|
|
286
|
+
SELECT ttl_config('poll_interval_ms', 100);
|
|
287
|
+
SELECT ttl_config('batch_size', 100);
|
|
288
|
+
SELECT ttl_config('max_lag_seconds', 60);
|
|
289
|
+
SELECT ttl_status();
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
The first two govern worker polling and batch size. The third is a stored application policy hint (the optional Python guard uses its own explicit settings). Status reports the last successful maintenance check, last SQLite result code, earliest expiry, overdue age and consecutive errors.
|
|
293
|
+
|
|
294
|
+
Ordinary SQLite queries continue regardless of maintenance health. To opt into fail-closed query admission, use the guard:
|
|
295
|
+
|
|
296
|
+
```python
|
|
297
|
+
from sqlite3ttl.guard import guarded_connect, TTLUnavailableError
|
|
298
|
+
|
|
299
|
+
db = guarded_connect(
|
|
300
|
+
"example.db",
|
|
301
|
+
max_lag_seconds=60,
|
|
302
|
+
max_check_age_seconds=5,
|
|
303
|
+
on_stale="error", # or "wait"
|
|
304
|
+
)
|
|
305
|
+
try:
|
|
306
|
+
rows = db.execute("SELECT * FROM sessions").fetchall()
|
|
307
|
+
except TTLUnavailableError:
|
|
308
|
+
# Handle stale or failed maintenance explicitly.
|
|
309
|
+
raise
|
|
310
|
+
finally:
|
|
311
|
+
db.close()
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
Use a configured database. The guard checks before connection/cursor execute, executemany and executescript (once per script). Wait mode has a bounded timeout and will not wait while a transaction holds locks. Commit, rollback, and close remain available. An ordinary connection can be used for diagnostics or repairs.
|
|
315
|
+
|
|
316
|
+
### Where To Enforce the Policy
|
|
317
|
+
|
|
318
|
+
SQLite's [authorizer](https://sqlite.org/c3ref/set_authorizer.html) can reject access during statement preparation. This is worth investigating for a best-effort extension-only guard, but it is not sufficient for reliable enforcement: already-prepared statements may execute again without authorization, callbacks must not perform SQL on the invoking connection, and an application can open the database without loading the extension.
|
|
319
|
+
|
|
320
|
+
For stronger enforcement, use the optional connection wrapper that checks maintenance health before executing or reusing prepared statements, and before admitting a new transaction. It can wait for the worker outside transactions or fail with a specific error. It must not wait for a worker while holding a lock the worker needs.
|
|
321
|
+
|
|
322
|
+
A wrapper protects only clients using it. Long-running queries and read transactions can retain older SQLite snapshots after cleanup commits; a strict lag policy would also need to bound or reject stale snapshots and long-running operations. Do not claim hard TTL or a global availability guarantee.
|
|
323
|
+
|
|
324
|
+
The beta guard implements this cooperating-client admission check, not hard TTL or a security boundary.
|
|
325
|
+
|
|
326
|
+
## Standalone Maintenance
|
|
327
|
+
|
|
328
|
+
To keep the native worker running even when no other application has the database open:
|
|
329
|
+
|
|
330
|
+
```sh
|
|
331
|
+
sqlite3ttl example.db
|
|
332
|
+
# Or: python -m sqlite3ttl example.db
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
The command accepts one or more existing configured databases, reports maintenance errors, and stops cleanly on SIGINT/SIGTERM (Ctrl+C or Ctrl+Break on Windows). The process only holds SQLite connections; expiry is still performed by C.
|
|
336
|
+
|
|
337
|
+
## Row Identity and Schema Changes
|
|
338
|
+
|
|
339
|
+
An expiration belongs to a particular row's lifetime, not simply to a numeric key. If row 42 is deleted and reinserted, it should not inherit row 42's previous expiration.
|
|
340
|
+
|
|
341
|
+
Install ordinary triggers on registered tables to clear metadata when a row is deleted or its key changes. Account for SQLite's REPLACE behavior: its implicit delete triggers depend on recursive triggers being enabled. Test replacement, key reuse and foreign-key cascades; if necessary, add insert-side metadata cleanup to ensure a replacement cannot inherit the previous deadline. Require supported trigger settings and validate invariants before trusting metadata.
|
|
342
|
+
|
|
343
|
+
Table registration should persist a stable identity and validate the schema. A dropped and recreated table with the same name must not inherit old expiration entries. Schema changes should go through explicit unregister/re-register operations initially, and maintenance should stop on a registration mismatch rather than risk deleting from the wrong table.
|
|
344
|
+
|
|
345
|
+
Automatic maintenance must be safe under crash recovery, concurrent writes, restore from backup, clock changes, expired-row renewal, and disk-full or read-only errors. Physical deletion is separate from reclaiming file space; SQLite's normal vacuum options continue to work.
|
|
346
|
+
|
|
347
|
+
## Beta Checklist
|
|
348
|
+
|
|
349
|
+
- [x] Python package, source distribution, native platform wheel and installation/loading helpers.
|
|
350
|
+
- [x] Native C extension with persistent metadata, INTEGER/TEXT/BLOB keys and transactional set/clear.
|
|
351
|
+
- [x] Indexed, bounded expiration batches and automatic worker lifecycle.
|
|
352
|
+
- [x] Startup catch-up, clean shutdown, contention handling and retry.
|
|
353
|
+
- [x] Maintenance configuration, last check, last error, next expiry and overdue age.
|
|
354
|
+
- [x] Integration coverage for crash/rollback, concurrent renewal, replacement/key reuse, schema changes, foreign keys, worker failure and recovery.
|
|
355
|
+
- [x] Benchmark ordinary reads, scheduled writes and expiration throughput.
|
|
356
|
+
- [x] Optional fail-closed connection guard and standalone maintenance command.
|
|
357
|
+
|
|
358
|
+
## Benchmark
|
|
359
|
+
|
|
360
|
+
Run `python benchmark.py --rows 2000 --reads 100000` against a built extension. An initial Apple Silicon/macOS run (CPython 3.14, SQLite 3.50.4) measured roughly 741k ordinary indexed reads/s and 737k TTL-table reads/s, 59k scheduled expirations/s and 899 automatic expirations/s with the default batch size and polling interval. These are preliminary local measurements, not cross-platform guarantees. Ordinary queries incur no TTL predicate or join; registration adds write-side trigger and metadata overhead.
|
|
361
|
+
|
|
362
|
+
The main success criterion: add TTL to an existing SQLite table without changing how it is queried or having to remember cleanup. If maintenance stops working, inspect status or choose guarded query admission.
|
|
363
|
+
|
|
364
|
+
## License
|
|
365
|
+
|
|
366
|
+
Apache-2.0. Vendored SQLite headers retain their upstream public-domain notices.
|
|
367
|
+
|
|
368
|
+
## Related Work
|
|
369
|
+
|
|
370
|
+
- [DiskCache](https://grantjenks.com/docs/diskcache/tutorial.html) provides per-key TTL on SQLite through a Python cache API. Its expiration machinery is worth studying.
|
|
371
|
+
- [sqlite3-partitioner](https://github.com/nuuskamummu/Sqlite3_partitioner) uses time-partitioned virtual tables and explicit partition cleanup, rather than expiring individual rows in existing tables.
|
|
372
|
+
- SQLite's [echo virtual table](https://github.com/sqlite/sqlite/blob/master/src/test8.c) wraps an ordinary table and is a useful reference if we revisit the hard TTL design.
|
|
373
|
+
|
|
374
|
+
## References
|
|
375
|
+
|
|
376
|
+
- [SQLite Run-Time Loadable Extensions](https://sqlite.org/loadext.html)
|
|
377
|
+
- [SQLite Auto-Extension Registration](https://sqlite.org/c3ref/auto_extension.html)
|
|
378
|
+
- [SQLite Transactions](https://sqlite.org/lang_transaction.html)
|
|
379
|
+
- [SQLite Commit Hooks](https://sqlite.org/c3ref/commit_hook.html)
|
|
380
|
+
- [SQLite Authorizer](https://sqlite.org/c3ref/set_authorizer.html)
|