SQLitey 0.1.0__tar.gz → 0.1.1__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.
- sqlitey-0.1.1/PKG-INFO +161 -0
- sqlitey-0.1.1/README.md +131 -0
- {sqlitey-0.1.0 → sqlitey-0.1.1}/pyproject.toml +1 -1
- sqlitey-0.1.1/sqlitey/__init__.py +330 -0
- {sqlitey-0.1.0 → sqlitey-0.1.1}/tests/test_sqlitey.py +53 -3
- sqlitey-0.1.0/PKG-INFO +0 -87
- sqlitey-0.1.0/README.md +0 -57
- sqlitey-0.1.0/sqlitey/__init__.py +0 -154
- {sqlitey-0.1.0 → sqlitey-0.1.1}/.github/workflows/ci.yaml +0 -0
- {sqlitey-0.1.0 → sqlitey-0.1.1}/.gitignore +0 -0
- {sqlitey-0.1.0 → sqlitey-0.1.1}/.python-version +0 -0
- {sqlitey-0.1.0 → sqlitey-0.1.1}/LICENSE +0 -0
- {sqlitey-0.1.0 → sqlitey-0.1.1}/Makefile +0 -0
- {sqlitey-0.1.0 → sqlitey-0.1.1}/tests/__init__.py +0 -0
- {sqlitey-0.1.0 → sqlitey-0.1.1}/tests/sql/test.sql +0 -0
- {sqlitey-0.1.0 → sqlitey-0.1.1}/uv.lock +0 -0
sqlitey-0.1.1/PKG-INFO
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: SQLitey
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Useful wrapper around SQLite
|
|
5
|
+
License: The MIT License (MIT)
|
|
6
|
+
|
|
7
|
+
Copyright (c) 2025 Matthieu Petiteau
|
|
8
|
+
|
|
9
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
10
|
+
a copy of this software and associated documentation files (the
|
|
11
|
+
"Software"), to deal in the Software without restriction, including
|
|
12
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
|
13
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
|
14
|
+
permit persons to whom the Software is furnished to do so, subject to
|
|
15
|
+
the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be
|
|
18
|
+
included in all copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
21
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
22
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
23
|
+
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
|
24
|
+
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
|
25
|
+
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
|
26
|
+
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
27
|
+
License-File: LICENSE
|
|
28
|
+
Requires-Python: >=3.11
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# SQLitey
|
|
32
|
+
|
|
33
|
+
SQLitey is a lightweight and flexible wrapper around SQLite, designed to streamline database access using configuration files, SQL templates, and custom row factories.
|
|
34
|
+
|
|
35
|
+
Key Features:
|
|
36
|
+
- Configuration-driven setup for database paths and SQL templates
|
|
37
|
+
- Support for SQL template files to keep queries organized
|
|
38
|
+
- Customizable row factories (e.g., return rows as namedtuples)
|
|
39
|
+
- Support for both templated and raw SQL queries
|
|
40
|
+
- Optional config usage for quick, one-off database access
|
|
41
|
+
|
|
42
|
+
## Installation
|
|
43
|
+
|
|
44
|
+
```
|
|
45
|
+
pip install sqlitey
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Quick Start
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from sqlitey import Db, Sql
|
|
52
|
+
|
|
53
|
+
with Db("mydb.sqlite") as db:
|
|
54
|
+
db.commit(Sql.raw("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)"))
|
|
55
|
+
db.commit(Sql.raw("INSERT INTO users (name) VALUES (?)"), ("Alice",))
|
|
56
|
+
user = db.fetchone(Sql.raw("SELECT * FROM users WHERE id = ?"), (1,))
|
|
57
|
+
print(user) # (1, 'Alice')
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Usage
|
|
61
|
+
|
|
62
|
+
### Row Factories
|
|
63
|
+
|
|
64
|
+
Return rows as dictionaries or namedtuples instead of tuples:
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from sqlitey import Db, Sql, dict_factory, namedtuple_factory
|
|
68
|
+
|
|
69
|
+
with Db("mydb.sqlite", row_factory=dict_factory) as db:
|
|
70
|
+
user = db.fetchone(Sql.raw("SELECT * FROM users WHERE id = ?"), (1,))
|
|
71
|
+
print(user["name"]) # 'Alice'
|
|
72
|
+
|
|
73
|
+
with Db("mydb.sqlite", row_factory=namedtuple_factory) as db:
|
|
74
|
+
user = db.fetchone(Sql.raw("SELECT * FROM users WHERE id = ?"), (1,))
|
|
75
|
+
print(user.name) # 'Alice'
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### SQL Templates
|
|
79
|
+
|
|
80
|
+
Keep SQL queries in separate files for better organization:
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
from pathlib import Path
|
|
84
|
+
from sqlitey import Db, DbPathConfig, Sql
|
|
85
|
+
|
|
86
|
+
config = DbPathConfig(
|
|
87
|
+
database=Path("mydb.sqlite"),
|
|
88
|
+
sql_templates_dir=Path("sql/"),
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
with Db.from_config(config) as db:
|
|
92
|
+
# Loads query from sql/get_user_by_id.sql
|
|
93
|
+
user = db.fetchone(Sql.template("get_user_by_id.sql"), (1,))
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Or specify the template path directly:
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
with Db("mydb.sqlite") as db:
|
|
100
|
+
sql = Sql.template("get_user_by_id.sql", path=Path("sql/"))
|
|
101
|
+
user = db.fetchone(sql, (1,))
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### Autocommit Mode
|
|
105
|
+
|
|
106
|
+
Disable transaction management for auto-committing each statement:
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
with Db("mydb.sqlite", autocommit=True) as db:
|
|
110
|
+
db.execute(Sql.raw("UPDATE users SET name = ? WHERE id = ?"), ("Bob", 1))
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### Batch Operations
|
|
114
|
+
|
|
115
|
+
Execute multiple parameter sets or run SQL scripts:
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
with Db("mydb.sqlite", autocommit=True) as db:
|
|
119
|
+
# Execute same query with multiple parameter sets
|
|
120
|
+
users = [("Alice",), ("Bob",), ("Charlie",)]
|
|
121
|
+
db.executemany(Sql.raw("INSERT INTO users (name) VALUES (?)"), users)
|
|
122
|
+
|
|
123
|
+
# Execute multiple statements as a script
|
|
124
|
+
db.executescript(Sql.raw("""
|
|
125
|
+
DELETE FROM users WHERE id = 1;
|
|
126
|
+
UPDATE users SET name = 'Robert' WHERE name = 'Bob';
|
|
127
|
+
"""))
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## API Reference
|
|
131
|
+
|
|
132
|
+
### Sql
|
|
133
|
+
|
|
134
|
+
| Method | Description |
|
|
135
|
+
|--------|-------------|
|
|
136
|
+
| `Sql.raw(query)` | Create a Sql instance from an inline query string |
|
|
137
|
+
| `Sql.template(filename, path=None)` | Create a Sql instance from a template file |
|
|
138
|
+
|
|
139
|
+
### Db
|
|
140
|
+
|
|
141
|
+
| Method | Description |
|
|
142
|
+
|--------|-------------|
|
|
143
|
+
| `Db(path, row_factory=None, sql_templates_dir=None, autocommit=False)` | Create a database connection |
|
|
144
|
+
| `Db.from_config(config, **kwargs)` | Create from a `DbPathConfig` |
|
|
145
|
+
| `execute(sql, *args)` | Execute a query and return the cursor |
|
|
146
|
+
| `executemany(sql, *args)` | Execute a query against multiple parameter sets |
|
|
147
|
+
| `executescript(sql)` | Execute multiple statements as a script |
|
|
148
|
+
| `fetchone(sql, *args)` | Execute and return the first row |
|
|
149
|
+
| `fetchall(sql, *args)` | Execute and return all rows |
|
|
150
|
+
| `commit(sql, *args)` | Execute and commit the transaction |
|
|
151
|
+
|
|
152
|
+
### Row Factories
|
|
153
|
+
|
|
154
|
+
| Factory | Description |
|
|
155
|
+
|---------|-------------|
|
|
156
|
+
| `dict_factory` | Return rows as dictionaries |
|
|
157
|
+
| `namedtuple_factory` | Return rows as namedtuples |
|
|
158
|
+
|
|
159
|
+
## More Examples
|
|
160
|
+
|
|
161
|
+
See the [test suite](https://github.com/smallwat3r/sqlitey/blob/main/tests/test_sqlitey.py) for more examples.
|
sqlitey-0.1.1/README.md
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# SQLitey
|
|
2
|
+
|
|
3
|
+
SQLitey is a lightweight and flexible wrapper around SQLite, designed to streamline database access using configuration files, SQL templates, and custom row factories.
|
|
4
|
+
|
|
5
|
+
Key Features:
|
|
6
|
+
- Configuration-driven setup for database paths and SQL templates
|
|
7
|
+
- Support for SQL template files to keep queries organized
|
|
8
|
+
- Customizable row factories (e.g., return rows as namedtuples)
|
|
9
|
+
- Support for both templated and raw SQL queries
|
|
10
|
+
- Optional config usage for quick, one-off database access
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
pip install sqlitey
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Quick Start
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
from sqlitey import Db, Sql
|
|
22
|
+
|
|
23
|
+
with Db("mydb.sqlite") as db:
|
|
24
|
+
db.commit(Sql.raw("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)"))
|
|
25
|
+
db.commit(Sql.raw("INSERT INTO users (name) VALUES (?)"), ("Alice",))
|
|
26
|
+
user = db.fetchone(Sql.raw("SELECT * FROM users WHERE id = ?"), (1,))
|
|
27
|
+
print(user) # (1, 'Alice')
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Usage
|
|
31
|
+
|
|
32
|
+
### Row Factories
|
|
33
|
+
|
|
34
|
+
Return rows as dictionaries or namedtuples instead of tuples:
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from sqlitey import Db, Sql, dict_factory, namedtuple_factory
|
|
38
|
+
|
|
39
|
+
with Db("mydb.sqlite", row_factory=dict_factory) as db:
|
|
40
|
+
user = db.fetchone(Sql.raw("SELECT * FROM users WHERE id = ?"), (1,))
|
|
41
|
+
print(user["name"]) # 'Alice'
|
|
42
|
+
|
|
43
|
+
with Db("mydb.sqlite", row_factory=namedtuple_factory) as db:
|
|
44
|
+
user = db.fetchone(Sql.raw("SELECT * FROM users WHERE id = ?"), (1,))
|
|
45
|
+
print(user.name) # 'Alice'
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### SQL Templates
|
|
49
|
+
|
|
50
|
+
Keep SQL queries in separate files for better organization:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from pathlib import Path
|
|
54
|
+
from sqlitey import Db, DbPathConfig, Sql
|
|
55
|
+
|
|
56
|
+
config = DbPathConfig(
|
|
57
|
+
database=Path("mydb.sqlite"),
|
|
58
|
+
sql_templates_dir=Path("sql/"),
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
with Db.from_config(config) as db:
|
|
62
|
+
# Loads query from sql/get_user_by_id.sql
|
|
63
|
+
user = db.fetchone(Sql.template("get_user_by_id.sql"), (1,))
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Or specify the template path directly:
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
with Db("mydb.sqlite") as db:
|
|
70
|
+
sql = Sql.template("get_user_by_id.sql", path=Path("sql/"))
|
|
71
|
+
user = db.fetchone(sql, (1,))
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### Autocommit Mode
|
|
75
|
+
|
|
76
|
+
Disable transaction management for auto-committing each statement:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
with Db("mydb.sqlite", autocommit=True) as db:
|
|
80
|
+
db.execute(Sql.raw("UPDATE users SET name = ? WHERE id = ?"), ("Bob", 1))
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Batch Operations
|
|
84
|
+
|
|
85
|
+
Execute multiple parameter sets or run SQL scripts:
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
with Db("mydb.sqlite", autocommit=True) as db:
|
|
89
|
+
# Execute same query with multiple parameter sets
|
|
90
|
+
users = [("Alice",), ("Bob",), ("Charlie",)]
|
|
91
|
+
db.executemany(Sql.raw("INSERT INTO users (name) VALUES (?)"), users)
|
|
92
|
+
|
|
93
|
+
# Execute multiple statements as a script
|
|
94
|
+
db.executescript(Sql.raw("""
|
|
95
|
+
DELETE FROM users WHERE id = 1;
|
|
96
|
+
UPDATE users SET name = 'Robert' WHERE name = 'Bob';
|
|
97
|
+
"""))
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## API Reference
|
|
101
|
+
|
|
102
|
+
### Sql
|
|
103
|
+
|
|
104
|
+
| Method | Description |
|
|
105
|
+
|--------|-------------|
|
|
106
|
+
| `Sql.raw(query)` | Create a Sql instance from an inline query string |
|
|
107
|
+
| `Sql.template(filename, path=None)` | Create a Sql instance from a template file |
|
|
108
|
+
|
|
109
|
+
### Db
|
|
110
|
+
|
|
111
|
+
| Method | Description |
|
|
112
|
+
|--------|-------------|
|
|
113
|
+
| `Db(path, row_factory=None, sql_templates_dir=None, autocommit=False)` | Create a database connection |
|
|
114
|
+
| `Db.from_config(config, **kwargs)` | Create from a `DbPathConfig` |
|
|
115
|
+
| `execute(sql, *args)` | Execute a query and return the cursor |
|
|
116
|
+
| `executemany(sql, *args)` | Execute a query against multiple parameter sets |
|
|
117
|
+
| `executescript(sql)` | Execute multiple statements as a script |
|
|
118
|
+
| `fetchone(sql, *args)` | Execute and return the first row |
|
|
119
|
+
| `fetchall(sql, *args)` | Execute and return all rows |
|
|
120
|
+
| `commit(sql, *args)` | Execute and commit the transaction |
|
|
121
|
+
|
|
122
|
+
### Row Factories
|
|
123
|
+
|
|
124
|
+
| Factory | Description |
|
|
125
|
+
|---------|-------------|
|
|
126
|
+
| `dict_factory` | Return rows as dictionaries |
|
|
127
|
+
| `namedtuple_factory` | Return rows as namedtuples |
|
|
128
|
+
|
|
129
|
+
## More Examples
|
|
130
|
+
|
|
131
|
+
See the [test suite](https://github.com/smallwat3r/sqlitey/blob/main/tests/test_sqlitey.py) for more examples.
|
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
"""Sqlitey - A lightweight SQLite wrapper with SQL injection protection.
|
|
2
|
+
|
|
3
|
+
This module provides a safe interface for SQLite database operations by
|
|
4
|
+
enforcing the use of the Sql class for all queries, preventing direct
|
|
5
|
+
string-based SQL execution.
|
|
6
|
+
|
|
7
|
+
Example:
|
|
8
|
+
>>> from sqlitey import Db, Sql
|
|
9
|
+
>>> with Db("mydb.sqlite") as db:
|
|
10
|
+
... users = db.fetchall(Sql.raw("SELECT * FROM users"))
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import sqlite3
|
|
14
|
+
from collections import namedtuple
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from functools import lru_cache, wraps
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any, Callable, Self, TypeAlias
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"Db",
|
|
22
|
+
"DbPathConfig",
|
|
23
|
+
"Sql",
|
|
24
|
+
"dict_factory",
|
|
25
|
+
"namedtuple_factory",
|
|
26
|
+
"RowFactory",
|
|
27
|
+
"SqlRow",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class DbPathConfig:
|
|
33
|
+
"""Configuration for database and SQL template paths.
|
|
34
|
+
|
|
35
|
+
Attributes:
|
|
36
|
+
database: Path to the SQLite database file.
|
|
37
|
+
sql_templates_dir: Optional directory containing SQL template files.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
database: Path
|
|
41
|
+
sql_templates_dir: Path | None = None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@lru_cache(maxsize=128)
|
|
45
|
+
def _read_sql_template(filename: str, template_path: Path) -> str:
|
|
46
|
+
"""Read and cache SQL template files.
|
|
47
|
+
|
|
48
|
+
Raises:
|
|
49
|
+
FileNotFoundError: If the template file does not exist.
|
|
50
|
+
ValueError: If the filename attempts path traversal.
|
|
51
|
+
"""
|
|
52
|
+
# Validate filename to prevent path traversal
|
|
53
|
+
if ".." in filename or filename.startswith("/"):
|
|
54
|
+
raise ValueError(f"Invalid template filename: {filename}")
|
|
55
|
+
|
|
56
|
+
file_path = template_path / filename
|
|
57
|
+
# Ensure resolved path is within template directory
|
|
58
|
+
try:
|
|
59
|
+
file_path.resolve().relative_to(template_path.resolve())
|
|
60
|
+
except ValueError:
|
|
61
|
+
raise ValueError(f"Template path traversal detected: {filename}") from None
|
|
62
|
+
|
|
63
|
+
try:
|
|
64
|
+
return file_path.read_text().strip()
|
|
65
|
+
except FileNotFoundError:
|
|
66
|
+
raise FileNotFoundError(
|
|
67
|
+
f"SQL template not found: {filename} in {template_path}"
|
|
68
|
+
) from None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class Sql:
|
|
72
|
+
"""Represents a SQL query, either inline or from a template file.
|
|
73
|
+
|
|
74
|
+
Use the class methods `raw()` or `template()` to create instances.
|
|
75
|
+
Direct instantiation is discouraged.
|
|
76
|
+
|
|
77
|
+
Example:
|
|
78
|
+
>>> sql = Sql.raw("SELECT * FROM users WHERE id = ?")
|
|
79
|
+
>>> sql = Sql.template("get_users.sql")
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
def __init__(self, query_loader: Callable, **kwargs) -> None:
|
|
83
|
+
self._query_loader = query_loader
|
|
84
|
+
self._is_templated = False
|
|
85
|
+
self._store = kwargs
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def has_template_path(self) -> bool:
|
|
89
|
+
"""Return True if this is a template with a configured path."""
|
|
90
|
+
return bool(self._is_templated and self._store.get("template_path"))
|
|
91
|
+
|
|
92
|
+
def set_template_path(self, template_path: Path) -> None:
|
|
93
|
+
"""Set the template directory path for deferred template resolution."""
|
|
94
|
+
if self._is_templated:
|
|
95
|
+
self._store["template_path"] = template_path
|
|
96
|
+
|
|
97
|
+
def load_query(self) -> str:
|
|
98
|
+
"""Load and return the SQL query string.
|
|
99
|
+
|
|
100
|
+
Raises:
|
|
101
|
+
ValueError: If this is a template without a configured path.
|
|
102
|
+
"""
|
|
103
|
+
if self._is_templated and not self.has_template_path:
|
|
104
|
+
raise ValueError("No template path configured")
|
|
105
|
+
return self._query_loader(**self._store)
|
|
106
|
+
|
|
107
|
+
@classmethod
|
|
108
|
+
def raw(cls, query: str) -> Self:
|
|
109
|
+
"""Create a Sql instance from an inline query string.
|
|
110
|
+
|
|
111
|
+
Args:
|
|
112
|
+
query: The SQL query string.
|
|
113
|
+
|
|
114
|
+
Returns:
|
|
115
|
+
A Sql instance wrapping the query.
|
|
116
|
+
"""
|
|
117
|
+
return cls(lambda: query)
|
|
118
|
+
|
|
119
|
+
@classmethod
|
|
120
|
+
def template(cls, filename: str, *, path: Path | None = None) -> Self:
|
|
121
|
+
"""Create a Sql instance from a template file.
|
|
122
|
+
|
|
123
|
+
The template path can be provided directly or deferred to be set
|
|
124
|
+
later via the Db configuration.
|
|
125
|
+
|
|
126
|
+
Args:
|
|
127
|
+
filename: Name of the SQL template file.
|
|
128
|
+
path: Optional directory containing the template file.
|
|
129
|
+
|
|
130
|
+
Returns:
|
|
131
|
+
A Sql instance that loads from the template file.
|
|
132
|
+
"""
|
|
133
|
+
instance = cls(_read_sql_template, template_path=path, filename=filename)
|
|
134
|
+
instance._is_templated = True
|
|
135
|
+
return instance
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
#: Type alias for database row data returned by queries.
|
|
139
|
+
SqlRow: TypeAlias = tuple[Any, ...] | dict[str, Any] | Any
|
|
140
|
+
|
|
141
|
+
#: Type alias for row factory functions that transform raw rows.
|
|
142
|
+
RowFactory: TypeAlias = Callable[[sqlite3.Cursor, sqlite3.Row], SqlRow]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def dict_factory(cursor: sqlite3.Cursor, row: sqlite3.Row) -> dict[str, Any]:
|
|
146
|
+
"""Row factory that returns rows as dictionaries.
|
|
147
|
+
|
|
148
|
+
Example:
|
|
149
|
+
>>> with Db("mydb.sqlite", row_factory=dict_factory) as db:
|
|
150
|
+
... user = db.fetchone(Sql.raw("SELECT id, name FROM users"))
|
|
151
|
+
... print(user["name"])
|
|
152
|
+
"""
|
|
153
|
+
return {col[0]: row[idx] for idx, col in enumerate(cursor.description)}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@lru_cache(maxsize=128)
|
|
157
|
+
def _make_row_class(fields: tuple[str, ...]) -> type[tuple[Any, ...]]:
|
|
158
|
+
"""Create and cache a namedtuple class for the given field names."""
|
|
159
|
+
return namedtuple("Row", fields)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def namedtuple_factory(cursor: sqlite3.Cursor, row: sqlite3.Row) -> tuple[Any, ...]:
|
|
163
|
+
"""Row factory that returns rows as namedtuples.
|
|
164
|
+
|
|
165
|
+
Example:
|
|
166
|
+
>>> with Db("mydb.sqlite", row_factory=namedtuple_factory) as db:
|
|
167
|
+
... user = db.fetchone(Sql.raw("SELECT id, name FROM users"))
|
|
168
|
+
... print(user.name)
|
|
169
|
+
"""
|
|
170
|
+
fields = tuple(col[0] for col in cursor.description)
|
|
171
|
+
return _make_row_class(fields)(*row)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
_HOOKED_METHODS = frozenset({"execute", "executemany", "executescript"})
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class _SafeCursor:
|
|
178
|
+
"""Cursor proxy that blocks direct access to execute methods.
|
|
179
|
+
|
|
180
|
+
This prevents bypassing the Sql class by calling cursor.execute() directly.
|
|
181
|
+
All other cursor attributes are proxied through to the underlying cursor.
|
|
182
|
+
"""
|
|
183
|
+
|
|
184
|
+
__slots__ = ("__cursor",)
|
|
185
|
+
|
|
186
|
+
def __init__(self, cursor: sqlite3.Cursor) -> None:
|
|
187
|
+
object.__setattr__(self, "_SafeCursor__cursor", cursor)
|
|
188
|
+
|
|
189
|
+
def __getattr__(self, name: str) -> Any:
|
|
190
|
+
if name in _HOOKED_METHODS:
|
|
191
|
+
raise AttributeError(f"Cannot access {name} from cursor directly")
|
|
192
|
+
return getattr(self.__cursor, name)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
class Db:
|
|
196
|
+
"""SQLite database wrapper with SQL injection protection.
|
|
197
|
+
|
|
198
|
+
All queries must be wrapped in a Sql object, preventing direct string
|
|
199
|
+
execution. Supports both inline queries and SQL template files.
|
|
200
|
+
|
|
201
|
+
Args:
|
|
202
|
+
*args: Positional arguments passed to sqlite3.connect().
|
|
203
|
+
row_factory: Optional factory function to transform result rows.
|
|
204
|
+
sql_templates_dir: Optional directory for SQL template files.
|
|
205
|
+
autocommit: If True, disable transaction management.
|
|
206
|
+
**kwargs: Keyword arguments passed to sqlite3.connect().
|
|
207
|
+
|
|
208
|
+
Example:
|
|
209
|
+
>>> with Db("mydb.sqlite", row_factory=dict_factory) as db:
|
|
210
|
+
... db.commit(Sql.raw("INSERT INTO users (name) VALUES (?)"), ("Alice",))
|
|
211
|
+
... users = db.fetchall(Sql.raw("SELECT * FROM users"))
|
|
212
|
+
"""
|
|
213
|
+
|
|
214
|
+
def __init__(
|
|
215
|
+
self,
|
|
216
|
+
*args,
|
|
217
|
+
row_factory: RowFactory | None = None,
|
|
218
|
+
sql_templates_dir: Path | None = None,
|
|
219
|
+
autocommit: bool = False,
|
|
220
|
+
**kwargs,
|
|
221
|
+
) -> None:
|
|
222
|
+
if autocommit:
|
|
223
|
+
kwargs["isolation_level"] = None
|
|
224
|
+
self.conn = sqlite3.connect(*args, **kwargs)
|
|
225
|
+
if row_factory:
|
|
226
|
+
self.conn.row_factory = row_factory
|
|
227
|
+
self._cursor = _SafeCursor(self.conn.cursor())
|
|
228
|
+
self._sql_templates_dir = sql_templates_dir
|
|
229
|
+
self._method_cache: dict[str, Callable] = {}
|
|
230
|
+
|
|
231
|
+
@classmethod
|
|
232
|
+
def from_config(cls, config: DbPathConfig, **kwargs) -> Self:
|
|
233
|
+
"""Create a Db instance from a DbPathConfig.
|
|
234
|
+
|
|
235
|
+
Args:
|
|
236
|
+
config: Database path configuration.
|
|
237
|
+
**kwargs: Additional arguments passed to the constructor.
|
|
238
|
+
"""
|
|
239
|
+
return cls(
|
|
240
|
+
config.database,
|
|
241
|
+
sql_templates_dir=config.sql_templates_dir,
|
|
242
|
+
**kwargs,
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
def __enter__(self) -> Self:
|
|
246
|
+
return self
|
|
247
|
+
|
|
248
|
+
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
|
|
249
|
+
try:
|
|
250
|
+
self.conn.close()
|
|
251
|
+
except Exception:
|
|
252
|
+
# Suppress close errors to avoid masking the original exception
|
|
253
|
+
if exc_type is None:
|
|
254
|
+
raise
|
|
255
|
+
|
|
256
|
+
def _pre_execute_hook(self, sql: Sql) -> None:
|
|
257
|
+
"""Set deferred template path from config if not already set."""
|
|
258
|
+
if not sql.has_template_path and self._sql_templates_dir:
|
|
259
|
+
sql.set_template_path(self._sql_templates_dir)
|
|
260
|
+
|
|
261
|
+
def __getattribute__(self, name: str) -> Any:
|
|
262
|
+
attr = super().__getattribute__(name)
|
|
263
|
+
# inject hook before running sensitive methods
|
|
264
|
+
if name in _HOOKED_METHODS:
|
|
265
|
+
# Cache wrapper functions to avoid creating new ones on each access
|
|
266
|
+
cache = super().__getattribute__("_method_cache")
|
|
267
|
+
if name not in cache:
|
|
268
|
+
|
|
269
|
+
@wraps(attr)
|
|
270
|
+
def wrapper(*args, **kwargs):
|
|
271
|
+
self._pre_execute_hook(args[0])
|
|
272
|
+
return attr(*args, **kwargs)
|
|
273
|
+
|
|
274
|
+
cache[name] = wrapper
|
|
275
|
+
return cache[name]
|
|
276
|
+
return attr
|
|
277
|
+
|
|
278
|
+
def execute(self, sql: Sql, *args) -> sqlite3.Cursor:
|
|
279
|
+
"""Execute a SQL query and return the cursor.
|
|
280
|
+
|
|
281
|
+
Args:
|
|
282
|
+
sql: The Sql object containing the query.
|
|
283
|
+
*args: Parameters to bind to the query.
|
|
284
|
+
"""
|
|
285
|
+
return self._cursor._SafeCursor__cursor.execute(sql.load_query(), *args)
|
|
286
|
+
|
|
287
|
+
def executemany(self, sql: Sql, *args) -> sqlite3.Cursor:
|
|
288
|
+
"""Execute a SQL query against multiple parameter sets.
|
|
289
|
+
|
|
290
|
+
Args:
|
|
291
|
+
sql: The Sql object containing the query.
|
|
292
|
+
*args: Sequence of parameter sets.
|
|
293
|
+
"""
|
|
294
|
+
return self._cursor._SafeCursor__cursor.executemany(sql.load_query(), *args)
|
|
295
|
+
|
|
296
|
+
def executescript(self, sql: Sql) -> sqlite3.Cursor:
|
|
297
|
+
"""Execute multiple SQL statements as a script.
|
|
298
|
+
|
|
299
|
+
Args:
|
|
300
|
+
sql: The Sql object containing the script.
|
|
301
|
+
"""
|
|
302
|
+
return self._cursor._SafeCursor__cursor.executescript(sql.load_query())
|
|
303
|
+
|
|
304
|
+
def fetchone(self, sql: Sql, *args) -> SqlRow | None:
|
|
305
|
+
"""Execute a query and return the first result row, or None.
|
|
306
|
+
|
|
307
|
+
Args:
|
|
308
|
+
sql: The Sql object containing the query.
|
|
309
|
+
*args: Parameters to bind to the query.
|
|
310
|
+
"""
|
|
311
|
+
return self.execute(sql, *args).fetchone()
|
|
312
|
+
|
|
313
|
+
def fetchall(self, sql: Sql, *args) -> list[SqlRow]:
|
|
314
|
+
"""Execute a query and return all result rows.
|
|
315
|
+
|
|
316
|
+
Args:
|
|
317
|
+
sql: The Sql object containing the query.
|
|
318
|
+
*args: Parameters to bind to the query.
|
|
319
|
+
"""
|
|
320
|
+
return self.execute(sql, *args).fetchall()
|
|
321
|
+
|
|
322
|
+
def commit(self, sql: Sql, *args) -> None:
|
|
323
|
+
"""Execute a query and commit the transaction.
|
|
324
|
+
|
|
325
|
+
Args:
|
|
326
|
+
sql: The Sql object containing the query.
|
|
327
|
+
*args: Parameters to bind to the query.
|
|
328
|
+
"""
|
|
329
|
+
self.execute(sql, *args)
|
|
330
|
+
self.conn.commit()
|
|
@@ -1,4 +1,12 @@
|
|
|
1
|
-
|
|
1
|
+
"""Tests for the sqlitey module.
|
|
2
|
+
|
|
3
|
+
This module tests the core functionality of sqlitey including:
|
|
4
|
+
- Sql class (raw and template queries)
|
|
5
|
+
- Db class (execute, fetch, commit operations)
|
|
6
|
+
- Row factories (dict and namedtuple)
|
|
7
|
+
- Security features (cursor protection, path traversal prevention)
|
|
8
|
+
"""
|
|
9
|
+
|
|
2
10
|
import sqlite3
|
|
3
11
|
from pathlib import Path
|
|
4
12
|
from sqlite3.dbapi2 import OperationalError
|
|
@@ -11,6 +19,12 @@ from sqlitey import Db, DbPathConfig, Sql, dict_factory, namedtuple_factory
|
|
|
11
19
|
|
|
12
20
|
@fixture
|
|
13
21
|
def temp_db_path():
|
|
22
|
+
"""Create a temporary SQLite database with test data.
|
|
23
|
+
|
|
24
|
+
Yields a path to a database containing a 'users' table with two rows:
|
|
25
|
+
- (1, 'Alice')
|
|
26
|
+
- (2, 'John')
|
|
27
|
+
"""
|
|
14
28
|
with NamedTemporaryFile(suffix=".db", delete=True) as tmp:
|
|
15
29
|
db_path = Path(tmp.name)
|
|
16
30
|
conn = sqlite3.connect(db_path)
|
|
@@ -23,6 +37,7 @@ def temp_db_path():
|
|
|
23
37
|
|
|
24
38
|
@fixture
|
|
25
39
|
def config(temp_db_path):
|
|
40
|
+
"""Create a DbPathConfig with the temp database and test SQL templates."""
|
|
26
41
|
return DbPathConfig(
|
|
27
42
|
database=temp_db_path,
|
|
28
43
|
sql_templates_dir=Path(__file__).resolve().parent / "sql"
|
|
@@ -123,9 +138,9 @@ def test_access_cursor_execute(config):
|
|
|
123
138
|
"""Test accessing cursor.execute() is forbidden."""
|
|
124
139
|
with Db.from_config(config) as db:
|
|
125
140
|
with raises(AttributeError, match="Cannot access execute from cursor directly"):
|
|
126
|
-
db.
|
|
141
|
+
db._cursor.execute(Sql.raw("SELECT 1;"))
|
|
127
142
|
# however we should be able to access other attributes
|
|
128
|
-
assert db.
|
|
143
|
+
assert db._cursor.rowcount == -1
|
|
129
144
|
|
|
130
145
|
|
|
131
146
|
def test_db_autocommit_behaviour(config):
|
|
@@ -178,3 +193,38 @@ def test_executemany(config):
|
|
|
178
193
|
results = db.fetchall(Sql.raw("SELECT name FROM users"))
|
|
179
194
|
assert "Alicia" in str(results)
|
|
180
195
|
assert "Bobby" in str(results)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def test_template_path_traversal_dotdot():
|
|
199
|
+
"""Test path traversal with .. is blocked."""
|
|
200
|
+
sql = Sql.template("../etc/passwd", path=Path(__file__).resolve().parent / "sql")
|
|
201
|
+
with raises(ValueError, match="Invalid template filename"):
|
|
202
|
+
sql.load_query()
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def test_template_path_traversal_absolute():
|
|
206
|
+
"""Test path traversal with absolute path is blocked."""
|
|
207
|
+
sql = Sql.template("/etc/passwd", path=Path(__file__).resolve().parent / "sql")
|
|
208
|
+
with raises(ValueError, match="Invalid template filename"):
|
|
209
|
+
sql.load_query()
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def test_template_file_not_found():
|
|
213
|
+
"""Test loading a template that doesn't exist."""
|
|
214
|
+
sql = Sql.template("nonexistent.sql", path=Path(__file__).resolve().parent / "sql")
|
|
215
|
+
with raises(FileNotFoundError, match="SQL template not found"):
|
|
216
|
+
sql.load_query()
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def test_access_cursor_executemany(config):
|
|
220
|
+
"""Test accessing cursor.executemany() is forbidden."""
|
|
221
|
+
with Db.from_config(config) as db:
|
|
222
|
+
with raises(AttributeError, match="Cannot access executemany from cursor directly"):
|
|
223
|
+
db._cursor.executemany(Sql.raw("SELECT 1;"), [])
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def test_access_cursor_executescript(config):
|
|
227
|
+
"""Test accessing cursor.executescript() is forbidden."""
|
|
228
|
+
with Db.from_config(config) as db:
|
|
229
|
+
with raises(AttributeError, match="Cannot access executescript from cursor directly"):
|
|
230
|
+
db._cursor.executescript(Sql.raw("SELECT 1;"))
|
sqlitey-0.1.0/PKG-INFO
DELETED
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: SQLitey
|
|
3
|
-
Version: 0.1.0
|
|
4
|
-
Summary: Useful wrapper around SQLite
|
|
5
|
-
License: The MIT License (MIT)
|
|
6
|
-
|
|
7
|
-
Copyright (c) 2025 Matthieu Petiteau
|
|
8
|
-
|
|
9
|
-
Permission is hereby granted, free of charge, to any person obtaining
|
|
10
|
-
a copy of this software and associated documentation files (the
|
|
11
|
-
"Software"), to deal in the Software without restriction, including
|
|
12
|
-
without limitation the rights to use, copy, modify, merge, publish,
|
|
13
|
-
distribute, sublicense, and/or sell copies of the Software, and to
|
|
14
|
-
permit persons to whom the Software is furnished to do so, subject to
|
|
15
|
-
the following conditions:
|
|
16
|
-
|
|
17
|
-
The above copyright notice and this permission notice shall be
|
|
18
|
-
included in all copies or substantial portions of the Software.
|
|
19
|
-
|
|
20
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
21
|
-
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
22
|
-
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
23
|
-
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
|
24
|
-
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
|
25
|
-
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
|
26
|
-
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
27
|
-
License-File: LICENSE
|
|
28
|
-
Requires-Python: >=3.11
|
|
29
|
-
Description-Content-Type: text/markdown
|
|
30
|
-
|
|
31
|
-
# SQLitey
|
|
32
|
-
|
|
33
|
-
SQLitey is a lightweight and flexible wrapper around SQLite, designed to streamline database access using configuration files, SQL templates, and custom row factories.
|
|
34
|
-
|
|
35
|
-
Key Features:
|
|
36
|
-
- Configuration-driven setup for database paths and SQL templates
|
|
37
|
-
- Support for SQL template files to keep queries organized
|
|
38
|
-
- Customizable row factories (e.g., return rows as namedtuples)
|
|
39
|
-
- Support for both templated and raw SQL queries
|
|
40
|
-
- Optional config usage for quick, one-off database access
|
|
41
|
-
|
|
42
|
-
## Exampe usage
|
|
43
|
-
|
|
44
|
-
### Using a Config File
|
|
45
|
-
|
|
46
|
-
Define a configuration with the database path and the directory for SQL templates:
|
|
47
|
-
|
|
48
|
-
``` python
|
|
49
|
-
from pathlib import Path
|
|
50
|
-
from sqlitey import Db, DbPathConfig, Sql, namedtuple_factory
|
|
51
|
-
|
|
52
|
-
dir = Path(__file__).resolve().parent
|
|
53
|
-
config = DbPathConfig(
|
|
54
|
-
database=dir / "db.sqlite3",
|
|
55
|
-
sql_templates_dir=dir / "sql"
|
|
56
|
-
)
|
|
57
|
-
|
|
58
|
-
with Db.from_config(config, row_factory=namedtuple_factory) as db:
|
|
59
|
-
result = db.fetchone(Sql.template("get_user_by_id.sql"), (3,))
|
|
60
|
-
print(result.id, result.name)
|
|
61
|
-
```
|
|
62
|
-
|
|
63
|
-
### Executing Raw SQL
|
|
64
|
-
|
|
65
|
-
You can also use raw SQL directly:
|
|
66
|
-
|
|
67
|
-
``` python
|
|
68
|
-
with Db.from_config(config, timeout=15) as db:
|
|
69
|
-
db.commit(Sql.raw("INSERT INTO users VALUES (10, 'John');"))
|
|
70
|
-
```
|
|
71
|
-
|
|
72
|
-
### Without a Config File
|
|
73
|
-
|
|
74
|
-
Skip the config and use the database path directly:
|
|
75
|
-
|
|
76
|
-
``` python
|
|
77
|
-
with Db("db.sqlite3", autocommit=True) as db:
|
|
78
|
-
db.execute(Sql.raw("UPDATE users SET name = 'Johnny' WHERE id = 10;"))
|
|
79
|
-
|
|
80
|
-
with Db("db.sqlite3") as db:
|
|
81
|
-
sql = Sql.template("get_user_by_id.sql", path=Path(__file__).resolve().parent / "sql")
|
|
82
|
-
result = db.fetchone(sql, (3,))
|
|
83
|
-
```
|
|
84
|
-
|
|
85
|
-
### More examples
|
|
86
|
-
|
|
87
|
-
See more examples in [tests](./tests/test_sqlight.py)
|
sqlitey-0.1.0/README.md
DELETED
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
# SQLitey
|
|
2
|
-
|
|
3
|
-
SQLitey is a lightweight and flexible wrapper around SQLite, designed to streamline database access using configuration files, SQL templates, and custom row factories.
|
|
4
|
-
|
|
5
|
-
Key Features:
|
|
6
|
-
- Configuration-driven setup for database paths and SQL templates
|
|
7
|
-
- Support for SQL template files to keep queries organized
|
|
8
|
-
- Customizable row factories (e.g., return rows as namedtuples)
|
|
9
|
-
- Support for both templated and raw SQL queries
|
|
10
|
-
- Optional config usage for quick, one-off database access
|
|
11
|
-
|
|
12
|
-
## Exampe usage
|
|
13
|
-
|
|
14
|
-
### Using a Config File
|
|
15
|
-
|
|
16
|
-
Define a configuration with the database path and the directory for SQL templates:
|
|
17
|
-
|
|
18
|
-
``` python
|
|
19
|
-
from pathlib import Path
|
|
20
|
-
from sqlitey import Db, DbPathConfig, Sql, namedtuple_factory
|
|
21
|
-
|
|
22
|
-
dir = Path(__file__).resolve().parent
|
|
23
|
-
config = DbPathConfig(
|
|
24
|
-
database=dir / "db.sqlite3",
|
|
25
|
-
sql_templates_dir=dir / "sql"
|
|
26
|
-
)
|
|
27
|
-
|
|
28
|
-
with Db.from_config(config, row_factory=namedtuple_factory) as db:
|
|
29
|
-
result = db.fetchone(Sql.template("get_user_by_id.sql"), (3,))
|
|
30
|
-
print(result.id, result.name)
|
|
31
|
-
```
|
|
32
|
-
|
|
33
|
-
### Executing Raw SQL
|
|
34
|
-
|
|
35
|
-
You can also use raw SQL directly:
|
|
36
|
-
|
|
37
|
-
``` python
|
|
38
|
-
with Db.from_config(config, timeout=15) as db:
|
|
39
|
-
db.commit(Sql.raw("INSERT INTO users VALUES (10, 'John');"))
|
|
40
|
-
```
|
|
41
|
-
|
|
42
|
-
### Without a Config File
|
|
43
|
-
|
|
44
|
-
Skip the config and use the database path directly:
|
|
45
|
-
|
|
46
|
-
``` python
|
|
47
|
-
with Db("db.sqlite3", autocommit=True) as db:
|
|
48
|
-
db.execute(Sql.raw("UPDATE users SET name = 'Johnny' WHERE id = 10;"))
|
|
49
|
-
|
|
50
|
-
with Db("db.sqlite3") as db:
|
|
51
|
-
sql = Sql.template("get_user_by_id.sql", path=Path(__file__).resolve().parent / "sql")
|
|
52
|
-
result = db.fetchone(sql, (3,))
|
|
53
|
-
```
|
|
54
|
-
|
|
55
|
-
### More examples
|
|
56
|
-
|
|
57
|
-
See more examples in [tests](./tests/test_sqlight.py)
|
|
@@ -1,154 +0,0 @@
|
|
|
1
|
-
import sqlite3
|
|
2
|
-
from collections import namedtuple
|
|
3
|
-
from dataclasses import dataclass
|
|
4
|
-
from functools import lru_cache
|
|
5
|
-
from pathlib import Path
|
|
6
|
-
from typing import Any, Callable, Self, TypeAlias
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
@dataclass(frozen=True)
|
|
10
|
-
class DbPathConfig:
|
|
11
|
-
"""Database path configurations."""
|
|
12
|
-
|
|
13
|
-
# database filepath
|
|
14
|
-
database: Path
|
|
15
|
-
# directory storing sql templates
|
|
16
|
-
sql_templates_dir: Path | None = None
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
@lru_cache
|
|
20
|
-
def _read_sql_template(filename: str, template_path: Path) -> str:
|
|
21
|
-
return (template_path / filename).read_text().strip()
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
class Sql:
|
|
25
|
-
"""Represent a SQL query."""
|
|
26
|
-
|
|
27
|
-
_is_templated = False
|
|
28
|
-
|
|
29
|
-
def __init__(self, query_loader: Callable, **kwargs) -> None:
|
|
30
|
-
self._query_loader = query_loader
|
|
31
|
-
self._store = kwargs
|
|
32
|
-
|
|
33
|
-
@property
|
|
34
|
-
def has_template_path(self) -> bool:
|
|
35
|
-
return bool(self._is_templated and self._store.get("template_path"))
|
|
36
|
-
|
|
37
|
-
def set_template_path(self, template_path: Path) -> None:
|
|
38
|
-
if self._is_templated:
|
|
39
|
-
self._store["template_path"] = template_path
|
|
40
|
-
|
|
41
|
-
def load_query(self) -> str:
|
|
42
|
-
if self._is_templated and not self.has_template_path:
|
|
43
|
-
raise ValueError("No template path configured")
|
|
44
|
-
return self._query_loader(**self._store)
|
|
45
|
-
|
|
46
|
-
@classmethod
|
|
47
|
-
def raw(cls, query: str) -> Self:
|
|
48
|
-
return cls(lambda *args, **kwargs: query)
|
|
49
|
-
|
|
50
|
-
@classmethod
|
|
51
|
-
def template(cls, filename: str, *, path: Path | None = None) -> Self:
|
|
52
|
-
# path is optional so we can defer setting at a later time, in order to
|
|
53
|
-
# derive its value from a config for example.
|
|
54
|
-
cls_ = cls(_read_sql_template, template_path=path, filename=filename)
|
|
55
|
-
cls_._is_templated = True
|
|
56
|
-
return cls_
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
SqlRow: TypeAlias = Any
|
|
60
|
-
RowFactory: TypeAlias = Callable[[sqlite3.Cursor, sqlite3.Row], SqlRow]
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
def dict_factory(cursor: sqlite3.Cursor, row: sqlite3.Row) -> SqlRow:
|
|
64
|
-
return {col[0]: row[idx] for idx, col in enumerate(cursor.description)}
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
def namedtuple_factory(cursor: sqlite3.Cursor, row: sqlite3.Row) -> SqlRow:
|
|
68
|
-
Row = namedtuple("Row", [str(col[0]) for col in cursor.description]) # type: ignore
|
|
69
|
-
return Row(*row)
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
_HOOKED_METHODS = ("execute", "executemany", "executescript")
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
class _SafeCursor:
|
|
76
|
-
"""Proxy to protect `cursor.execute` to be accessed directly."""
|
|
77
|
-
|
|
78
|
-
def __init__(self, safe_cursor: sqlite3.Cursor) -> None:
|
|
79
|
-
self._safe_cursor = safe_cursor
|
|
80
|
-
|
|
81
|
-
def __getattr__(self, name: str) -> Any:
|
|
82
|
-
if name in _HOOKED_METHODS:
|
|
83
|
-
raise AttributeError(f"Cannot access {name} from cursor directly")
|
|
84
|
-
return getattr(self._safe_cursor, name)
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
class Db:
|
|
88
|
-
"""SQLite wrapper class."""
|
|
89
|
-
|
|
90
|
-
def __init__(
|
|
91
|
-
self,
|
|
92
|
-
*args,
|
|
93
|
-
row_factory: RowFactory | None = None,
|
|
94
|
-
sql_templates_dir: Path | None = None,
|
|
95
|
-
autocommit: bool = False,
|
|
96
|
-
**kwargs,
|
|
97
|
-
) -> None:
|
|
98
|
-
if autocommit:
|
|
99
|
-
kwargs["isolation_level"] = None
|
|
100
|
-
self.conn = sqlite3.connect(*args, **kwargs)
|
|
101
|
-
if row_factory:
|
|
102
|
-
self.conn.row_factory = row_factory
|
|
103
|
-
self.cursor = _SafeCursor(self.conn.cursor())
|
|
104
|
-
self._sql_templates_dir = sql_templates_dir
|
|
105
|
-
|
|
106
|
-
@classmethod
|
|
107
|
-
def from_config(cls, config: DbPathConfig, **kwargs) -> Self:
|
|
108
|
-
return cls(
|
|
109
|
-
config.database,
|
|
110
|
-
sql_templates_dir=config.sql_templates_dir,
|
|
111
|
-
**kwargs,
|
|
112
|
-
)
|
|
113
|
-
|
|
114
|
-
def __enter__(self) -> Self:
|
|
115
|
-
return self
|
|
116
|
-
|
|
117
|
-
def __exit__(self, *args, **kwargs) -> None:
|
|
118
|
-
self.conn.close()
|
|
119
|
-
|
|
120
|
-
def _pre_execute_hook(self, sql: Sql) -> None:
|
|
121
|
-
if not sql.has_template_path and self._sql_templates_dir:
|
|
122
|
-
# path is deferred, lets set it from the config
|
|
123
|
-
sql.set_template_path(self._sql_templates_dir)
|
|
124
|
-
|
|
125
|
-
def __getattribute__(self, name: str) -> Any:
|
|
126
|
-
attr = super().__getattribute__(name)
|
|
127
|
-
# inject hook before running sensitive methods
|
|
128
|
-
if name in _HOOKED_METHODS:
|
|
129
|
-
|
|
130
|
-
def wrapper(*args, **kwargs):
|
|
131
|
-
self._pre_execute_hook(args[0])
|
|
132
|
-
return attr(*args, **kwargs)
|
|
133
|
-
|
|
134
|
-
return wrapper
|
|
135
|
-
return attr
|
|
136
|
-
|
|
137
|
-
def execute(self, sql: Sql, *args) -> SqlRow:
|
|
138
|
-
return self.cursor._safe_cursor.execute(sql.load_query(), *args)
|
|
139
|
-
|
|
140
|
-
def executemany(self, sql: Sql, *args) -> SqlRow:
|
|
141
|
-
return self.cursor._safe_cursor.executemany(sql.load_query(), *args)
|
|
142
|
-
|
|
143
|
-
def executescript(self, sql: Sql) -> SqlRow:
|
|
144
|
-
return self.cursor._safe_cursor.executescript(sql.load_query())
|
|
145
|
-
|
|
146
|
-
def fetchone(self, sql: Sql, *args) -> SqlRow:
|
|
147
|
-
return self.execute(sql, *args).fetchone()
|
|
148
|
-
|
|
149
|
-
def fetchall(self, sql: Sql, *args) -> list[SqlRow]:
|
|
150
|
-
return self.execute(sql, *args).fetchall()
|
|
151
|
-
|
|
152
|
-
def commit(self, sql: Sql, *args) -> None:
|
|
153
|
-
self.execute(sql, *args)
|
|
154
|
-
self.conn.commit()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|