SQLitey 0.1.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.
- sqlitey-0.1.0/.github/workflows/ci.yaml +22 -0
- sqlitey-0.1.0/.gitignore +6 -0
- sqlitey-0.1.0/.python-version +1 -0
- sqlitey-0.1.0/LICENSE +22 -0
- sqlitey-0.1.0/Makefile +47 -0
- sqlitey-0.1.0/PKG-INFO +87 -0
- sqlitey-0.1.0/README.md +57 -0
- sqlitey-0.1.0/pyproject.toml +23 -0
- sqlitey-0.1.0/sqlitey/__init__.py +154 -0
- sqlitey-0.1.0/tests/__init__.py +0 -0
- sqlitey-0.1.0/tests/sql/test.sql +1 -0
- sqlitey-0.1.0/tests/test_sqlitey.py +180 -0
- sqlitey-0.1.0/uv.lock +789 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
on: [push, pull_request]
|
|
3
|
+
jobs:
|
|
4
|
+
build:
|
|
5
|
+
runs-on: ubuntu-latest
|
|
6
|
+
strategy:
|
|
7
|
+
matrix:
|
|
8
|
+
python-version: ["3.11", "3.12"]
|
|
9
|
+
steps:
|
|
10
|
+
- uses: actions/checkout@v3
|
|
11
|
+
- name: Set up Python ${{ matrix.python-version }}
|
|
12
|
+
uses: actions/setup-python@v4
|
|
13
|
+
with:
|
|
14
|
+
python-version: ${{ matrix.python-version }}
|
|
15
|
+
- name: Install dependencies
|
|
16
|
+
run: pip install uv && uv sync --inexact
|
|
17
|
+
- name: Lint with Ruff
|
|
18
|
+
run: python -m uv run ruff check sqlitey
|
|
19
|
+
- name: Run Mypy
|
|
20
|
+
run: python -m uv run mypy sqlitey
|
|
21
|
+
- name: Test suite
|
|
22
|
+
run: python -m uv run pytest --cov=sqlitey tests
|
sqlitey-0.1.0/.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
3.11
|
sqlitey-0.1.0/LICENSE
ADDED
|
@@ -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.
|
sqlitey-0.1.0/Makefile
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
SRC = sqlitey
|
|
2
|
+
|
|
3
|
+
.PHONY: help
|
|
4
|
+
help: ## Show this help menu
|
|
5
|
+
@echo "Usage: make [TARGET ...]"
|
|
6
|
+
@echo ""
|
|
7
|
+
@grep --no-filename -E '^[a-zA-Z_%-]+:.*?## .*$$' $(MAKEFILE_LIST) | \
|
|
8
|
+
awk 'BEGIN {FS = ":.*?## "}; {printf "%-25s %s\n", $$1, $$2}'
|
|
9
|
+
|
|
10
|
+
VENV = .venv
|
|
11
|
+
VENV_PYTHON = $(VENV)/bin/python
|
|
12
|
+
SYSTEM_PYTHON = $(shell which python3.13)
|
|
13
|
+
PYTHON = $(wildcard $(VENV_PYTHON))
|
|
14
|
+
|
|
15
|
+
$(VENV_PYTHON):
|
|
16
|
+
rm -rf $(VENV)
|
|
17
|
+
$(SYSTEM_PYTHON) -m venv $(VENV)
|
|
18
|
+
|
|
19
|
+
.PHONY: venv
|
|
20
|
+
venv: $(VENV_PYTHON) ## Create a Python virtual environment
|
|
21
|
+
|
|
22
|
+
.PHONY: deps
|
|
23
|
+
deps: venv ## Install requirements in virtual environment
|
|
24
|
+
$(PYTHON) -m ensurepip
|
|
25
|
+
$(PYTHON) -m pip install uv
|
|
26
|
+
$(PYTHON) -m uv sync --inexact
|
|
27
|
+
|
|
28
|
+
.PHONY: tests
|
|
29
|
+
tests: ## Run unit tests
|
|
30
|
+
$(PYTHON) -m uv run pytest --cov=$(SRC) --cov-report term-missing tests
|
|
31
|
+
|
|
32
|
+
.PHONY: mypy
|
|
33
|
+
mypy: ## Run mypy
|
|
34
|
+
$(PYTHON) -m uv run mypy $(SRC)
|
|
35
|
+
|
|
36
|
+
.PHONY: ruff
|
|
37
|
+
ruff: ## Run ruff
|
|
38
|
+
$(PYTHON) -m uv run ruff check $(SRC)
|
|
39
|
+
|
|
40
|
+
.PHONY: black
|
|
41
|
+
black: ## Run black
|
|
42
|
+
$(PYTHON) -m uv run black $(SRC)
|
|
43
|
+
|
|
44
|
+
.PHONY: release
|
|
45
|
+
release: ## Release to PyPI
|
|
46
|
+
$(PYTHON) -m build
|
|
47
|
+
$(PYTHON) -m twine upload dist/*
|
sqlitey-0.1.0/PKG-INFO
ADDED
|
@@ -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)
|
sqlitey-0.1.0/README.md
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
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)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "SQLitey"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Useful wrapper around SQLite"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = { file="LICENSE" }
|
|
7
|
+
requires-python = ">=3.11"
|
|
8
|
+
dependencies = []
|
|
9
|
+
|
|
10
|
+
[dependency-groups]
|
|
11
|
+
dev = [
|
|
12
|
+
"black>=25.1.0",
|
|
13
|
+
"build>=1.2.2.post1",
|
|
14
|
+
"mypy>=1.16.0",
|
|
15
|
+
"pytest>=8.3.5",
|
|
16
|
+
"pytest-cov>=6.1.1",
|
|
17
|
+
"ruff>=0.11.11",
|
|
18
|
+
"twine>=6.1.0",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[build-system]
|
|
22
|
+
requires = ["hatchling"]
|
|
23
|
+
build-backend = "hatchling.build"
|
|
@@ -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()
|
|
File without changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
SELECT 1;
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import re
|
|
2
|
+
import sqlite3
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from sqlite3.dbapi2 import OperationalError
|
|
5
|
+
from tempfile import NamedTemporaryFile
|
|
6
|
+
|
|
7
|
+
from pytest import fixture, raises
|
|
8
|
+
|
|
9
|
+
from sqlitey import Db, DbPathConfig, Sql, dict_factory, namedtuple_factory
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@fixture
|
|
13
|
+
def temp_db_path():
|
|
14
|
+
with NamedTemporaryFile(suffix=".db", delete=True) as tmp:
|
|
15
|
+
db_path = Path(tmp.name)
|
|
16
|
+
conn = sqlite3.connect(db_path)
|
|
17
|
+
conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
|
|
18
|
+
conn.execute("INSERT INTO users VALUES (1, 'Alice'), (2, 'John')")
|
|
19
|
+
conn.commit()
|
|
20
|
+
conn.close()
|
|
21
|
+
yield db_path
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@fixture
|
|
25
|
+
def config(temp_db_path):
|
|
26
|
+
return DbPathConfig(
|
|
27
|
+
database=temp_db_path,
|
|
28
|
+
sql_templates_dir=Path(__file__).resolve().parent / "sql"
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_raw_sql():
|
|
33
|
+
"""Test loading raw SQL."""
|
|
34
|
+
sql = Sql.raw("SELECT 1")
|
|
35
|
+
assert sql.load_query() == "SELECT 1"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_template_sql_no_path_config():
|
|
39
|
+
"""Test loading a template without a path."""
|
|
40
|
+
sql = Sql.template("test.sql")
|
|
41
|
+
with raises(ValueError, match="No template path configured"):
|
|
42
|
+
sql.load_query()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def test_template_sql():
|
|
46
|
+
"""Test loading a template."""
|
|
47
|
+
sql = Sql.template("test.sql", path=Path(__file__).resolve().parent / "sql")
|
|
48
|
+
assert sql.load_query() == "SELECT 1;"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def test_db_fetchone(config):
|
|
52
|
+
"""Test using fetchone."""
|
|
53
|
+
sql = Sql.raw("SELECT id, name FROM users WHERE id = ?")
|
|
54
|
+
with Db.from_config(config) as db:
|
|
55
|
+
result = db.fetchone(sql, (1,))
|
|
56
|
+
assert result == (1, "Alice")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def test_db_fetchone_dict_factory(config):
|
|
60
|
+
"""Test using fetchone and the dict factory."""
|
|
61
|
+
sql = Sql.raw("SELECT id, name FROM users WHERE id = ?")
|
|
62
|
+
with Db.from_config(config, row_factory=dict_factory) as db:
|
|
63
|
+
result = db.fetchone(sql, (1,))
|
|
64
|
+
assert result == {"id": 1, "name": "Alice"}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def test_db_fetchone_namedtuple_factory(config):
|
|
68
|
+
"""Test using fetchone and the namedtuple factory."""
|
|
69
|
+
sql = Sql.raw("SELECT id, name FROM users WHERE id = ?")
|
|
70
|
+
with Db.from_config(config, row_factory=namedtuple_factory) as db:
|
|
71
|
+
result = db.fetchone(sql, (1,))
|
|
72
|
+
assert result.id == 1
|
|
73
|
+
assert result.name == "Alice"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def test_db_fetchall(config):
|
|
77
|
+
"""Test using fetchall."""
|
|
78
|
+
sql = Sql.raw("SELECT id, name FROM users")
|
|
79
|
+
with Db.from_config(config) as db:
|
|
80
|
+
results = db.fetchall(sql)
|
|
81
|
+
assert results == [(1, "Alice"), (2, "John")]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def test_db_fetchall_dict_factory(config):
|
|
85
|
+
"""Test using fetchall and the dict factory."""
|
|
86
|
+
sql = Sql.raw("SELECT id, name FROM users")
|
|
87
|
+
with Db.from_config(config, row_factory=dict_factory) as db:
|
|
88
|
+
results = db.fetchall(sql)
|
|
89
|
+
assert results == [{"id": 1, "name": "Alice"}, {"id": 2, "name": "John"}]
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def test_db_fetchall_namedtuple_factory(config):
|
|
93
|
+
"""Test using fetchall and the namedtuple factory."""
|
|
94
|
+
sql = Sql.raw("SELECT id, name FROM users")
|
|
95
|
+
with Db.from_config(config, row_factory=namedtuple_factory) as db:
|
|
96
|
+
results = db.fetchall(sql)
|
|
97
|
+
assert results[0].id == 1
|
|
98
|
+
assert results[0].name == "Alice"
|
|
99
|
+
assert results[1].id == 2
|
|
100
|
+
assert results[1].name == "John"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def test_db_commit(config):
|
|
104
|
+
"""Test using commit."""
|
|
105
|
+
with Db.from_config(config, row_factory=namedtuple_factory) as db:
|
|
106
|
+
db.commit(Sql.raw("INSERT INTO users VALUES (3, 'Kate')"))
|
|
107
|
+
result = db.fetchone(Sql.raw("SELECT COUNT(id) as total FROM users"))
|
|
108
|
+
assert result.total == 3
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def test_db_context_manager_rollback(config):
|
|
112
|
+
"""Test rolling back in context manager."""
|
|
113
|
+
with raises(OperationalError):
|
|
114
|
+
with Db.from_config(config) as db:
|
|
115
|
+
db.execute(Sql.raw("INSERT INTO users VALUES (3, 'Kate')"))
|
|
116
|
+
db.execute(Sql.raw("SYNTAX ERROR;")) # raise
|
|
117
|
+
with Db.from_config(config) as db:
|
|
118
|
+
result = db.fetchone(Sql.raw("SELECT id FROM users WHERE id = 3"))
|
|
119
|
+
assert result is None
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def test_access_cursor_execute(config):
|
|
123
|
+
"""Test accessing cursor.execute() is forbidden."""
|
|
124
|
+
with Db.from_config(config) as db:
|
|
125
|
+
with raises(AttributeError, match="Cannot access execute from cursor directly"):
|
|
126
|
+
db.cursor.execute(Sql.raw("SELECT 1;"))
|
|
127
|
+
# however we should be able to access other attributes
|
|
128
|
+
assert db.cursor.rowcount == -1
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def test_db_autocommit_behaviour(config):
|
|
132
|
+
"""Test autocommit works as expected in context manager."""
|
|
133
|
+
with raises(OperationalError):
|
|
134
|
+
with Db.from_config(config, autocommit=True) as db:
|
|
135
|
+
db.execute(Sql.raw("INSERT INTO users VALUES (3, 'Kate')"))
|
|
136
|
+
db.execute(Sql.raw("SYNTAX ERROR")) # raise
|
|
137
|
+
with Db.from_config(config) as db:
|
|
138
|
+
result = db.fetchone(Sql.raw("SELECT id FROM users WHERE id = 3"))
|
|
139
|
+
assert result == (3,)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def test_db_undefer_template_path(temp_db_path):
|
|
143
|
+
"""Test setting template path not using a config."""
|
|
144
|
+
sql = Sql.template("test.sql", path=Path(__file__).resolve().parent / "sql")
|
|
145
|
+
with Db(temp_db_path) as db:
|
|
146
|
+
result = db.fetchone(sql)
|
|
147
|
+
assert result == (1,)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def test_db_defer_template_path(config):
|
|
151
|
+
"""Test setting template path from a config."""
|
|
152
|
+
with Db.from_config(config) as db:
|
|
153
|
+
result = db.fetchone(Sql.template("test.sql"))
|
|
154
|
+
assert result == (1,)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def test_executescript(config):
|
|
158
|
+
"""Test using executescript."""
|
|
159
|
+
with Db.from_config(config) as db:
|
|
160
|
+
db.executescript(
|
|
161
|
+
Sql.raw(
|
|
162
|
+
"INSERT INTO users VALUES (3, 'Kate');"
|
|
163
|
+
"INSERT INTO users VALUES (4, 'Johny');"
|
|
164
|
+
)
|
|
165
|
+
)
|
|
166
|
+
result = db.fetchone(Sql.raw("SELECT COUNT(id) as total FROM users"))
|
|
167
|
+
assert result == (4,)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def test_executemany(config):
|
|
171
|
+
"""Test using executemany."""
|
|
172
|
+
updates = [
|
|
173
|
+
('Alicia', 1),
|
|
174
|
+
('Bobby', 2),
|
|
175
|
+
]
|
|
176
|
+
with Db.from_config(config, autocommit=True) as db:
|
|
177
|
+
db.executemany(Sql.raw("UPDATE users SET name = ? WHERE id = ?"), updates)
|
|
178
|
+
results = db.fetchall(Sql.raw("SELECT name FROM users"))
|
|
179
|
+
assert "Alicia" in str(results)
|
|
180
|
+
assert "Bobby" in str(results)
|