postgreslite 0.2.1__tar.gz → 1.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-1.0.0/PKG-INFO +103 -0
- postgreslite-1.0.0/PostgresLite.egg-info/PKG-INFO +103 -0
- {postgreslite-0.2.1 → postgreslite-1.0.0}/PostgresLite.egg-info/SOURCES.txt +6 -1
- postgreslite-1.0.0/README.md +85 -0
- {postgreslite-0.2.1 → postgreslite-1.0.0}/postgreslite/__init__.py +1 -1
- postgreslite-1.0.0/postgreslite/handler.py +340 -0
- postgreslite-1.0.0/postgreslite/pool.py +499 -0
- {postgreslite-0.2.1 → postgreslite-1.0.0}/pyproject.toml +6 -3
- postgreslite-1.0.0/tests/test_async_pool.py +100 -0
- postgreslite-1.0.0/tests/test_datetime_sync.py +42 -0
- postgreslite-1.0.0/tests/test_init.py +25 -0
- postgreslite-1.0.0/tests/test_sql_statements.py +31 -0
- postgreslite-1.0.0/tests/test_sync_pool.py +105 -0
- postgreslite-1.0.0/tests/test_table_column.py +27 -0
- postgreslite-0.2.1/PKG-INFO +0 -38
- postgreslite-0.2.1/PostgresLite.egg-info/PKG-INFO +0 -38
- postgreslite-0.2.1/README.md +0 -20
- postgreslite-0.2.1/postgreslite/handler.py +0 -92
- postgreslite-0.2.1/postgreslite/pool.py +0 -281
- postgreslite-0.2.1/tests/test_file.py +0 -9
- {postgreslite-0.2.1 → postgreslite-1.0.0}/LICENSE +0 -0
- {postgreslite-0.2.1 → postgreslite-1.0.0}/PostgresLite.egg-info/dependency_links.txt +0 -0
- {postgreslite-0.2.1 → postgreslite-1.0.0}/PostgresLite.egg-info/requires.txt +0 -0
- {postgreslite-0.2.1 → postgreslite-1.0.0}/PostgresLite.egg-info/top_level.txt +0 -0
- {postgreslite-0.2.1 → postgreslite-1.0.0}/setup.cfg +0 -0
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: PostgresLite
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Python SQLite combined with syntax compared to asyncpg progject.
|
|
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
|
+
Requires-Python: >=3.11.0
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Provides-Extra: dev
|
|
14
|
+
Requires-Dist: pyright>=1.1.401; extra == "dev"
|
|
15
|
+
Requires-Dist: ruff>=0.11.13; extra == "dev"
|
|
16
|
+
Requires-Dist: toml>=0.10.2; extra == "dev"
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# PostgresLite
|
|
20
|
+
Python SQLite library built around asyncpg-style syntax.
|
|
21
|
+
|
|
22
|
+
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:
|
|
23
|
+
- Automatic type conversion for `DATE`, `DATETIME`, `TIMESTAMP`, and `JSON` columns
|
|
24
|
+
- Transaction support via context managers
|
|
25
|
+
- Schema syncing and dumping
|
|
26
|
+
- Both sync and async connections, using the same API
|
|
27
|
+
|
|
28
|
+
## Installing
|
|
29
|
+
> You need **Python >=3.11** to use this library.
|
|
30
|
+
|
|
31
|
+
Install by using `pip install postgreslite` in the terminal.
|
|
32
|
+
|
|
33
|
+
## Quick example
|
|
34
|
+
|
|
35
|
+
**Sync**
|
|
36
|
+
```py
|
|
37
|
+
from postgreslite import PostgresLite
|
|
38
|
+
|
|
39
|
+
pool = PostgresLite("./hello_world.db").connect()
|
|
40
|
+
|
|
41
|
+
pool.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL)")
|
|
42
|
+
pool.execute("INSERT INTO users (name) VALUES (?) ON CONFLICT DO NOTHING", "AlexFlipnote")
|
|
43
|
+
|
|
44
|
+
data = pool.fetch("SELECT * FROM users")
|
|
45
|
+
print(data) # [{'id': 1, 'name': 'AlexFlipnote'}]
|
|
46
|
+
|
|
47
|
+
pool.close()
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
**Async**
|
|
51
|
+
```py
|
|
52
|
+
import asyncio
|
|
53
|
+
from postgreslite import PostgresLite
|
|
54
|
+
|
|
55
|
+
async def main():
|
|
56
|
+
pool = PostgresLite("./hello_world.db").connect_async()
|
|
57
|
+
data = await pool.fetch("SELECT * FROM users")
|
|
58
|
+
await pool.close()
|
|
59
|
+
|
|
60
|
+
asyncio.run(main())
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Both connection types support the same API: `execute`, `fetch`, `fetchrow`, `fetchval`, `executemany`.
|
|
64
|
+
asyncpg-style placeholders (`$1`, `$2`, …) are also accepted and converted automatically.
|
|
65
|
+
|
|
66
|
+
## Type handling
|
|
67
|
+
Columns declared as `DATE`, `DATETIME`, `TIMESTAMP`, or `JSON` are automatically converted on read:
|
|
68
|
+
|
|
69
|
+
| Column type | Python type |
|
|
70
|
+
|-------------|-------------|
|
|
71
|
+
| `DATE` | `datetime.date` |
|
|
72
|
+
| `DATETIME` | `datetime.datetime` |
|
|
73
|
+
| `TIMESTAMP` | `datetime.datetime` (UTC) |
|
|
74
|
+
| `JSON` | `dict` / `list` |
|
|
75
|
+
|
|
76
|
+
## Transactions
|
|
77
|
+
```py
|
|
78
|
+
with pool.transaction():
|
|
79
|
+
pool.execute("UPDATE accounts SET balance = balance - 100 WHERE id = 1")
|
|
80
|
+
pool.execute("UPDATE accounts SET balance = balance + 100 WHERE id = 2")
|
|
81
|
+
```
|
|
82
|
+
Raises on error and rolls back automatically. Async pools use `async with pool.transaction()`.
|
|
83
|
+
|
|
84
|
+
## Schema utilities
|
|
85
|
+
```py
|
|
86
|
+
db = PostgresLite("./hello_world.db")
|
|
87
|
+
|
|
88
|
+
# Dump current schema to stdout, a file, or a folder of per-table files
|
|
89
|
+
db.dump_schema()
|
|
90
|
+
db.dump_schema(output="schema.sql")
|
|
91
|
+
db.dump_schema(output="schema/")
|
|
92
|
+
|
|
93
|
+
# Sync a schema definition (SQL string, .sql file, or folder) to the live database
|
|
94
|
+
result = db.sync_schema("schema/")
|
|
95
|
+
```
|
|
96
|
+
`sync_schema` adds new tables and missing columns non-destructively by default (`safe_mode=True`).
|
|
97
|
+
|
|
98
|
+
## Introspection
|
|
99
|
+
```py
|
|
100
|
+
pool.tables() # ['users', 'posts']
|
|
101
|
+
pool.table_exists("users") # True
|
|
102
|
+
pool.table_columns("users") # [<TableColumn name='id' ...>, ...]
|
|
103
|
+
```
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: PostgresLite
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Python SQLite combined with syntax compared to asyncpg progject.
|
|
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
|
+
Requires-Python: >=3.11.0
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Provides-Extra: dev
|
|
14
|
+
Requires-Dist: pyright>=1.1.401; extra == "dev"
|
|
15
|
+
Requires-Dist: ruff>=0.11.13; extra == "dev"
|
|
16
|
+
Requires-Dist: toml>=0.10.2; extra == "dev"
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# PostgresLite
|
|
20
|
+
Python SQLite library built around asyncpg-style syntax.
|
|
21
|
+
|
|
22
|
+
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:
|
|
23
|
+
- Automatic type conversion for `DATE`, `DATETIME`, `TIMESTAMP`, and `JSON` columns
|
|
24
|
+
- Transaction support via context managers
|
|
25
|
+
- Schema syncing and dumping
|
|
26
|
+
- Both sync and async connections, using the same API
|
|
27
|
+
|
|
28
|
+
## Installing
|
|
29
|
+
> You need **Python >=3.11** to use this library.
|
|
30
|
+
|
|
31
|
+
Install by using `pip install postgreslite` in the terminal.
|
|
32
|
+
|
|
33
|
+
## Quick example
|
|
34
|
+
|
|
35
|
+
**Sync**
|
|
36
|
+
```py
|
|
37
|
+
from postgreslite import PostgresLite
|
|
38
|
+
|
|
39
|
+
pool = PostgresLite("./hello_world.db").connect()
|
|
40
|
+
|
|
41
|
+
pool.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL)")
|
|
42
|
+
pool.execute("INSERT INTO users (name) VALUES (?) ON CONFLICT DO NOTHING", "AlexFlipnote")
|
|
43
|
+
|
|
44
|
+
data = pool.fetch("SELECT * FROM users")
|
|
45
|
+
print(data) # [{'id': 1, 'name': 'AlexFlipnote'}]
|
|
46
|
+
|
|
47
|
+
pool.close()
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
**Async**
|
|
51
|
+
```py
|
|
52
|
+
import asyncio
|
|
53
|
+
from postgreslite import PostgresLite
|
|
54
|
+
|
|
55
|
+
async def main():
|
|
56
|
+
pool = PostgresLite("./hello_world.db").connect_async()
|
|
57
|
+
data = await pool.fetch("SELECT * FROM users")
|
|
58
|
+
await pool.close()
|
|
59
|
+
|
|
60
|
+
asyncio.run(main())
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Both connection types support the same API: `execute`, `fetch`, `fetchrow`, `fetchval`, `executemany`.
|
|
64
|
+
asyncpg-style placeholders (`$1`, `$2`, …) are also accepted and converted automatically.
|
|
65
|
+
|
|
66
|
+
## Type handling
|
|
67
|
+
Columns declared as `DATE`, `DATETIME`, `TIMESTAMP`, or `JSON` are automatically converted on read:
|
|
68
|
+
|
|
69
|
+
| Column type | Python type |
|
|
70
|
+
|-------------|-------------|
|
|
71
|
+
| `DATE` | `datetime.date` |
|
|
72
|
+
| `DATETIME` | `datetime.datetime` |
|
|
73
|
+
| `TIMESTAMP` | `datetime.datetime` (UTC) |
|
|
74
|
+
| `JSON` | `dict` / `list` |
|
|
75
|
+
|
|
76
|
+
## Transactions
|
|
77
|
+
```py
|
|
78
|
+
with pool.transaction():
|
|
79
|
+
pool.execute("UPDATE accounts SET balance = balance - 100 WHERE id = 1")
|
|
80
|
+
pool.execute("UPDATE accounts SET balance = balance + 100 WHERE id = 2")
|
|
81
|
+
```
|
|
82
|
+
Raises on error and rolls back automatically. Async pools use `async with pool.transaction()`.
|
|
83
|
+
|
|
84
|
+
## Schema utilities
|
|
85
|
+
```py
|
|
86
|
+
db = PostgresLite("./hello_world.db")
|
|
87
|
+
|
|
88
|
+
# Dump current schema to stdout, a file, or a folder of per-table files
|
|
89
|
+
db.dump_schema()
|
|
90
|
+
db.dump_schema(output="schema.sql")
|
|
91
|
+
db.dump_schema(output="schema/")
|
|
92
|
+
|
|
93
|
+
# Sync a schema definition (SQL string, .sql file, or folder) to the live database
|
|
94
|
+
result = db.sync_schema("schema/")
|
|
95
|
+
```
|
|
96
|
+
`sync_schema` adds new tables and missing columns non-destructively by default (`safe_mode=True`).
|
|
97
|
+
|
|
98
|
+
## Introspection
|
|
99
|
+
```py
|
|
100
|
+
pool.tables() # ['users', 'posts']
|
|
101
|
+
pool.table_exists("users") # True
|
|
102
|
+
pool.table_columns("users") # [<TableColumn name='id' ...>, ...]
|
|
103
|
+
```
|
|
@@ -9,4 +9,9 @@ PostgresLite.egg-info/top_level.txt
|
|
|
9
9
|
postgreslite/__init__.py
|
|
10
10
|
postgreslite/handler.py
|
|
11
11
|
postgreslite/pool.py
|
|
12
|
-
tests/
|
|
12
|
+
tests/test_async_pool.py
|
|
13
|
+
tests/test_datetime_sync.py
|
|
14
|
+
tests/test_init.py
|
|
15
|
+
tests/test_sql_statements.py
|
|
16
|
+
tests/test_sync_pool.py
|
|
17
|
+
tests/test_table_column.py
|
|
@@ -0,0 +1,85 @@
|
|
|
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
|
+
- Transaction support via context managers
|
|
7
|
+
- Schema syncing and dumping
|
|
8
|
+
- Both sync and async connections, using the same API
|
|
9
|
+
|
|
10
|
+
## Installing
|
|
11
|
+
> You need **Python >=3.11** to use this library.
|
|
12
|
+
|
|
13
|
+
Install by using `pip install postgreslite` in the terminal.
|
|
14
|
+
|
|
15
|
+
## Quick example
|
|
16
|
+
|
|
17
|
+
**Sync**
|
|
18
|
+
```py
|
|
19
|
+
from postgreslite import PostgresLite
|
|
20
|
+
|
|
21
|
+
pool = PostgresLite("./hello_world.db").connect()
|
|
22
|
+
|
|
23
|
+
pool.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL)")
|
|
24
|
+
pool.execute("INSERT INTO users (name) VALUES (?) ON CONFLICT DO NOTHING", "AlexFlipnote")
|
|
25
|
+
|
|
26
|
+
data = pool.fetch("SELECT * FROM users")
|
|
27
|
+
print(data) # [{'id': 1, 'name': 'AlexFlipnote'}]
|
|
28
|
+
|
|
29
|
+
pool.close()
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
**Async**
|
|
33
|
+
```py
|
|
34
|
+
import asyncio
|
|
35
|
+
from postgreslite import PostgresLite
|
|
36
|
+
|
|
37
|
+
async def main():
|
|
38
|
+
pool = PostgresLite("./hello_world.db").connect_async()
|
|
39
|
+
data = await pool.fetch("SELECT * FROM users")
|
|
40
|
+
await pool.close()
|
|
41
|
+
|
|
42
|
+
asyncio.run(main())
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Both connection types support the same API: `execute`, `fetch`, `fetchrow`, `fetchval`, `executemany`.
|
|
46
|
+
asyncpg-style placeholders (`$1`, `$2`, …) are also accepted and converted automatically.
|
|
47
|
+
|
|
48
|
+
## Type handling
|
|
49
|
+
Columns declared as `DATE`, `DATETIME`, `TIMESTAMP`, or `JSON` are automatically converted on read:
|
|
50
|
+
|
|
51
|
+
| Column type | Python type |
|
|
52
|
+
|-------------|-------------|
|
|
53
|
+
| `DATE` | `datetime.date` |
|
|
54
|
+
| `DATETIME` | `datetime.datetime` |
|
|
55
|
+
| `TIMESTAMP` | `datetime.datetime` (UTC) |
|
|
56
|
+
| `JSON` | `dict` / `list` |
|
|
57
|
+
|
|
58
|
+
## Transactions
|
|
59
|
+
```py
|
|
60
|
+
with pool.transaction():
|
|
61
|
+
pool.execute("UPDATE accounts SET balance = balance - 100 WHERE id = 1")
|
|
62
|
+
pool.execute("UPDATE accounts SET balance = balance + 100 WHERE id = 2")
|
|
63
|
+
```
|
|
64
|
+
Raises on error and rolls back automatically. Async pools use `async with pool.transaction()`.
|
|
65
|
+
|
|
66
|
+
## Schema utilities
|
|
67
|
+
```py
|
|
68
|
+
db = PostgresLite("./hello_world.db")
|
|
69
|
+
|
|
70
|
+
# Dump current schema to stdout, a file, or a folder of per-table files
|
|
71
|
+
db.dump_schema()
|
|
72
|
+
db.dump_schema(output="schema.sql")
|
|
73
|
+
db.dump_schema(output="schema/")
|
|
74
|
+
|
|
75
|
+
# Sync a schema definition (SQL string, .sql file, or folder) to the live database
|
|
76
|
+
result = db.sync_schema("schema/")
|
|
77
|
+
```
|
|
78
|
+
`sync_schema` adds new tables and missing columns non-destructively by default (`safe_mode=True`).
|
|
79
|
+
|
|
80
|
+
## Introspection
|
|
81
|
+
```py
|
|
82
|
+
pool.tables() # ['users', 'posts']
|
|
83
|
+
pool.table_exists("users") # True
|
|
84
|
+
pool.table_columns("users") # [<TableColumn name='id' ...>, ...]
|
|
85
|
+
```
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import re
|
|
4
|
+
import sqlite3
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
|
|
7
|
+
from .pool import PoolConnection, AsyncPoolConnection
|
|
8
|
+
from datetime import datetime, date, UTC
|
|
9
|
+
|
|
10
|
+
__all__ = (
|
|
11
|
+
"PostgresLite",
|
|
12
|
+
"SchemaSyncResult",
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _normalize_sql(sql: str) -> str:
|
|
17
|
+
lines = [line.strip() for line in sql.splitlines() if line.strip()]
|
|
18
|
+
if len(lines) <= 1:
|
|
19
|
+
return lines[0] if lines else sql
|
|
20
|
+
result = lines[0] + "\n" + "\n".join(f" {line}" for line in lines[1:-1]) + "\n" + lines[-1]
|
|
21
|
+
return re.sub(
|
|
22
|
+
r"CREATE\s+TABLE\s+(?!IF\s+NOT\s+EXISTS\s+)(\w)",
|
|
23
|
+
r"CREATE TABLE IF NOT EXISTS \1",
|
|
24
|
+
result, count=1, flags=re.IGNORECASE,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
_re_create_table = re.compile(
|
|
29
|
+
r"CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(\w+)",
|
|
30
|
+
re.IGNORECASE,
|
|
31
|
+
)
|
|
32
|
+
_re_create_index = re.compile(
|
|
33
|
+
r"CREATE\s+(UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?(\w+)",
|
|
34
|
+
re.IGNORECASE,
|
|
35
|
+
)
|
|
36
|
+
_re_strip_comments = re.compile(r"--[^\n]*|/\*.*?\*/", re.DOTALL)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class SchemaSyncResult:
|
|
41
|
+
tables_created: list[str] = field(default_factory=list)
|
|
42
|
+
columns_added: dict[str, list[str]] = field(default_factory=dict)
|
|
43
|
+
columns_removed: dict[str, list[str]] = field(default_factory=dict)
|
|
44
|
+
skipped: list[str] = field(default_factory=list)
|
|
45
|
+
warnings: list[str] = field(default_factory=list)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def dict_factory(cursor: sqlite3.Cursor, row: sqlite3.Row) -> dict:
|
|
49
|
+
d = {}
|
|
50
|
+
for index, col in enumerate(cursor.description):
|
|
51
|
+
d[col[0]] = row[index]
|
|
52
|
+
return d
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class PostgresLite:
|
|
56
|
+
def __init__(self, filename: str = "storage.db"):
|
|
57
|
+
self._prepare_settings()
|
|
58
|
+
self._filename = filename
|
|
59
|
+
|
|
60
|
+
if filename != ":memory:" and not filename.endswith(".db"):
|
|
61
|
+
raise ValueError("Database filename must end with '.db'")
|
|
62
|
+
|
|
63
|
+
def connect(self) -> PoolConnection:
|
|
64
|
+
""" Makes a connection to the database and returns the pool (sync). """
|
|
65
|
+
conn = sqlite3.connect(
|
|
66
|
+
self._filename,
|
|
67
|
+
isolation_level=None,
|
|
68
|
+
detect_types=sqlite3.PARSE_DECLTYPES
|
|
69
|
+
)
|
|
70
|
+
conn.row_factory = dict_factory
|
|
71
|
+
conn.execute("PRAGMA foreign_keys = ON")
|
|
72
|
+
return PoolConnection(conn.cursor(), conn)
|
|
73
|
+
|
|
74
|
+
def connect_async(self) -> AsyncPoolConnection:
|
|
75
|
+
""" Makes a connection to the database and returns the pool (async). """
|
|
76
|
+
conn = sqlite3.connect(
|
|
77
|
+
self._filename,
|
|
78
|
+
isolation_level=None,
|
|
79
|
+
check_same_thread=False,
|
|
80
|
+
detect_types=sqlite3.PARSE_DECLTYPES
|
|
81
|
+
)
|
|
82
|
+
conn.row_factory = dict_factory
|
|
83
|
+
conn.execute("PRAGMA journal_mode=WAL")
|
|
84
|
+
conn.execute("PRAGMA foreign_keys = ON")
|
|
85
|
+
return AsyncPoolConnection(conn.cursor(), conn)
|
|
86
|
+
|
|
87
|
+
def dump_schema(self, include_indexes: bool = False, output: 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
|
+
conn = sqlite3.connect(self._filename)
|
|
105
|
+
try:
|
|
106
|
+
cur = conn.cursor()
|
|
107
|
+
cur.execute(
|
|
108
|
+
"SELECT name, sql FROM sqlite_master "
|
|
109
|
+
"WHERE type='table' AND name NOT LIKE 'sqlite_%' "
|
|
110
|
+
"ORDER BY name"
|
|
111
|
+
)
|
|
112
|
+
tables = [(row[0], _normalize_sql(row[1])) for row in cur.fetchall() if row[1]]
|
|
113
|
+
|
|
114
|
+
indexes_by_table: dict[str, list[str]] = {}
|
|
115
|
+
if include_indexes:
|
|
116
|
+
cur.execute(
|
|
117
|
+
"SELECT tbl_name, sql FROM sqlite_master "
|
|
118
|
+
"WHERE type='index' AND name NOT LIKE 'sqlite_%' "
|
|
119
|
+
"ORDER BY name"
|
|
120
|
+
)
|
|
121
|
+
for tbl, sql in cur.fetchall():
|
|
122
|
+
if sql:
|
|
123
|
+
indexes_by_table.setdefault(tbl, []).append(_normalize_sql(sql))
|
|
124
|
+
finally:
|
|
125
|
+
conn.close()
|
|
126
|
+
|
|
127
|
+
if output is None or output.endswith(".sql"):
|
|
128
|
+
parts = [sql for _, sql in tables]
|
|
129
|
+
for idx_list in indexes_by_table.values():
|
|
130
|
+
parts += idx_list
|
|
131
|
+
full = ";\n\n".join(parts) + ";" if parts else ""
|
|
132
|
+
if output is not None:
|
|
133
|
+
os.makedirs(os.path.dirname(os.path.abspath(output)), exist_ok=True)
|
|
134
|
+
with open(output, "w", encoding="utf-8") as f:
|
|
135
|
+
f.write(full)
|
|
136
|
+
return full
|
|
137
|
+
|
|
138
|
+
os.makedirs(output, exist_ok=True)
|
|
139
|
+
all_parts = []
|
|
140
|
+
for tbl_name, tbl_sql in tables:
|
|
141
|
+
file_parts = [tbl_sql]
|
|
142
|
+
for idx_sql in indexes_by_table.get(tbl_name, []):
|
|
143
|
+
file_parts.append(idx_sql)
|
|
144
|
+
content = ";\n\n".join(file_parts) + ";"
|
|
145
|
+
with open(os.path.join(output, f"{tbl_name}.sql"), "w", encoding="utf-8") as f:
|
|
146
|
+
f.write(content)
|
|
147
|
+
all_parts.extend(file_parts)
|
|
148
|
+
return ";\n\n".join(all_parts) + ";" if all_parts else ""
|
|
149
|
+
|
|
150
|
+
def sync_schema(self, schema: str = "schema", safe_mode: bool = True) -> SchemaSyncResult:
|
|
151
|
+
"""
|
|
152
|
+
Sync a schema definition to the database.
|
|
153
|
+
|
|
154
|
+
Parameters
|
|
155
|
+
----------
|
|
156
|
+
schema:
|
|
157
|
+
An inline SQL string, a path to a .sql file, or a folder of .sql files
|
|
158
|
+
(default folder name is "schema"). Only CREATE TABLE and CREATE INDEX statements
|
|
159
|
+
are permitted; anything else raises ValueError.
|
|
160
|
+
safe_mode:
|
|
161
|
+
When True (default), extra columns are reported in result.warnings but not dropped.
|
|
162
|
+
When False, extra columns are removed and reported in result.columns_removed.
|
|
163
|
+
Note: columns with PRIMARY KEY or UNIQUE constraints cannot be added via ALTER TABLE.
|
|
164
|
+
|
|
165
|
+
Returns
|
|
166
|
+
-------
|
|
167
|
+
A SchemaSyncResult with tables_created, columns_added, columns_removed, skipped, and warnings.
|
|
168
|
+
"""
|
|
169
|
+
sql = self._load_schema_sql(schema)
|
|
170
|
+
statements = self._parse_statements(sql)
|
|
171
|
+
result = SchemaSyncResult()
|
|
172
|
+
|
|
173
|
+
conn = sqlite3.connect(self._filename)
|
|
174
|
+
try:
|
|
175
|
+
cur = conn.cursor()
|
|
176
|
+
cur.execute(
|
|
177
|
+
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"
|
|
178
|
+
)
|
|
179
|
+
existing_tables = {row[0] for row in cur.fetchall()}
|
|
180
|
+
|
|
181
|
+
for kind, name, stmt in statements:
|
|
182
|
+
if kind == "table":
|
|
183
|
+
safe_stmt = re.sub(
|
|
184
|
+
r"CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?",
|
|
185
|
+
"CREATE TABLE IF NOT EXISTS ",
|
|
186
|
+
stmt, count=1, flags=re.IGNORECASE,
|
|
187
|
+
)
|
|
188
|
+
cur.execute(safe_stmt)
|
|
189
|
+
conn.commit()
|
|
190
|
+
|
|
191
|
+
if name in existing_tables:
|
|
192
|
+
new_cols = self._get_desired_columns(name, stmt)
|
|
193
|
+
cur.execute(f"PRAGMA table_info({name})")
|
|
194
|
+
pragma_rows = cur.fetchall()
|
|
195
|
+
existing_cols = {row[1] for row in pragma_rows}
|
|
196
|
+
pk_cols = {row[1] for row in pragma_rows if row[5]}
|
|
197
|
+
|
|
198
|
+
added = []
|
|
199
|
+
for col_name, col_def in new_cols.items():
|
|
200
|
+
if col_name not in existing_cols:
|
|
201
|
+
try:
|
|
202
|
+
cur.execute(f"ALTER TABLE {name} ADD COLUMN {col_def}")
|
|
203
|
+
conn.commit()
|
|
204
|
+
added.append(col_name)
|
|
205
|
+
except sqlite3.OperationalError:
|
|
206
|
+
pass # PRIMARY KEY / UNIQUE columns can't be added
|
|
207
|
+
|
|
208
|
+
removable = [c for c in existing_cols if c not in new_cols and c not in pk_cols]
|
|
209
|
+
if removable:
|
|
210
|
+
if safe_mode:
|
|
211
|
+
for col in removable:
|
|
212
|
+
result.warnings.append(
|
|
213
|
+
f"Column '{col}' on table '{name}' is not in the schema "
|
|
214
|
+
f"and would be dropped. Re-run with safe_mode=False to apply."
|
|
215
|
+
)
|
|
216
|
+
else:
|
|
217
|
+
removed = []
|
|
218
|
+
for col in removable:
|
|
219
|
+
cur.execute(f"ALTER TABLE {name} DROP COLUMN {col}")
|
|
220
|
+
conn.commit()
|
|
221
|
+
removed.append(col)
|
|
222
|
+
if removed:
|
|
223
|
+
result.columns_removed[name] = removed
|
|
224
|
+
|
|
225
|
+
if added:
|
|
226
|
+
result.columns_added[name] = added
|
|
227
|
+
elif not removable:
|
|
228
|
+
result.skipped.append(name)
|
|
229
|
+
else:
|
|
230
|
+
result.tables_created.append(name)
|
|
231
|
+
|
|
232
|
+
elif kind == "index":
|
|
233
|
+
safe_stmt = re.sub(
|
|
234
|
+
r"CREATE\s+(UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?",
|
|
235
|
+
lambda m: f"CREATE {m.group(1) or ''}INDEX IF NOT EXISTS ",
|
|
236
|
+
stmt, count=1, flags=re.IGNORECASE,
|
|
237
|
+
)
|
|
238
|
+
cur.execute(safe_stmt)
|
|
239
|
+
conn.commit()
|
|
240
|
+
finally:
|
|
241
|
+
conn.close()
|
|
242
|
+
|
|
243
|
+
return result
|
|
244
|
+
|
|
245
|
+
def _load_schema_sql(self, schema: str) -> str:
|
|
246
|
+
if os.path.isdir(schema):
|
|
247
|
+
parts = []
|
|
248
|
+
for fname in sorted(os.listdir(schema)):
|
|
249
|
+
if fname.endswith(".sql"):
|
|
250
|
+
with open(os.path.join(schema, fname), encoding="utf-8") as f:
|
|
251
|
+
parts.append(f.read())
|
|
252
|
+
return "\n".join(parts)
|
|
253
|
+
if schema.endswith(".sql") and os.path.isfile(schema):
|
|
254
|
+
with open(schema, encoding="utf-8") as f:
|
|
255
|
+
return f.read()
|
|
256
|
+
return schema
|
|
257
|
+
|
|
258
|
+
def _parse_statements(self, sql: str) -> list[tuple[str, str, str]]:
|
|
259
|
+
sql = _re_strip_comments.sub("", sql)
|
|
260
|
+
results = []
|
|
261
|
+
for chunk in sql.split(";"):
|
|
262
|
+
chunk = chunk.strip()
|
|
263
|
+
if not chunk:
|
|
264
|
+
continue
|
|
265
|
+
first = chunk.split()[0].upper() if chunk.split() else ""
|
|
266
|
+
second = chunk.split()[1].upper() if len(chunk.split()) > 1 else ""
|
|
267
|
+
|
|
268
|
+
if first == "CREATE" and second == "TABLE":
|
|
269
|
+
m = _re_create_table.search(chunk)
|
|
270
|
+
if m:
|
|
271
|
+
results.append(("table", m.group(1), chunk))
|
|
272
|
+
elif first == "CREATE" and second in ("INDEX", "UNIQUE"):
|
|
273
|
+
m = _re_create_index.search(chunk)
|
|
274
|
+
if m:
|
|
275
|
+
results.append(("index", m.group(2), chunk))
|
|
276
|
+
else:
|
|
277
|
+
raise ValueError(
|
|
278
|
+
f"sync_schema only permits CREATE TABLE and CREATE INDEX statements; got: {first} {second}".strip()
|
|
279
|
+
)
|
|
280
|
+
return results
|
|
281
|
+
|
|
282
|
+
def _get_desired_columns(self, table_name: str, create_stmt: str) -> dict[str, str]:
|
|
283
|
+
conn = sqlite3.connect(":memory:")
|
|
284
|
+
try:
|
|
285
|
+
safe_stmt = re.sub(
|
|
286
|
+
r"CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?",
|
|
287
|
+
"CREATE TABLE IF NOT EXISTS ",
|
|
288
|
+
create_stmt, count=1, flags=re.IGNORECASE,
|
|
289
|
+
)
|
|
290
|
+
conn.execute(safe_stmt)
|
|
291
|
+
cur = conn.execute(f"PRAGMA table_info({table_name})")
|
|
292
|
+
cols = {}
|
|
293
|
+
for row in cur.fetchall():
|
|
294
|
+
col_name = row[1]
|
|
295
|
+
col_type = row[2] or "TEXT"
|
|
296
|
+
notnull = row[3]
|
|
297
|
+
default = row[4]
|
|
298
|
+
pk = row[5]
|
|
299
|
+
if pk:
|
|
300
|
+
continue # cannot ALTER TABLE ADD COLUMN with PRIMARY KEY
|
|
301
|
+
defn = f"{col_name} {col_type}"
|
|
302
|
+
if notnull:
|
|
303
|
+
defn += " NOT NULL"
|
|
304
|
+
if default is not None:
|
|
305
|
+
defn += f" DEFAULT {default}"
|
|
306
|
+
cols[col_name] = defn
|
|
307
|
+
finally:
|
|
308
|
+
conn.close()
|
|
309
|
+
return cols
|
|
310
|
+
|
|
311
|
+
def _prepare_settings(self) -> None:
|
|
312
|
+
""" Prepare SQLite settings for better experience. """
|
|
313
|
+
|
|
314
|
+
def adapt_date_iso(val: date) -> str:
|
|
315
|
+
return val.isoformat()
|
|
316
|
+
|
|
317
|
+
def adapt_datetime_iso(val: datetime) -> str:
|
|
318
|
+
return val.isoformat()
|
|
319
|
+
|
|
320
|
+
sqlite3.register_adapter(date, adapt_date_iso)
|
|
321
|
+
sqlite3.register_adapter(datetime, adapt_datetime_iso)
|
|
322
|
+
sqlite3.register_adapter(dict, json.dumps)
|
|
323
|
+
sqlite3.register_adapter(list, json.dumps)
|
|
324
|
+
|
|
325
|
+
def convert_date(val: bytes) -> date:
|
|
326
|
+
return date.fromisoformat(val.decode())
|
|
327
|
+
|
|
328
|
+
def convert_datetime(val: bytes) -> datetime:
|
|
329
|
+
return datetime.fromisoformat(val.decode())
|
|
330
|
+
|
|
331
|
+
def convert_timestamp(val: bytes) -> datetime:
|
|
332
|
+
return datetime.fromisoformat(val.decode()).replace(tzinfo=UTC)
|
|
333
|
+
|
|
334
|
+
def convert_json(val: bytes) -> object:
|
|
335
|
+
return json.loads(val.decode())
|
|
336
|
+
|
|
337
|
+
sqlite3.register_converter("date", convert_date)
|
|
338
|
+
sqlite3.register_converter("datetime", convert_datetime)
|
|
339
|
+
sqlite3.register_converter("timestamp", convert_timestamp)
|
|
340
|
+
sqlite3.register_converter("json", convert_json)
|