dataclassdb 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.
dataclassdb/utils.py ADDED
@@ -0,0 +1,74 @@
1
+ import logging
2
+ import sqlite3
3
+ from dataclasses import dataclass
4
+ from enum import Enum, StrEnum
5
+ from typing import Any, ClassVar
6
+
7
+ import dacite
8
+
9
+ logger = logging.getLogger()
10
+
11
+
12
+ class UpperStrEnum(StrEnum):
13
+ @staticmethod
14
+ def _generate_next_value_(
15
+ name: str, start: int, count: int, last_values: list[Any]
16
+ ) -> Any:
17
+ return name.upper().replace("_", " ")
18
+
19
+
20
+ def table_exists(connection: sqlite3.Connection, table_name):
21
+ cursor = connection.cursor()
22
+ cursor.execute(
23
+ "SELECT name FROM sqlite_schema WHERE type='table' AND name=?",
24
+ (table_name,),
25
+ )
26
+ result = cursor.fetchone()
27
+ return result is not None
28
+
29
+
30
+ def dict_factory(cursor, row):
31
+ fields = [column[0] for column in cursor.description]
32
+ row_dict = {}
33
+ for key, value in zip(fields, row):
34
+ row_dict[key] = value
35
+ return row_dict
36
+
37
+
38
+ def is_enum_class(cls):
39
+ try:
40
+ return issubclass(cls, Enum)
41
+ except Exception:
42
+ return False
43
+
44
+
45
+ def is_strenum(cls):
46
+ try:
47
+ return issubclass(cls, Enum) and issubclass(cls, str)
48
+ except Exception:
49
+ return False
50
+
51
+
52
+ @dataclass
53
+ class PragmaTableInfo:
54
+ cid: int
55
+ name: str | None
56
+ type: str | None
57
+ notnull: bool | None
58
+ dflt_value: Any
59
+ pk: bool | None
60
+
61
+ _config: ClassVar[dacite.Config] = dacite.Config(
62
+ type_hooks={
63
+ bool: lambda x: bool(x),
64
+ }
65
+ )
66
+
67
+ @classmethod
68
+ def from_dict(cls, data) -> "PragmaTableInfo":
69
+ return dacite.from_dict(cls, data, cls._config)
70
+
71
+ @classmethod
72
+ def from_list(cls, data) -> list["PragmaTableInfo"]:
73
+ cols = [cls.from_dict(col) for col in data]
74
+ return cols
@@ -0,0 +1,237 @@
1
+ Metadata-Version: 2.4
2
+ Name: dataclassdb
3
+ Version: 0.1.0
4
+ Summary: This module provides a lightweight sqlite3 ORM using normal dataclass.
5
+ Author-email: "@stuarts-art" <stuartsartemail@gmail.com>
6
+ Maintainer-email: "@stuarts-art" <stuartsartemail@gmail.com>
7
+ License-Expression: MIT
8
+ Project-URL: Repository, https://github.com/stuarts-art/DataclassDb
9
+ Keywords: dataclasses,sqlite3,orm
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Topic :: Database :: Front-Ends
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Requires-Python: >=3.11
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: dacite>=1.9.2
22
+ Dynamic: license-file
23
+
24
+ # dataclassdb
25
+
26
+ This module provides a lightweight sqlite3 ORM for dataclasses.
27
+
28
+ ## Installation
29
+
30
+ To install dataclassdb, simply use 'pip:
31
+
32
+ ```zsh
33
+ pip install dataclassdb
34
+ ```
35
+
36
+ ## Requirements
37
+
38
+ Minimum Python version supported by `dataclassdb` is 3.11. The only dependency is [dacite](https://github.com/konradhalas/dacite).
39
+
40
+ ## Quick Start
41
+
42
+ ```python
43
+ from dataclassdb import DataclassDb
44
+ from types import Annotated
45
+ from dataclasses import dataclass, Annotated
46
+
47
+ @dataclass
48
+ class Foo:
49
+ id: Annotated[int, "PRIMARY KEY"]
50
+ bar: str
51
+ baz: list[int]
52
+
53
+ with DataclassDb(Foo, "example.db") as db:
54
+ # Insert and get
55
+ db.insert(Foo(0, "x", [1, 2, 3]))
56
+ foo = db.get(0)
57
+
58
+ # Arbitrary SQL
59
+ db.SELECT("bar").FROM(FOO).WHERE("id").eq("?")
60
+ selection = db.execute_one(0) # Replaces ? with 0
61
+ ```
62
+
63
+ ## Overview
64
+
65
+ - Uses `@dataclass` classes to generate and interact with database files using `sqlite3`. No "Model" super class required.
66
+ - SQL table columns are inferred by the dataclass field annotation.
67
+ - Codecs(Encoder/Decoder) translate Python to SQL and back.
68
+ - Build in [QueryBuilder](src/dataclassdb/builders/query_builder.py) with every SQL statement and function for easy query writing
69
+ - Built in [DbEngine](src/dataclassdb/db_engine.py) context manager for managing the db connection, creating tables, and executing queries.
70
+
71
+ ## Deeper Dive
72
+
73
+ - Each `@dataclass` fields' SQL type is inferred by the python type or by override. By default, undefined mapping are set to "TEXT".
74
+ - A Codec (Encoder/Decoder) is used to translate between python and SQL. The following are supported:
75
+ - **Basic Types**: `int`, `str`, `float`, `bool`
76
+ - **Enums**: `Enum`, `StrEnum`
77
+ - **Dates**: `datetime -> INTEGER (unix time)`, `datetime -> TEXT (ISO 8601)`
78
+ - **Json**: `list`, `dict`, `@dataclass` (If all elements are json encodable)
79
+ - **Pickle (Bytes)**: Any `python` object. Notably `set`s are not json encodable. Pickle is not safe and should be used with caution**.
80
+ - Any user defined [Codec](src/dataclassdb/dataclass_types.py#8)
81
+ - [Constraints](https://www.sqlite.org/syntax/column-constraint.html)
82
+ such as `PRIMARY KEY` or `UNIQUE` can be added as `typing.Annotated` metadata without affecting the base type.
83
+ - Dataclass field defaults are encoded
84
+ - "NOT NULL" field status is inferred by the
85
+
86
+ Column type is inferred by the python type and SQL type.
87
+
88
+ - The column type is inferred by the python type but can be overridden as the first annotation.
89
+ - This package does not attempt to abstract away SQL behavior. It's simply a lightweight wrapper around sqlite3.
90
+
91
+ ## Motivation
92
+
93
+ ### 1. Easier to write than plaintext
94
+
95
+ - All sqlite [keywords](src/dataclassdb/sql_statement_builder.py) and [functions](src/dataclassdb/sql_function_builder.py) are supported
96
+ - Queries can be written written without filler words.
97
+ - Lists and args are handled how you'd expect them to be handled.
98
+
99
+ ### 2. Easier to write than [SqlAlchemy](https://docs.sqlalchemy.org/), [SqlModel](https://sqlmodel.tiangolo.com/features/#editor-support), and other more complex abstractions
100
+
101
+ - No required imports [QueryBuilder](src/dataclassdb/query_builder.py)
102
+ - Minimal package specific syntax or abstractions to learn
103
+
104
+ ### 3. Abstracts away Non-SQL, `sqlite3`, actions
105
+
106
+ - Creating connection
107
+ - Executing the query
108
+ - Returning the result as a list or dictionary
109
+
110
+ ## Features
111
+
112
+ - [DataclassDb](#dataclassdb): Maps dataclass class into a sqlite3 table.
113
+ - [QueryBuilder](#query-builder): Specialized StringBuilder with methods for each sqlite3 [keywords](src/dataclassdb/sql_statement_builder.py) and [functions](src/dataclassdb/sql_function_builder.py). Note that DataclassDb inherits from QueryBuilder.
114
+ - [DbEngine](src/dataclassdb/db_engine.py):
115
+ - [Codec](src/dataclassdb/dataclass_types.py#5): Protocol
116
+ - [CustomCodec](src/dataclassdb/dataclass_types.py#12)
117
+
118
+ ## DataclassDb
119
+
120
+ ### Column Definition
121
+
122
+ ```python
123
+ col_name: Annotated(Type, ? [SQL Type], *[Constraints], [Codec])
124
+ ```
125
+
126
+ - Type: The python type for the dataclass field
127
+ - SQL Type: Override the default mapped SQL type (see next section)
128
+ - Constraints: SQL constraints as text
129
+ - Codec: Overrides the default codec. Any object that is a [Codec](src/dataclassdb/dataclass_types.py#5) (has an encode and decode method)
130
+
131
+ Examples:
132
+
133
+ | Python Field | Sqlite Col Definition |
134
+ | --- | --- |
135
+ | `id: Annotated[int, "PRIMARY KEY"]` | `id INTEGER PRIMARY KEY NOT NULL` |
136
+ | `username: Annotated[str, "UNIQUE"]` | `username TEXT UNIQUE NOT NULL` |
137
+ | `email: str = ""` | `email TEXT NOT NULL DEFAULT ""` |
138
+
139
+ ### Python type to SQL type resolution
140
+
141
+ Because sqlite has a limited amount of supported types: (INTEGER, TEXT, REAL, NUMERICAL, BLOB), we must map between python types and SQL types.
142
+
143
+ The "easiest" way to do this is by converting our python object into binary using pickle and storing it as a BLOB. However, there are a few issues with this approach.
144
+
145
+ 1. Pickle is unsafe (bad actors can run arbitrary code on decode.)
146
+ 2. This data cannot be read without decoding.
147
+ 3. This data cannot be used in queries without decoding.
148
+
149
+ This package approaches this issue by using Codecs (Encoder/Decoder) to handle the python -> sqlite -> python conversions.
150
+ If no SQL type is declared in the Annotated column definition, first checks the below mapping.
151
+
152
+ If no mapping is found, the column is assumed to be json encodable. This setting can be overridden by either providing a custom Codec or setting the type to "BLOB".
153
+
154
+ | SQL Type | python type | Codec |
155
+ | --- | --- | --- |
156
+ | TEXT | datetime | DatetimeTextCodec |
157
+ | TEXT | str | IdentityCodec |
158
+ | TEXT | default | JsonCodec |
159
+ | INTEGER | datetime | DatetimeIntCodec |
160
+ | INTEGER | bool | BoolCodec |
161
+ | INTEGER | int | IdentityCodec |
162
+ | REAL | float | IdentityCodec |
163
+ | BLOB | @dataclass | DataclassPickleCodec |
164
+ | BLOB | default | PickleCodec |
165
+
166
+ ## Query Builder
167
+
168
+ ```python
169
+ qb = QueryBuilder() # str(qb)
170
+ qb.SELECT # = SELECT
171
+ qb("a", "b").Group_concat("c") # = SELECT a b group_concat(c)
172
+ ```
173
+
174
+ - All SQL statement keywords, such as `SELECT`, `FROM`, etc. are available as **chainable** properties of Query builders `query.SELECT` or as standalone variables `db.SELECT`. See [StatementBuilder](src/dataclassdb/statement_builder.py) or [SQL enum](src/dataclassdb/constants.py#L4)
175
+ - Similarly, all SQL functions, such as `count`, `sum`, `group_concat` are available as **chainable** functions `query.SELECT.Count("type")` or as standalone functions `db.Count("type")`. See [QueryBuilder](src/dataclassdb/query_builder.py) or [SQL_FUNC enum](src/dataclassdb/constants.py#L161)
176
+ - QueryBuilders `__call__` adds provided arguments to the string as a list, with optional quote and parenthesis options.
177
+
178
+ QueryBuilder is a fancy SQL flavored String Builder which the following goals:
179
+
180
+ ### Convention breaking weirdness
181
+
182
+ SQL [statements](src/dataclassdb/sql_statement_builder.py) leverage a totally legal but questionable hack. Each statement is a [`@property`](https://docs.python.org/3/library/functions.html#property) that returns self. The
183
+ [`__call__`](https://docs.python.org/3/reference/datamodel.html#emulating-callable-objects) handles the case where the object is called directly. Note that SQL functions are **NOT** properties.
184
+
185
+ So to for the Query `qb.SELECT("a","b")`
186
+
187
+ 1. `qb.SELECT`: Calls the property `SELECT` which adds `"SELECT"` to the string. It returns self.
188
+ 2. `qb.SELECT("a", "b")` calls `__call__` function instead of `SELECT` function.
189
+
190
+ ### Comparing QueryBuilder, plain sqlite3 and sqlAlchemy
191
+
192
+ #### QueryBuilder
193
+
194
+ ```python
195
+ query = QueryBuilder("example.db").
196
+ query.SELECT("name").FROM("sqlite_master").WHERE("name='spam'")
197
+ result = query.execute()
198
+ ```
199
+
200
+ #### Sqlite3
201
+
202
+ ```python
203
+ #sqlite3
204
+ con = sqlite3.connect("example.db")
205
+ cur = con.cursor()
206
+ res = cur.execute("SELECT name FROM sqlite_master WHERE name='spam'")
207
+ ```
208
+
209
+ #### sqlAlchemy
210
+
211
+ ```python
212
+ engine = create_engine("sqlite:///example.db")
213
+ with engine.connect() as conn:
214
+ query = text("SELECT name FROM sqlite_master WHERE name='spam'")
215
+ res = conn.execute(query)
216
+ ```
217
+
218
+ ### Bonus functions
219
+
220
+ - `placeholders(n)` adds string "(? ... n)"
221
+ - `show()` prints the query at its current state
222
+ - `br` newline
223
+ - `lpar` "\("
224
+ - `rpar` "\)"
225
+ - `rpar` "\)"
226
+ - `comma` ","
227
+ - `execute(*args)`: Executes the command with the provided args replacing the placeholders.
228
+
229
+ ## Created By
230
+
231
+ Stuart (@stuarts_art)
232
+
233
+ - Washed dev who now makes furry art
234
+ - I branched this out of [ArtRefSync](https://github.com/stuarts-art/ArtRefSync), a pure python desktop ui to sync reference art from SFW and NSFW image boards.
235
+ - It uses client provided api keys to ethically get data while respecting usage rules
236
+ - User defined black list to avoid the scourge of AI art
237
+ - Is not using excessive ram to spy on you (plus memory is expensive)
@@ -0,0 +1,19 @@
1
+ dataclassdb/__init__.py,sha256=Kdd09r2eCtCRBytfVmBhaXHu754HielzU6SxxK8S3go,1178
2
+ dataclassdb/constants.py,sha256=OFUuZk-jTzzuxwF7LnEL9ukhT43euwC89PuOpkRsZls,8168
3
+ dataclassdb/dataclass_db.py,sha256=pImI4NRqwjEl1SRpJ0v5V7qQ0_ehQcX40CH6ry5MGDg,10306
4
+ dataclassdb/dataclass_field_codec.py,sha256=nLpDeDEE80WlH8sicKNjinECx9E255OSgmhLPqpZBI0,6007
5
+ dataclassdb/dataclass_sqlite_field.py,sha256=ZajjSQKVqyRZwTGMhXlfMT8oyXKQOHlcZC1lqTnW-Dg,6329
6
+ dataclassdb/dataclass_sqlite_table.py,sha256=YP0G2uFUQU-EETtdgocIGaISF12h1BzYCyTfmF6MFFY,4832
7
+ dataclassdb/dataclass_types.py,sha256=6HS_GabByR84PnWDQK2HDkWMd3WqB5Kc27v_gNjxqVk,541
8
+ dataclassdb/db_engine.py,sha256=RQUzx5YiwDogbRzIc6ijlxRN08XkcKWKc-E6tKIB728,4162
9
+ dataclassdb/utils.py,sha256=q4AKAzqIiKv9lbPMx3gjmxFmAAdvDEeglY6FVa2OWvw,1666
10
+ dataclassdb/builders/function_builder.py,sha256=c3n9arh4AVto5sj_9J3fNiQfTndROBHR5oYyWhqSpS4,13840
11
+ dataclassdb/builders/list_utils.py,sha256=6NZFg-p5om3w_kQ56b3PsZ--ZQRL_7mEXIUtoLvpaNU,1136
12
+ dataclassdb/builders/query_builder.py,sha256=-vWzizzA-EcPFx8C0FAWbNlNmrXbhd1ZwEP1wdqoLTo,4712
13
+ dataclassdb/builders/statement_builder.py,sha256=w8KGg168wQo-erfWC7nx9N_MZonP2mHdwJXg_ZPfQzs,12908
14
+ dataclassdb/builders/string_builder.py,sha256=6isyBEI-LiluAEuoKWjbxE8r1kLrBcdYyWLJ__fPJYQ,2592
15
+ dataclassdb-0.1.0.dist-info/licenses/LICENSE,sha256=NH7HgSWcsdHQ7MqNe_zp9c3PJY9pQj2uBC2hY4-FBFg,1071
16
+ dataclassdb-0.1.0.dist-info/METADATA,sha256=iVwwPGakOl78YCQ7KuyY1PJAwQLFKu9ZXQwhJ7G7dU4,9668
17
+ dataclassdb-0.1.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
18
+ dataclassdb-0.1.0.dist-info/top_level.txt,sha256=-H4LZZBr1TGqOxNhWA_CYcPEp-I9dbE71E9fPsE66OI,12
19
+ dataclassdb-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 stuartsartcode
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ dataclassdb