postgreslite 1.0.0__tar.gz → 2.0.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.
- postgreslite-2.0.0/PKG-INFO +156 -0
- postgreslite-2.0.0/PostgresLite.egg-info/PKG-INFO +156 -0
- {postgreslite-1.0.0 → postgreslite-2.0.0}/PostgresLite.egg-info/SOURCES.txt +6 -1
- {postgreslite-1.0.0 → postgreslite-2.0.0}/PostgresLite.egg-info/requires.txt +0 -1
- postgreslite-2.0.0/README.md +128 -0
- {postgreslite-1.0.0 → postgreslite-2.0.0}/postgreslite/__init__.py +6 -5
- postgreslite-2.0.0/postgreslite/handler.py +110 -0
- postgreslite-2.0.0/postgreslite/migrations.py +170 -0
- postgreslite-2.0.0/postgreslite/pool.py +864 -0
- postgreslite-2.0.0/postgreslite/schema.py +73 -0
- {postgreslite-1.0.0 → postgreslite-2.0.0}/pyproject.toml +15 -7
- {postgreslite-1.0.0 → postgreslite-2.0.0}/tests/test_async_pool.py +33 -6
- postgreslite-2.0.0/tests/test_datetime_sync.py +69 -0
- postgreslite-2.0.0/tests/test_init.py +54 -0
- postgreslite-2.0.0/tests/test_migrations.py +173 -0
- postgreslite-2.0.0/tests/test_schema.py +91 -0
- postgreslite-2.0.0/tests/test_sql_statements.py +71 -0
- {postgreslite-1.0.0 → postgreslite-2.0.0}/tests/test_sync_pool.py +62 -5
- postgreslite-2.0.0/tests/test_transactions.py +161 -0
- postgreslite-1.0.0/PKG-INFO +0 -103
- postgreslite-1.0.0/PostgresLite.egg-info/PKG-INFO +0 -103
- postgreslite-1.0.0/README.md +0 -85
- postgreslite-1.0.0/postgreslite/handler.py +0 -340
- postgreslite-1.0.0/postgreslite/pool.py +0 -499
- postgreslite-1.0.0/tests/test_datetime_sync.py +0 -42
- postgreslite-1.0.0/tests/test_init.py +0 -25
- postgreslite-1.0.0/tests/test_sql_statements.py +0 -31
- {postgreslite-1.0.0 → postgreslite-2.0.0}/LICENSE +0 -0
- {postgreslite-1.0.0 → postgreslite-2.0.0}/PostgresLite.egg-info/dependency_links.txt +0 -0
- {postgreslite-1.0.0 → postgreslite-2.0.0}/PostgresLite.egg-info/top_level.txt +0 -0
- {postgreslite-1.0.0 → postgreslite-2.0.0}/setup.cfg +0 -0
- {postgreslite-1.0.0 → postgreslite-2.0.0}/tests/test_table_column.py +0 -0
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: PostgresLite
|
|
3
|
+
Version: 2.0.0
|
|
4
|
+
Summary: SQLite for Python with an asyncpg-style API, sync and async.
|
|
5
|
+
Author-email: AlexFlipnote <root@alexflipnote.dev>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/AlexFlipnote/PostgresLite
|
|
8
|
+
Project-URL: Repository, https://github.com/AlexFlipnote/PostgresLite
|
|
9
|
+
Keywords: asyncpg,sqlite,postgres,lite,database,sql
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Framework :: AsyncIO
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Topic :: Database
|
|
21
|
+
Requires-Python: >=3.11.0
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: pyright>=1.1.401; extra == "dev"
|
|
26
|
+
Requires-Dist: ruff>=0.11.13; extra == "dev"
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# PostgresLite
|
|
30
|
+
Python SQLite library built around asyncpg-style syntax.
|
|
31
|
+
|
|
32
|
+
No longer do you need to wrestle with raw SQLite. PostgresLite gives you a cleaner, asyncpg-inspired API with everything you'd expect out of the box:
|
|
33
|
+
- Automatic type conversion for `DATE`, `DATETIME`, `TIMESTAMP`, and `JSON` columns
|
|
34
|
+
- Transactions (and nested savepoints) via context managers
|
|
35
|
+
- asyncpg-style placeholders (`$1`, `$2`, …) and status strings (`"INSERT 0 1"`)
|
|
36
|
+
- Schema dumping and introspection
|
|
37
|
+
- Both sync and async connections, using the same API
|
|
38
|
+
|
|
39
|
+
## Installing
|
|
40
|
+
> You need **Python >=3.11** to use this library.
|
|
41
|
+
|
|
42
|
+
Install by using `pip install postgreslite` in the terminal.
|
|
43
|
+
|
|
44
|
+
## Quick example
|
|
45
|
+
|
|
46
|
+
**Sync**
|
|
47
|
+
```py
|
|
48
|
+
from postgreslite import PostgresLite
|
|
49
|
+
|
|
50
|
+
pool = PostgresLite("./hello_world.db").connect()
|
|
51
|
+
|
|
52
|
+
pool.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL)")
|
|
53
|
+
pool.execute("INSERT INTO users (name) VALUES ($1) ON CONFLICT DO NOTHING", "AlexFlipnote")
|
|
54
|
+
|
|
55
|
+
data = pool.fetch("SELECT * FROM users")
|
|
56
|
+
print(data) # [{'id': 1, 'name': 'AlexFlipnote'}]
|
|
57
|
+
|
|
58
|
+
pool.close()
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
**Async**
|
|
62
|
+
```py
|
|
63
|
+
import asyncio
|
|
64
|
+
from postgreslite import PostgresLite
|
|
65
|
+
|
|
66
|
+
async def main():
|
|
67
|
+
async with PostgresLite("./hello_world.db").connect_async() as pool:
|
|
68
|
+
data = await pool.fetch("SELECT * FROM users")
|
|
69
|
+
|
|
70
|
+
asyncio.run(main())
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Both connection types support the same API: `execute`, `executemany`, `fetch`, `fetchrow`, `fetchval`, `transaction`, `acquire`.
|
|
74
|
+
Queries run in a worker thread on the async connection, so they don't block the event loop.
|
|
75
|
+
|
|
76
|
+
`PostgresLite(filename, timeout=5.0)` accepts a `.db`, `.sqlite`, `.sqlite3` or `.db3` path, a `file:` URI, or `":memory:"`.
|
|
77
|
+
`timeout` is how many seconds to wait on another connection's lock before raising `database is locked`.
|
|
78
|
+
|
|
79
|
+
## Coming from asyncpg
|
|
80
|
+
Most asyncpg code works as-is, including `async with pool.acquire() as conn, conn.transaction():`.
|
|
81
|
+
The differences:
|
|
82
|
+
|
|
83
|
+
| | asyncpg | PostgresLite |
|
|
84
|
+
|---|---|---|
|
|
85
|
+
| Rows | `Record` | `dict` (so no `row[0]`; duplicate column names keep the last one) |
|
|
86
|
+
| `pool.acquire()` | Takes a connection from the pool | Yields the same single connection |
|
|
87
|
+
| Concurrent use | Raises "another operation is in progress" | Queries are queued; an open transaction blocks other tasks until it finishes |
|
|
88
|
+
| `executemany` | Returns `None` | Returns a status, e.g. `"INSERT 0 3"` |
|
|
89
|
+
| Placeholders | `$1` only | `$1` or `?` |
|
|
90
|
+
|
|
91
|
+
## Type handling
|
|
92
|
+
Columns declared as `DATE`, `DATETIME`, `TIMESTAMP`, or `JSON` are automatically converted on read:
|
|
93
|
+
|
|
94
|
+
| Column type | Python type |
|
|
95
|
+
|-------------|-------------|
|
|
96
|
+
| `DATE` | `datetime.date` |
|
|
97
|
+
| `DATETIME` | `datetime.datetime` |
|
|
98
|
+
| `TIMESTAMP` | `datetime.datetime` (converted to UTC) |
|
|
99
|
+
| `JSON` | `dict` / `list` |
|
|
100
|
+
|
|
101
|
+
`date`, `datetime`, `dict` and `list` arguments are converted on write.
|
|
102
|
+
|
|
103
|
+
> The column converters are registered with Python's `sqlite3` module, which is process-wide.
|
|
104
|
+
> They only affect connections opened with `detect_types=sqlite3.PARSE_DECLTYPES`.
|
|
105
|
+
|
|
106
|
+
## Transactions
|
|
107
|
+
```py
|
|
108
|
+
with pool.transaction():
|
|
109
|
+
pool.execute("UPDATE accounts SET balance = balance - 100 WHERE id = 1")
|
|
110
|
+
pool.execute("UPDATE accounts SET balance = balance + 100 WHERE id = 2")
|
|
111
|
+
```
|
|
112
|
+
Rolls back on any error (including cancellation) and re-raises.
|
|
113
|
+
Nested `transaction()` blocks become savepoints, and you can also call `start()`, `commit()` and `rollback()` yourself.
|
|
114
|
+
Async pools use `async with pool.transaction()`.
|
|
115
|
+
|
|
116
|
+
## Migrations
|
|
117
|
+
Put numbered `.sql` files in a folder, and apply the new ones on startup:
|
|
118
|
+
```
|
|
119
|
+
migrations/
|
|
120
|
+
├── 001_init.sql
|
|
121
|
+
├── 002_add_bio.sql
|
|
122
|
+
└── 003_posts.sql
|
|
123
|
+
```
|
|
124
|
+
```py
|
|
125
|
+
applied = pool.migrate("migrations") # ['002_add_bio.sql', '003_posts.sql']
|
|
126
|
+
```
|
|
127
|
+
- Files run in filename order, each in its own transaction, and are recorded in a `_migrations` table, so each one only ever runs once.
|
|
128
|
+
- If a file fails, its changes are rolled back and `MigrationError` is raised. Fix it and run again.
|
|
129
|
+
- Don't edit a migration after it has been applied; add a new one. Edited files raise `MigrationError`.
|
|
130
|
+
- Files must not contain `BEGIN`, `COMMIT`, `ROLLBACK`, `SAVEPOINT` or `RELEASE`.
|
|
131
|
+
- Foreign keys are checked when each file finishes rather than per statement, so you can rebuild a table
|
|
132
|
+
(create the new one, copy the rows, drop the old one, rename) without `ON DELETE CASCADE` wiping related rows.
|
|
133
|
+
- A database that already has tables but no `_migrations` table is assumed to be up to date:
|
|
134
|
+
every current file is recorded as applied without running it.
|
|
135
|
+
|
|
136
|
+
## Schema utilities
|
|
137
|
+
```py
|
|
138
|
+
db = PostgresLite("./hello_world.db")
|
|
139
|
+
|
|
140
|
+
# Dump the current schema as a string, to a file, or to a folder of per-table files
|
|
141
|
+
db.dump_schema()
|
|
142
|
+
db.dump_schema(output="schema.sql")
|
|
143
|
+
db.dump_schema(include_indexes=True, output="schema/")
|
|
144
|
+
|
|
145
|
+
# For ":memory:" databases, dump from the connection instead
|
|
146
|
+
pool.dump_schema()
|
|
147
|
+
```
|
|
148
|
+
The output uses `IF NOT EXISTS`, so it can be run again safely, e.g. with `pool.run_sql("schema.sql")`.
|
|
149
|
+
|
|
150
|
+
## Introspection
|
|
151
|
+
```py
|
|
152
|
+
pool.tables() # ['users', 'posts']
|
|
153
|
+
pool.table_exists("users") # True
|
|
154
|
+
pool.table_columns("users") # [<TableColumn name='id' ...>, ...]
|
|
155
|
+
pool.lastrowid # ID of the last inserted row
|
|
156
|
+
```
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: PostgresLite
|
|
3
|
+
Version: 2.0.0
|
|
4
|
+
Summary: SQLite for Python with an asyncpg-style API, sync and async.
|
|
5
|
+
Author-email: AlexFlipnote <root@alexflipnote.dev>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/AlexFlipnote/PostgresLite
|
|
8
|
+
Project-URL: Repository, https://github.com/AlexFlipnote/PostgresLite
|
|
9
|
+
Keywords: asyncpg,sqlite,postgres,lite,database,sql
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Framework :: AsyncIO
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Topic :: Database
|
|
21
|
+
Requires-Python: >=3.11.0
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: pyright>=1.1.401; extra == "dev"
|
|
26
|
+
Requires-Dist: ruff>=0.11.13; extra == "dev"
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# PostgresLite
|
|
30
|
+
Python SQLite library built around asyncpg-style syntax.
|
|
31
|
+
|
|
32
|
+
No longer do you need to wrestle with raw SQLite. PostgresLite gives you a cleaner, asyncpg-inspired API with everything you'd expect out of the box:
|
|
33
|
+
- Automatic type conversion for `DATE`, `DATETIME`, `TIMESTAMP`, and `JSON` columns
|
|
34
|
+
- Transactions (and nested savepoints) via context managers
|
|
35
|
+
- asyncpg-style placeholders (`$1`, `$2`, …) and status strings (`"INSERT 0 1"`)
|
|
36
|
+
- Schema dumping and introspection
|
|
37
|
+
- Both sync and async connections, using the same API
|
|
38
|
+
|
|
39
|
+
## Installing
|
|
40
|
+
> You need **Python >=3.11** to use this library.
|
|
41
|
+
|
|
42
|
+
Install by using `pip install postgreslite` in the terminal.
|
|
43
|
+
|
|
44
|
+
## Quick example
|
|
45
|
+
|
|
46
|
+
**Sync**
|
|
47
|
+
```py
|
|
48
|
+
from postgreslite import PostgresLite
|
|
49
|
+
|
|
50
|
+
pool = PostgresLite("./hello_world.db").connect()
|
|
51
|
+
|
|
52
|
+
pool.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL)")
|
|
53
|
+
pool.execute("INSERT INTO users (name) VALUES ($1) ON CONFLICT DO NOTHING", "AlexFlipnote")
|
|
54
|
+
|
|
55
|
+
data = pool.fetch("SELECT * FROM users")
|
|
56
|
+
print(data) # [{'id': 1, 'name': 'AlexFlipnote'}]
|
|
57
|
+
|
|
58
|
+
pool.close()
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
**Async**
|
|
62
|
+
```py
|
|
63
|
+
import asyncio
|
|
64
|
+
from postgreslite import PostgresLite
|
|
65
|
+
|
|
66
|
+
async def main():
|
|
67
|
+
async with PostgresLite("./hello_world.db").connect_async() as pool:
|
|
68
|
+
data = await pool.fetch("SELECT * FROM users")
|
|
69
|
+
|
|
70
|
+
asyncio.run(main())
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Both connection types support the same API: `execute`, `executemany`, `fetch`, `fetchrow`, `fetchval`, `transaction`, `acquire`.
|
|
74
|
+
Queries run in a worker thread on the async connection, so they don't block the event loop.
|
|
75
|
+
|
|
76
|
+
`PostgresLite(filename, timeout=5.0)` accepts a `.db`, `.sqlite`, `.sqlite3` or `.db3` path, a `file:` URI, or `":memory:"`.
|
|
77
|
+
`timeout` is how many seconds to wait on another connection's lock before raising `database is locked`.
|
|
78
|
+
|
|
79
|
+
## Coming from asyncpg
|
|
80
|
+
Most asyncpg code works as-is, including `async with pool.acquire() as conn, conn.transaction():`.
|
|
81
|
+
The differences:
|
|
82
|
+
|
|
83
|
+
| | asyncpg | PostgresLite |
|
|
84
|
+
|---|---|---|
|
|
85
|
+
| Rows | `Record` | `dict` (so no `row[0]`; duplicate column names keep the last one) |
|
|
86
|
+
| `pool.acquire()` | Takes a connection from the pool | Yields the same single connection |
|
|
87
|
+
| Concurrent use | Raises "another operation is in progress" | Queries are queued; an open transaction blocks other tasks until it finishes |
|
|
88
|
+
| `executemany` | Returns `None` | Returns a status, e.g. `"INSERT 0 3"` |
|
|
89
|
+
| Placeholders | `$1` only | `$1` or `?` |
|
|
90
|
+
|
|
91
|
+
## Type handling
|
|
92
|
+
Columns declared as `DATE`, `DATETIME`, `TIMESTAMP`, or `JSON` are automatically converted on read:
|
|
93
|
+
|
|
94
|
+
| Column type | Python type |
|
|
95
|
+
|-------------|-------------|
|
|
96
|
+
| `DATE` | `datetime.date` |
|
|
97
|
+
| `DATETIME` | `datetime.datetime` |
|
|
98
|
+
| `TIMESTAMP` | `datetime.datetime` (converted to UTC) |
|
|
99
|
+
| `JSON` | `dict` / `list` |
|
|
100
|
+
|
|
101
|
+
`date`, `datetime`, `dict` and `list` arguments are converted on write.
|
|
102
|
+
|
|
103
|
+
> The column converters are registered with Python's `sqlite3` module, which is process-wide.
|
|
104
|
+
> They only affect connections opened with `detect_types=sqlite3.PARSE_DECLTYPES`.
|
|
105
|
+
|
|
106
|
+
## Transactions
|
|
107
|
+
```py
|
|
108
|
+
with pool.transaction():
|
|
109
|
+
pool.execute("UPDATE accounts SET balance = balance - 100 WHERE id = 1")
|
|
110
|
+
pool.execute("UPDATE accounts SET balance = balance + 100 WHERE id = 2")
|
|
111
|
+
```
|
|
112
|
+
Rolls back on any error (including cancellation) and re-raises.
|
|
113
|
+
Nested `transaction()` blocks become savepoints, and you can also call `start()`, `commit()` and `rollback()` yourself.
|
|
114
|
+
Async pools use `async with pool.transaction()`.
|
|
115
|
+
|
|
116
|
+
## Migrations
|
|
117
|
+
Put numbered `.sql` files in a folder, and apply the new ones on startup:
|
|
118
|
+
```
|
|
119
|
+
migrations/
|
|
120
|
+
├── 001_init.sql
|
|
121
|
+
├── 002_add_bio.sql
|
|
122
|
+
└── 003_posts.sql
|
|
123
|
+
```
|
|
124
|
+
```py
|
|
125
|
+
applied = pool.migrate("migrations") # ['002_add_bio.sql', '003_posts.sql']
|
|
126
|
+
```
|
|
127
|
+
- Files run in filename order, each in its own transaction, and are recorded in a `_migrations` table, so each one only ever runs once.
|
|
128
|
+
- If a file fails, its changes are rolled back and `MigrationError` is raised. Fix it and run again.
|
|
129
|
+
- Don't edit a migration after it has been applied; add a new one. Edited files raise `MigrationError`.
|
|
130
|
+
- Files must not contain `BEGIN`, `COMMIT`, `ROLLBACK`, `SAVEPOINT` or `RELEASE`.
|
|
131
|
+
- Foreign keys are checked when each file finishes rather than per statement, so you can rebuild a table
|
|
132
|
+
(create the new one, copy the rows, drop the old one, rename) without `ON DELETE CASCADE` wiping related rows.
|
|
133
|
+
- A database that already has tables but no `_migrations` table is assumed to be up to date:
|
|
134
|
+
every current file is recorded as applied without running it.
|
|
135
|
+
|
|
136
|
+
## Schema utilities
|
|
137
|
+
```py
|
|
138
|
+
db = PostgresLite("./hello_world.db")
|
|
139
|
+
|
|
140
|
+
# Dump the current schema as a string, to a file, or to a folder of per-table files
|
|
141
|
+
db.dump_schema()
|
|
142
|
+
db.dump_schema(output="schema.sql")
|
|
143
|
+
db.dump_schema(include_indexes=True, output="schema/")
|
|
144
|
+
|
|
145
|
+
# For ":memory:" databases, dump from the connection instead
|
|
146
|
+
pool.dump_schema()
|
|
147
|
+
```
|
|
148
|
+
The output uses `IF NOT EXISTS`, so it can be run again safely, e.g. with `pool.run_sql("schema.sql")`.
|
|
149
|
+
|
|
150
|
+
## Introspection
|
|
151
|
+
```py
|
|
152
|
+
pool.tables() # ['users', 'posts']
|
|
153
|
+
pool.table_exists("users") # True
|
|
154
|
+
pool.table_columns("users") # [<TableColumn name='id' ...>, ...]
|
|
155
|
+
pool.lastrowid # ID of the last inserted row
|
|
156
|
+
```
|
|
@@ -8,10 +8,15 @@ PostgresLite.egg-info/requires.txt
|
|
|
8
8
|
PostgresLite.egg-info/top_level.txt
|
|
9
9
|
postgreslite/__init__.py
|
|
10
10
|
postgreslite/handler.py
|
|
11
|
+
postgreslite/migrations.py
|
|
11
12
|
postgreslite/pool.py
|
|
13
|
+
postgreslite/schema.py
|
|
12
14
|
tests/test_async_pool.py
|
|
13
15
|
tests/test_datetime_sync.py
|
|
14
16
|
tests/test_init.py
|
|
17
|
+
tests/test_migrations.py
|
|
18
|
+
tests/test_schema.py
|
|
15
19
|
tests/test_sql_statements.py
|
|
16
20
|
tests/test_sync_pool.py
|
|
17
|
-
tests/test_table_column.py
|
|
21
|
+
tests/test_table_column.py
|
|
22
|
+
tests/test_transactions.py
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
# PostgresLite
|
|
2
|
+
Python SQLite library built around asyncpg-style syntax.
|
|
3
|
+
|
|
4
|
+
No longer do you need to wrestle with raw SQLite. PostgresLite gives you a cleaner, asyncpg-inspired API with everything you'd expect out of the box:
|
|
5
|
+
- Automatic type conversion for `DATE`, `DATETIME`, `TIMESTAMP`, and `JSON` columns
|
|
6
|
+
- Transactions (and nested savepoints) via context managers
|
|
7
|
+
- asyncpg-style placeholders (`$1`, `$2`, …) and status strings (`"INSERT 0 1"`)
|
|
8
|
+
- Schema dumping and introspection
|
|
9
|
+
- Both sync and async connections, using the same API
|
|
10
|
+
|
|
11
|
+
## Installing
|
|
12
|
+
> You need **Python >=3.11** to use this library.
|
|
13
|
+
|
|
14
|
+
Install by using `pip install postgreslite` in the terminal.
|
|
15
|
+
|
|
16
|
+
## Quick example
|
|
17
|
+
|
|
18
|
+
**Sync**
|
|
19
|
+
```py
|
|
20
|
+
from postgreslite import PostgresLite
|
|
21
|
+
|
|
22
|
+
pool = PostgresLite("./hello_world.db").connect()
|
|
23
|
+
|
|
24
|
+
pool.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL)")
|
|
25
|
+
pool.execute("INSERT INTO users (name) VALUES ($1) ON CONFLICT DO NOTHING", "AlexFlipnote")
|
|
26
|
+
|
|
27
|
+
data = pool.fetch("SELECT * FROM users")
|
|
28
|
+
print(data) # [{'id': 1, 'name': 'AlexFlipnote'}]
|
|
29
|
+
|
|
30
|
+
pool.close()
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
**Async**
|
|
34
|
+
```py
|
|
35
|
+
import asyncio
|
|
36
|
+
from postgreslite import PostgresLite
|
|
37
|
+
|
|
38
|
+
async def main():
|
|
39
|
+
async with PostgresLite("./hello_world.db").connect_async() as pool:
|
|
40
|
+
data = await pool.fetch("SELECT * FROM users")
|
|
41
|
+
|
|
42
|
+
asyncio.run(main())
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Both connection types support the same API: `execute`, `executemany`, `fetch`, `fetchrow`, `fetchval`, `transaction`, `acquire`.
|
|
46
|
+
Queries run in a worker thread on the async connection, so they don't block the event loop.
|
|
47
|
+
|
|
48
|
+
`PostgresLite(filename, timeout=5.0)` accepts a `.db`, `.sqlite`, `.sqlite3` or `.db3` path, a `file:` URI, or `":memory:"`.
|
|
49
|
+
`timeout` is how many seconds to wait on another connection's lock before raising `database is locked`.
|
|
50
|
+
|
|
51
|
+
## Coming from asyncpg
|
|
52
|
+
Most asyncpg code works as-is, including `async with pool.acquire() as conn, conn.transaction():`.
|
|
53
|
+
The differences:
|
|
54
|
+
|
|
55
|
+
| | asyncpg | PostgresLite |
|
|
56
|
+
|---|---|---|
|
|
57
|
+
| Rows | `Record` | `dict` (so no `row[0]`; duplicate column names keep the last one) |
|
|
58
|
+
| `pool.acquire()` | Takes a connection from the pool | Yields the same single connection |
|
|
59
|
+
| Concurrent use | Raises "another operation is in progress" | Queries are queued; an open transaction blocks other tasks until it finishes |
|
|
60
|
+
| `executemany` | Returns `None` | Returns a status, e.g. `"INSERT 0 3"` |
|
|
61
|
+
| Placeholders | `$1` only | `$1` or `?` |
|
|
62
|
+
|
|
63
|
+
## Type handling
|
|
64
|
+
Columns declared as `DATE`, `DATETIME`, `TIMESTAMP`, or `JSON` are automatically converted on read:
|
|
65
|
+
|
|
66
|
+
| Column type | Python type |
|
|
67
|
+
|-------------|-------------|
|
|
68
|
+
| `DATE` | `datetime.date` |
|
|
69
|
+
| `DATETIME` | `datetime.datetime` |
|
|
70
|
+
| `TIMESTAMP` | `datetime.datetime` (converted to UTC) |
|
|
71
|
+
| `JSON` | `dict` / `list` |
|
|
72
|
+
|
|
73
|
+
`date`, `datetime`, `dict` and `list` arguments are converted on write.
|
|
74
|
+
|
|
75
|
+
> The column converters are registered with Python's `sqlite3` module, which is process-wide.
|
|
76
|
+
> They only affect connections opened with `detect_types=sqlite3.PARSE_DECLTYPES`.
|
|
77
|
+
|
|
78
|
+
## Transactions
|
|
79
|
+
```py
|
|
80
|
+
with pool.transaction():
|
|
81
|
+
pool.execute("UPDATE accounts SET balance = balance - 100 WHERE id = 1")
|
|
82
|
+
pool.execute("UPDATE accounts SET balance = balance + 100 WHERE id = 2")
|
|
83
|
+
```
|
|
84
|
+
Rolls back on any error (including cancellation) and re-raises.
|
|
85
|
+
Nested `transaction()` blocks become savepoints, and you can also call `start()`, `commit()` and `rollback()` yourself.
|
|
86
|
+
Async pools use `async with pool.transaction()`.
|
|
87
|
+
|
|
88
|
+
## Migrations
|
|
89
|
+
Put numbered `.sql` files in a folder, and apply the new ones on startup:
|
|
90
|
+
```
|
|
91
|
+
migrations/
|
|
92
|
+
├── 001_init.sql
|
|
93
|
+
├── 002_add_bio.sql
|
|
94
|
+
└── 003_posts.sql
|
|
95
|
+
```
|
|
96
|
+
```py
|
|
97
|
+
applied = pool.migrate("migrations") # ['002_add_bio.sql', '003_posts.sql']
|
|
98
|
+
```
|
|
99
|
+
- Files run in filename order, each in its own transaction, and are recorded in a `_migrations` table, so each one only ever runs once.
|
|
100
|
+
- If a file fails, its changes are rolled back and `MigrationError` is raised. Fix it and run again.
|
|
101
|
+
- Don't edit a migration after it has been applied; add a new one. Edited files raise `MigrationError`.
|
|
102
|
+
- Files must not contain `BEGIN`, `COMMIT`, `ROLLBACK`, `SAVEPOINT` or `RELEASE`.
|
|
103
|
+
- Foreign keys are checked when each file finishes rather than per statement, so you can rebuild a table
|
|
104
|
+
(create the new one, copy the rows, drop the old one, rename) without `ON DELETE CASCADE` wiping related rows.
|
|
105
|
+
- A database that already has tables but no `_migrations` table is assumed to be up to date:
|
|
106
|
+
every current file is recorded as applied without running it.
|
|
107
|
+
|
|
108
|
+
## Schema utilities
|
|
109
|
+
```py
|
|
110
|
+
db = PostgresLite("./hello_world.db")
|
|
111
|
+
|
|
112
|
+
# Dump the current schema as a string, to a file, or to a folder of per-table files
|
|
113
|
+
db.dump_schema()
|
|
114
|
+
db.dump_schema(output="schema.sql")
|
|
115
|
+
db.dump_schema(include_indexes=True, output="schema/")
|
|
116
|
+
|
|
117
|
+
# For ":memory:" databases, dump from the connection instead
|
|
118
|
+
pool.dump_schema()
|
|
119
|
+
```
|
|
120
|
+
The output uses `IF NOT EXISTS`, so it can be run again safely, e.g. with `pool.run_sql("schema.sql")`.
|
|
121
|
+
|
|
122
|
+
## Introspection
|
|
123
|
+
```py
|
|
124
|
+
pool.tables() # ['users', 'posts']
|
|
125
|
+
pool.table_exists("users") # True
|
|
126
|
+
pool.table_columns("users") # [<TableColumn name='id' ...>, ...]
|
|
127
|
+
pool.lastrowid # ID of the last inserted row
|
|
128
|
+
```
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
# ruff: noqa: F403
|
|
2
|
-
from .handler import *
|
|
3
|
-
from .
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
# ruff: noqa: F403
|
|
2
|
+
from .handler import *
|
|
3
|
+
from .migrations import *
|
|
4
|
+
from .pool import *
|
|
5
|
+
|
|
6
|
+
__version__ = "2.0.0"
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import sqlite3
|
|
4
|
+
|
|
5
|
+
from datetime import datetime, date, UTC
|
|
6
|
+
|
|
7
|
+
from .pool import PoolConnection, AsyncPoolConnection
|
|
8
|
+
|
|
9
|
+
__all__ = (
|
|
10
|
+
"PostgresLite",
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
_EXTENSIONS = (".db", ".sqlite", ".sqlite3", ".db3")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def dict_factory(cursor: sqlite3.Cursor, row: tuple) -> dict:
|
|
17
|
+
return {col[0]: value for col, value in zip(cursor.description, row, strict=True)}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _convert_date(val: bytes) -> date:
|
|
21
|
+
return date.fromisoformat(val.decode())
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _convert_datetime(val: bytes) -> datetime:
|
|
25
|
+
return datetime.fromisoformat(val.decode())
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _convert_timestamp(val: bytes) -> datetime:
|
|
29
|
+
dt = datetime.fromisoformat(val.decode())
|
|
30
|
+
if dt.tzinfo is None:
|
|
31
|
+
return dt.replace(tzinfo=UTC)
|
|
32
|
+
return dt.astimezone(UTC)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _convert_json(val: bytes) -> object:
|
|
36
|
+
return json.loads(val.decode())
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# sqlite3 converters are process-wide, so they're registered once here.
|
|
40
|
+
# They only apply to connections opened with detect_types=PARSE_DECLTYPES.
|
|
41
|
+
# Values going in are converted per query instead (see pool._adapt), so sqlite3's adapters are untouched.
|
|
42
|
+
sqlite3.register_converter("date", _convert_date)
|
|
43
|
+
sqlite3.register_converter("datetime", _convert_datetime)
|
|
44
|
+
sqlite3.register_converter("timestamp", _convert_timestamp)
|
|
45
|
+
sqlite3.register_converter("json", _convert_json)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class PostgresLite:
|
|
49
|
+
def __init__(self, filename: str | os.PathLike[str] = "storage.db", *, timeout: float = 5.0):
|
|
50
|
+
"""
|
|
51
|
+
Parameters
|
|
52
|
+
----------
|
|
53
|
+
filename:
|
|
54
|
+
Path to the database file (.db, .sqlite, .sqlite3 or .db3), a 'file:' URI, or ':memory:'.
|
|
55
|
+
timeout:
|
|
56
|
+
How many seconds to wait for another connection's lock before raising 'database is locked'.
|
|
57
|
+
""" # noqa: D205
|
|
58
|
+
self._filename = os.fspath(filename)
|
|
59
|
+
self._timeout = timeout
|
|
60
|
+
self._uri = self._filename.startswith("file:")
|
|
61
|
+
|
|
62
|
+
if self._filename != ":memory:" and not self._uri and not self._filename.endswith(_EXTENSIONS):
|
|
63
|
+
raise ValueError(f"Database filename must end with one of: {', '.join(_EXTENSIONS)}")
|
|
64
|
+
|
|
65
|
+
def _connect(self, *, check_same_thread: bool) -> sqlite3.Connection:
|
|
66
|
+
conn = sqlite3.connect(
|
|
67
|
+
self._filename,
|
|
68
|
+
timeout=self._timeout,
|
|
69
|
+
isolation_level=None,
|
|
70
|
+
check_same_thread=check_same_thread,
|
|
71
|
+
detect_types=sqlite3.PARSE_DECLTYPES,
|
|
72
|
+
uri=self._uri,
|
|
73
|
+
)
|
|
74
|
+
conn.row_factory = dict_factory
|
|
75
|
+
conn.execute("PRAGMA journal_mode=WAL")
|
|
76
|
+
conn.execute("PRAGMA foreign_keys = ON")
|
|
77
|
+
return conn
|
|
78
|
+
|
|
79
|
+
def connect(self) -> PoolConnection:
|
|
80
|
+
""" Makes a connection to the database and returns the pool (sync). """
|
|
81
|
+
return PoolConnection(self._connect(check_same_thread=True))
|
|
82
|
+
|
|
83
|
+
def connect_async(self) -> AsyncPoolConnection:
|
|
84
|
+
""" Makes a connection to the database and returns the pool (async). """
|
|
85
|
+
return AsyncPoolConnection(self._connect(check_same_thread=False))
|
|
86
|
+
|
|
87
|
+
def dump_schema(self, include_indexes: bool = False, output: str | os.PathLike[str] | None = None) -> str:
|
|
88
|
+
"""
|
|
89
|
+
Returns the current database schema as a SQL string.
|
|
90
|
+
|
|
91
|
+
Parameters
|
|
92
|
+
----------
|
|
93
|
+
include_indexes:
|
|
94
|
+
Whether to include CREATE INDEX statements in the output (default False).
|
|
95
|
+
output:
|
|
96
|
+
If a path ending in '.sql', writes the full schema to that file.
|
|
97
|
+
If a folder path, writes one '{table}.sql' file per table with indexes appended.
|
|
98
|
+
If None, no file is written.
|
|
99
|
+
|
|
100
|
+
Returns
|
|
101
|
+
-------
|
|
102
|
+
The full schema as a SQL string, regardless of output mode.
|
|
103
|
+
"""
|
|
104
|
+
if self._filename == ":memory:":
|
|
105
|
+
raise ValueError(
|
|
106
|
+
"An in-memory database only exists on its own connection, "
|
|
107
|
+
"use dump_schema() on that connection instead"
|
|
108
|
+
)
|
|
109
|
+
with self.connect() as conn:
|
|
110
|
+
return conn.dump_schema(include_indexes, output)
|