sqliter-py 0.2.0__tar.gz → 0.3.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.

Potentially problematic release.


This version of sqliter-py might be problematic. Click here for more details.

@@ -217,3 +217,5 @@ pyrightconfig.json
217
217
  .vscode
218
218
  .changelog_generator.toml
219
219
  repopack-output.xml
220
+ .envrc
221
+ demo-db
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+ Copyright (c) 2024 Grant Ramsay
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ of this software and associated documentation files (the "Software"), to deal
6
+ in the Software without restriction, including without limitation the rights
7
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the Software is
9
+ furnished to do so, subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
20
+ OR OTHER DEALINGS IN THE SOFTWARE.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: sqliter-py
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Interact with SQLite databases using Python and Pydantic
5
5
  Project-URL: Pull Requests, https://github.com/seapagan/sqliter-py/pulls
6
6
  Project-URL: Bug Tracker, https://github.com/seapagan/sqliter-py/issues
@@ -8,6 +8,7 @@ Project-URL: Changelog, https://github.com/seapagan/sqliter-py/blob/main/CHANGEL
8
8
  Project-URL: Repository, https://github.com/seapagan/sqliter-py
9
9
  Author-email: Grant Ramsay <grant@gnramsay.com>
10
10
  License-Expression: MIT
11
+ License-File: LICENSE.txt
11
12
  Classifier: Development Status :: 4 - Beta
12
13
  Classifier: Intended Audience :: Developers
13
14
  Classifier: License :: OSI Approved :: MIT License
@@ -21,6 +22,8 @@ Classifier: Topic :: Software Development
21
22
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
23
  Requires-Python: >=3.9
23
24
  Requires-Dist: pydantic>=2.9.0
25
+ Provides-Extra: extras
26
+ Requires-Dist: inflect==7.0.0; extra == 'extras'
24
27
  Description-Content-Type: text/markdown
25
28
 
26
29
  # SQLiter <!-- omit in toc -->
@@ -44,19 +47,28 @@ time).
44
47
  The ideal use case is more for Python CLI tools that need to store data in a
45
48
  database-like format without needing to learn SQL or use a full ORM.
46
49
 
47
- > [!NOTE]
50
+ > [!IMPORTANT]
48
51
  > This project is still in the early stages of development and is lacking some
49
52
  > planned functionality. Please use with caution.
50
53
  >
54
+ > Also, structures like `list`, `dict`, `set` etc are not supported **at this
55
+ > time** as field types, since SQLite does not have a native column type for
56
+ > these. I will look at implementing these in the future, probably by
57
+ > serializing them to JSON or pickling them and storing in a text field. For
58
+ > now, you can actually do this manually when creating your Model (use `TEXT` or
59
+ > `BLOB` fields), then serialize before saving after and retrieving data.
60
+ >
51
61
  > See the [TODO](TODO.md) for planned features and improvements.
52
62
 
53
63
  - [Features](#features)
54
64
  - [Installation](#installation)
65
+ - [Optional Dependencies](#optional-dependencies)
55
66
  - [Quick Start](#quick-start)
56
67
  - [Detailed Usage](#detailed-usage)
57
68
  - [Defining Models](#defining-models)
58
69
  - [Database Operations](#database-operations)
59
70
  - [Creating a Connection](#creating-a-connection)
71
+ - [Using an In-Memory Database](#using-an-in-memory-database)
60
72
  - [Creating Tables](#creating-tables)
61
73
  - [Inserting Records](#inserting-records)
62
74
  - [Querying Records](#querying-records)
@@ -65,6 +77,11 @@ database-like format without needing to learn SQL or use a full ORM.
65
77
  - [Commit your changes](#commit-your-changes)
66
78
  - [Close the Connection](#close-the-connection)
67
79
  - [Transactions](#transactions)
80
+ - [Ordering](#ordering)
81
+ - [Field Control](#field-control)
82
+ - [Selecting Specific Fields](#selecting-specific-fields)
83
+ - [Excluding Specific Fields](#excluding-specific-fields)
84
+ - [Returning exactly one explicit field only](#returning-exactly-one-explicit-field-only)
68
85
  - [Filter Options](#filter-options)
69
86
  - [Basic Filters](#basic-filters)
70
87
  - [Null Checks](#null-checks)
@@ -73,6 +90,7 @@ database-like format without needing to learn SQL or use a full ORM.
73
90
  - [String Operations (Case-Sensitive)](#string-operations-case-sensitive)
74
91
  - [String Operations (Case-Insensitive)](#string-operations-case-insensitive)
75
92
  - [Contributing](#contributing)
93
+ - [Exceptions](#exceptions)
76
94
  - [License](#license)
77
95
  - [Acknowledgements](#acknowledgements)
78
96
 
@@ -83,29 +101,60 @@ database-like format without needing to learn SQL or use a full ORM.
83
101
  - Basic query building with filtering, ordering, and pagination
84
102
  - Transaction support
85
103
  - Custom exceptions for better error handling
104
+ - Full type hinting and type checking
105
+ - No external dependencies other than Pydantic
106
+ - Full test coverage
86
107
 
87
108
  ## Installation
88
109
 
89
110
  You can install SQLiter using whichever method you prefer or is compatible with
90
111
  your project setup.
91
112
 
113
+ With `uv` which is rapidly becoming my favorite tool for managing projects and
114
+ virtual environments (`uv` is used for developing this project and in the CI):
115
+
116
+ ```bash
117
+ uv add sqliter-py
118
+ ```
119
+
92
120
  With `pip`:
93
121
 
94
122
  ```bash
95
123
  pip install sqliter-py
96
124
  ```
97
125
 
98
- Or `Poetry`:
126
+ Or with `Poetry`:
99
127
 
100
128
  ```bash
101
129
  poetry add sqliter-py
102
130
  ```
103
131
 
104
- Or `uv` which is rapidly becoming my favorite tool for managing projects and
105
- virtual environments (`uv` is used for developing this project and in the CI):
132
+ ### Optional Dependencies
133
+
134
+ Currently by default, the only external dependency is Pydantic. However, there
135
+ are some optional dependencies that can be installed to enable additional
136
+ features:
137
+
138
+ - `inflect`: For pluralizing table names (if not specified). This just offers a
139
+ more-advanced pluralization than the default method used. In most cases you
140
+ will not need this.
141
+
142
+ These can be installed using `uv`:
106
143
 
107
144
  ```bash
108
- uv add sqliter-py
145
+ uv add 'sqliter-py[extras]'
146
+ ```
147
+
148
+ Or with `pip`:
149
+
150
+ ```bash
151
+ pip install 'sqliter-py[extras]'
152
+ ```
153
+
154
+ Or with `Poetry`:
155
+
156
+ ```bash
157
+ poetry add 'sqliter-py[extras]'
109
158
  ```
110
159
 
111
160
  ## Quick Start
@@ -165,9 +214,28 @@ class User(BaseDBModel):
165
214
  class Meta:
166
215
  table_name = "users"
167
216
  primary_key = "name" # Default is "id"
168
- create_id = False # Set to True to auto-create an ID field
217
+ create_pk = False # disable auto-creating an incrementing primary key - default is True
169
218
  ```
170
219
 
220
+ For a standard database with an auto-incrementing integer 'id' primary key, you
221
+ do not need to specify the `primary_key` or `create_pk` fields. If you want to
222
+ specify a different primary key field name, you can do so using the
223
+ `primary_key` field in the `Meta` class.
224
+
225
+ If `table_name` is not specified, the table name will be the same as the model
226
+ name, converted to 'snake_case' and pluralized (e.g., `User` -> `users`). Also,
227
+ any 'Model' suffix will be removed (e.g., `UserModel` -> `users`). To override
228
+ this behavior, you can specify the `table_name` in the `Meta` class manually as
229
+ above.
230
+
231
+ > [!NOTE]
232
+ >
233
+ > The pluralization is pretty basic by default, and just consists of adding an
234
+ > 's' if not already there. This will fail on words like 'person' or 'child'. If
235
+ > you need more advanced pluralization, you can install the `extras` package as
236
+ > mentioned above. Of course, you can always specify the `table_name` manually
237
+ > in this case!
238
+
171
239
  ### Database Operations
172
240
 
173
241
  #### Creating a Connection
@@ -190,6 +258,36 @@ It is then up to you to manually commit changes using the `commit()` method.
190
258
  This can be useful when you want to perform multiple operations in a single
191
259
  transaction without the overhead of committing after each operation.
192
260
 
261
+ #### Using an In-Memory Database
262
+
263
+ If you want to use an in-memory database, you can set `memory=True` when
264
+ creating the database connection:
265
+
266
+ ```python
267
+ db = SqliterDB(memory=True)
268
+ ```
269
+
270
+ This will create an in-memory database that is not persisted to disk. If you
271
+ also specify a database name, it will be ignored.
272
+
273
+ ```python
274
+ db = SqliterDB("ignored.db", memory=True)
275
+ ```
276
+
277
+ The `ignored.db` file will not be created, and the database will be in-memory.
278
+ If you do not specify a database name, and do NOT set `memory=True`, an
279
+ exception will be raised.
280
+
281
+ > [!NOTE]
282
+ >
283
+ > You can also use `":memory:"` as the database name (same as normal with
284
+ > Sqlite) to create an in-memory database, this is just a cleaner and more
285
+ > descriptive way to do it.
286
+ >
287
+ > ```python
288
+ > db = SqliterDB(":memory:")
289
+ > ```
290
+
193
291
  #### Creating Tables
194
292
 
195
293
  ```python
@@ -213,12 +311,17 @@ all_users = db.select(User).fetch_all()
213
311
  young_users = db.select(User).filter(age=25).fetch_all()
214
312
 
215
313
  # Order users
216
- ordered_users = db.select(User).order("age", direction="DESC").fetch_all()
314
+ ordered_users = db.select(User).order("age", reverse=True).fetch_all()
217
315
 
218
316
  # Limit and offset
219
317
  paginated_users = db.select(User).limit(10).offset(20).fetch_all()
220
318
  ```
221
319
 
320
+ > [!IMPORTANT]
321
+ >
322
+ > The `select()` MUST come first, before any filtering, ordering, or pagination
323
+ > etc. This is the starting point for building your query.
324
+
222
325
  See below for more advanced filtering options.
223
326
 
224
327
  #### Updating Records
@@ -278,9 +381,83 @@ with db:
278
381
  > at the end (unless an exception occurs), regardless of the `auto_commit`
279
382
  > setting.
280
383
  >
281
- > the 'close()' method will also be called when the context manager exits, so you
384
+ > the `close()` method will also be called when the context manager exits, so you
282
385
  > do not need to call it manually.
283
386
 
387
+ ### Ordering
388
+
389
+ For now we only support ordering by the single field. You can specify the
390
+ field to order by and whether to reverse the order:
391
+
392
+ ```python
393
+ results = db.select(User).order("age", reverse=True).fetch_all()
394
+ ```
395
+
396
+ This will order the results by the `age` field in descending order.
397
+
398
+ > [!WARNING]
399
+ >
400
+ > Previously ordering was done using the `direction` parameter with `asc` or
401
+ > `desc`, but this has been deprecated in favor of using the `reverse`
402
+ > parameter. The `direction` parameter still works, but will raise a
403
+ > `DeprecationWarning` and will be removed in a future release.
404
+
405
+ ### Field Control
406
+
407
+ #### Selecting Specific Fields
408
+
409
+ By default, all commands query and return all fields in the table. If you want
410
+ to select only specific fields, you can pass them using the `fields()`
411
+ method:
412
+
413
+ ```python
414
+ results = db.select(User).fields(["name", "age"]).fetch_all()
415
+ ```
416
+
417
+ This will return only the `name` and `age` fields for each record.
418
+
419
+ You can also pass this as a parameter to the `select()` method:
420
+
421
+ ```python
422
+ results = db.select(User, fields=["name", "age"]).fetch_all()
423
+ ```
424
+
425
+ Note that using the `fields()` method will override any fields specified in the
426
+ 'select()' method.
427
+
428
+ #### Excluding Specific Fields
429
+
430
+ If you want to exclude specific fields from the results, you can use the
431
+ `exclude()` method:
432
+
433
+ ```python
434
+ results = db.select(User).exclude(["email"]).fetch_all()
435
+ ```
436
+
437
+ This will return all fields except the `email` field.
438
+
439
+ You can also pass this as a parameter to the `select()` method:
440
+
441
+ ```python
442
+ results = db.select(User, exclude=["email"]).fetch_all()
443
+ ```
444
+
445
+ #### Returning exactly one explicit field only
446
+
447
+ If you only want to return a single field from the results, you can use the
448
+ `only()` method:
449
+
450
+ ```python
451
+ result = db.select(User).only("name").fetch_first()
452
+ ```
453
+
454
+ This will return only the `name` field for the first record.
455
+
456
+ This is exactly the same as using the `fields()` method with a single field, but
457
+ very specific and obvious. **There is NO equivalent argument to this in the
458
+ `select()` method**. An exception **WILL** be raised if you try to use this method
459
+ with more than one field.
460
+
284
461
  ### Filter Options
285
462
 
286
463
  The `filter()` method in SQLiter supports various filter options to query records.
@@ -339,10 +516,83 @@ The `filter()` method in SQLiter supports various filter options to query record
339
516
 
340
517
  Contributions are welcome! Please feel free to submit a Pull Request.
341
518
 
519
+ See the [CONTRIBUTING](CONTRIBUTING.md) guide for more information.
520
+
521
+ Please note that this project is released with a Contributor Code of Conduct,
522
+ which you can read in the [CODE_OF_CONDUCT](CODE_OF_CONDUCT.md) file.
523
+
524
+ ## Exceptions
525
+
526
+ SQLiter includes several custom exceptions to handle specific errors that may occur during database operations. These exceptions inherit from a common base class, `SqliterError`, to ensure consistency across error messages and behavior.
527
+
528
+ - **`SqliterError`**:
529
+ - The base class for all exceptions in SQLiter. It captures the exception context and chains any previous exceptions.
530
+ - **Message**: "An error occurred in the SQLiter package."
531
+
532
+ - **`DatabaseConnectionError`**:
533
+ - Raised when the SQLite database connection fails.
534
+ - **Message**: "Failed to connect to the database: '{}'."
535
+
536
+ - **`InvalidOffsetError`**:
537
+ - Raised when an invalid offset value (0 or negative) is used in queries.
538
+ - **Message**: "Invalid offset value: '{}'. Offset must be a positive integer."
539
+
540
+ - **`InvalidOrderError`**:
541
+ - Raised when an invalid order value is used in queries, such as a non-existent field or an incorrect sorting direction.
542
+ - **Message**: "Invalid order value - {}"
543
+
544
+ - **`TableCreationError`**:
545
+ - Raised when a table cannot be created in the database.
546
+ - **Message**: "Failed to create the table: '{}'."
547
+
548
+ - **`RecordInsertionError`**:
549
+ - Raised when an error occurs during record insertion.
550
+ - **Message**: "Failed to insert record into table: '{}'."
551
+
552
+ - **`RecordUpdateError`**:
553
+ - Raised when an error occurs during record update.
554
+ - **Message**: "Failed to update record in table: '{}'."
555
+
556
+ - **`RecordNotFoundError`**:
557
+ - Raised when a record with the specified primary key is not found.
558
+ - **Message**: "Failed to find a record for key '{}'".
559
+
560
+ - **`RecordFetchError`**:
561
+ - Raised when an error occurs while fetching records from the database.
562
+ - **Message**: "Failed to fetch record from table: '{}'."
563
+
564
+ - **`RecordDeletionError`**:
565
+ - Raised when an error occurs during record deletion.
566
+ - **Message**: "Failed to delete record from table: '{}'."
567
+
568
+ - **`InvalidFilterError`**:
569
+ - Raised when an invalid filter field is used in a query.
570
+ - **Message**: "Failed to apply filter: invalid field '{}'".
571
+
342
572
  ## License
343
573
 
344
574
  This project is licensed under the MIT License.
345
575
 
576
+ Copyright (c) 2024 Grant Ramsay
577
+
578
+ Permission is hereby granted, free of charge, to any person obtaining a copy
579
+ of this software and associated documentation files (the "Software"), to deal
580
+ in the Software without restriction, including without limitation the rights
581
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
582
+ copies of the Software, and to permit persons to whom the Software is
583
+ furnished to do so, subject to the following conditions:
584
+
585
+ The above copyright notice and this permission notice shall be included in all
586
+ copies or substantial portions of the Software.
587
+
588
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
589
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
590
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
591
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
592
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
593
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
594
+ OR OTHER DEALINGS IN THE SOFTWARE.
595
+
346
596
  ## Acknowledgements
347
597
 
348
598
  SQLiter was initially developed as an experiment to see how helpful ChatGPT and