SQLitey 0.1.0__py3-none-any.whl
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/__init__.py +154 -0
- sqlitey-0.1.0.dist-info/METADATA +87 -0
- sqlitey-0.1.0.dist-info/RECORD +5 -0
- sqlitey-0.1.0.dist-info/WHEEL +4 -0
- sqlitey-0.1.0.dist-info/licenses/LICENSE +22 -0
sqlitey/__init__.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
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()
|
|
@@ -0,0 +1,87 @@
|
|
|
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)
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
sqlitey/__init__.py,sha256=8plqNkh0YMvN9_dJ8FM8OcYy-vDfam88liZbLuJVUNI,4813
|
|
2
|
+
sqlitey-0.1.0.dist-info/METADATA,sha256=Rkpn1xIX_iEMm996L3UNBgOGHDCjMiQySYbX4u_C_3Q,3092
|
|
3
|
+
sqlitey-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
4
|
+
sqlitey-0.1.0.dist-info/licenses/LICENSE,sha256=0u06wIiVg9FooZGOF0fBibfyDmYSxRORrErXYN9xb5s,1084
|
|
5
|
+
sqlitey-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Matthieu Petiteau
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
6
|
+
a copy of this software and associated documentation files (the
|
|
7
|
+
"Software"), to deal in the Software without restriction, including
|
|
8
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
|
9
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
|
10
|
+
permit persons to whom the Software is furnished to do so, subject to
|
|
11
|
+
the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be
|
|
14
|
+
included in all copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
17
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
18
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
19
|
+
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
|
20
|
+
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
|
21
|
+
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
|
22
|
+
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|