sqliter-py 0.2.0__py3-none-any.whl → 0.3.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.
sqliter/model/model.py CHANGED
@@ -2,30 +2,96 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import Optional
5
+ import re
6
+ from typing import Any, Optional, TypeVar, Union, get_args, get_origin
6
7
 
7
- from pydantic import BaseModel
8
+ from pydantic import BaseModel, ConfigDict
9
+
10
+ T = TypeVar("T", bound="BaseDBModel")
8
11
 
9
12
 
10
13
  class BaseDBModel(BaseModel):
11
14
  """Custom base model for database models."""
12
15
 
16
+ model_config = ConfigDict(
17
+ extra="ignore",
18
+ populate_by_name=True,
19
+ validate_assignment=False,
20
+ from_attributes=True,
21
+ )
22
+
13
23
  class Meta:
14
24
  """Configure the base model with default options."""
15
25
 
16
- create_id: bool = True # Whether to create an auto-increment ID
17
- primary_key: str = "id" # Default primary key field
26
+ create_pk: bool = (
27
+ True # Whether to create an auto-increment primary key
28
+ )
29
+ primary_key: str = "id" # Default primary key name
18
30
  table_name: Optional[str] = (
19
31
  None # Table name, defaults to class name if not set
20
32
  )
21
33
 
34
+ @classmethod
35
+ def model_validate_partial(cls: type[T], obj: dict[str, Any]) -> T:
36
+ """Validate a partial model object."""
37
+ converted_obj: dict[str, Any] = {}
38
+ for field_name, value in obj.items():
39
+ field = cls.model_fields[field_name]
40
+ field_type: Optional[type] = field.annotation
41
+ if (
42
+ field_type is None or value is None
43
+ ): # Direct check for None values here
44
+ converted_obj[field_name] = None
45
+ else:
46
+ origin = get_origin(field_type)
47
+ if origin is Union:
48
+ args = get_args(field_type)
49
+ for arg in args:
50
+ try:
51
+ # Try converting the value to the type
52
+ converted_obj[field_name] = arg(value)
53
+ break
54
+ except (ValueError, TypeError):
55
+ pass
56
+ else:
57
+ converted_obj[field_name] = value
58
+ else:
59
+ converted_obj[field_name] = field_type(value)
60
+
61
+ return cls.model_construct(**converted_obj)
62
+
22
63
  @classmethod
23
64
  def get_table_name(cls) -> str:
24
- """Get the table name from the Meta, or default to the classname."""
65
+ """Get the table name from the Meta, or generate one.
66
+
67
+ Returns:
68
+ str: The table name, either specified in the Meta class or
69
+ generated by converting the class name to pluralized snake_case
70
+ and removing any 'Model' suffix.
71
+ """
25
72
  table_name: str | None = getattr(cls.Meta, "table_name", None)
26
73
  if table_name is not None:
27
74
  return table_name
28
- return cls.__name__.lower() # Default to class name in lowercase
75
+
76
+ # Get class name and remove 'Model' suffix if present
77
+ class_name = cls.__name__.removesuffix("Model")
78
+
79
+ # Convert to snake_case
80
+ snake_case_name = re.sub(r"(?<!^)(?=[A-Z])", "_", class_name).lower()
81
+
82
+ # Pluralize the table name
83
+ try:
84
+ import inflect
85
+
86
+ p = inflect.engine()
87
+ return p.plural(snake_case_name)
88
+ except ImportError:
89
+ # Fallback to simple pluralization by adding 's'
90
+ return (
91
+ snake_case_name
92
+ if snake_case_name.endswith("s")
93
+ else snake_case_name + "s"
94
+ )
29
95
 
30
96
  @classmethod
31
97
  def get_primary_key(cls) -> str:
@@ -33,6 +99,6 @@ class BaseDBModel(BaseModel):
33
99
  return getattr(cls.Meta, "primary_key", "id")
34
100
 
35
101
  @classmethod
36
- def should_create_id(cls) -> bool:
102
+ def should_create_pk(cls) -> bool:
37
103
  """Check whether the model should create an auto-increment ID."""
38
- return getattr(cls.Meta, "create_id", True)
104
+ return getattr(cls.Meta, "create_pk", True)
sqliter/query/query.py CHANGED
@@ -3,7 +3,16 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import sqlite3
6
- from typing import TYPE_CHECKING, Any, Callable, Optional, Union
6
+ import warnings
7
+ from typing import (
8
+ TYPE_CHECKING,
9
+ Any,
10
+ Callable,
11
+ Literal,
12
+ Optional,
13
+ Union,
14
+ overload,
15
+ )
7
16
 
8
17
  from typing_extensions import LiteralString, Self
9
18
 
@@ -30,8 +39,22 @@ FilterValue = Union[
30
39
  class QueryBuilder:
31
40
  """Functions to build and execute queries for a given model."""
32
41
 
33
- def __init__(self, db: SqliterDB, model_class: type[BaseDBModel]) -> None:
34
- """Initialize the query builder with the database, model class, etc."""
42
+ def __init__(
43
+ self,
44
+ db: SqliterDB,
45
+ model_class: type[BaseDBModel],
46
+ fields: Optional[list[str]] = None,
47
+ ) -> None:
48
+ """Initialize the query builder.
49
+
50
+ Pass the database, model class, and optional fields.
51
+
52
+ Args:
53
+ db: The SqliterDB instance.
54
+ model_class: The model class to query.
55
+ fields: Optional list of field names to select. If None, all fields
56
+ are selected.
57
+ """
35
58
  self.db = db
36
59
  self.model_class = model_class
37
60
  self.table_name = model_class.get_table_name() # Use model_class method
@@ -39,6 +62,22 @@ class QueryBuilder:
39
62
  self._limit: Optional[int] = None
40
63
  self._offset: Optional[int] = None
41
64
  self._order_by: Optional[str] = None
65
+ self._fields: Optional[list[str]] = fields
66
+
67
+ if self._fields:
68
+ self._validate_fields()
69
+
70
+ def _validate_fields(self) -> None:
71
+ """Validate that the specified fields exist in the model."""
72
+ if self._fields is None:
73
+ return
74
+ valid_fields = set(self.model_class.model_fields.keys())
75
+ invalid_fields = set(self._fields) - valid_fields
76
+ if invalid_fields:
77
+ err_message = (
78
+ f"Invalid fields specified: {', '.join(invalid_fields)}"
79
+ )
80
+ raise ValueError(err_message)
42
81
 
43
82
  def filter(self, **conditions: str | float | None) -> QueryBuilder:
44
83
  """Add filter conditions to the query."""
@@ -53,6 +92,53 @@ class QueryBuilder:
53
92
 
54
93
  return self
55
94
 
95
+ def fields(self, fields: Optional[list[str]] = None) -> QueryBuilder:
96
+ """Select specific fields to return in the query."""
97
+ if fields:
98
+ self._fields = fields
99
+ self._validate_fields()
100
+ return self
101
+
102
+ def exclude(self, fields: Optional[list[str]] = None) -> QueryBuilder:
103
+ """Exclude specific fields from the query output."""
104
+ if fields:
105
+ all_fields = set(self.model_class.model_fields.keys())
106
+
107
+ # Check for invalid fields before subtraction
108
+ invalid_fields = set(fields) - all_fields
109
+ if invalid_fields:
110
+ err = (
111
+ "Invalid fields specified for exclusion: "
112
+ f"{', '.join(invalid_fields)}"
113
+ )
114
+ raise ValueError(err)
115
+
116
+ # Subtract the fields specified for exclusion
117
+ self._fields = list(all_fields - set(fields))
118
+
119
+ # Explicit check: raise an error if no fields remain
120
+ if not self._fields:
121
+ err = "Exclusion results in no fields being selected."
122
+ raise ValueError(err)
123
+
124
+ # Now validate the remaining fields to ensure they are all valid
125
+ self._validate_fields()
126
+
127
+ return self
128
+
129
+ def only(self, field: str) -> QueryBuilder:
130
+ """Return only the specified single field."""
131
+ all_fields = set(self.model_class.model_fields.keys())
132
+
133
+ # Validate that the field exists
134
+ if field not in all_fields:
135
+ err = f"Invalid field specified: {field}"
136
+ raise ValueError(err)
137
+
138
+ # Set self._fields to just the single field
139
+ self._fields = [field]
140
+ return self
141
+
56
142
  def _get_operator_handler(
57
143
  self, operator: str
58
144
  ) -> Callable[[str, Any, str], None]:
@@ -182,34 +268,61 @@ class QueryBuilder:
182
268
  self._limit = -1
183
269
  return self
184
270
 
185
- def order(self, order_by_field: str, direction: str = "ASC") -> Self:
186
- """Order the results by a specific field and optionally direction.
187
-
188
- Currently only supports ordering by a single field, though this will be
189
- expanded in the future. You can chain this method to order by multiple
190
- fields.
271
+ def order(
272
+ self,
273
+ order_by_field: str,
274
+ direction: Optional[str] = None,
275
+ *,
276
+ reverse: bool = False,
277
+ ) -> Self:
278
+ """Order the query results by the specified field.
191
279
 
192
- Parameters:
280
+ Args:
193
281
  order_by_field (str): The field to order by.
194
- direction (str, optional): The sorting direction, either 'ASC' or
195
- 'DESC'. Defaults to 'ASC'.
196
-
197
- Returns:
198
- Self: Returns the query object for chaining.
282
+ direction (Optional[str]): The ordering direction ('ASC' or 'DESC').
283
+ This is deprecated in favor of 'reverse'.
284
+ reverse (bool): Whether to reverse the order (True for descending,
285
+ False for ascending).
199
286
 
200
287
  Raises:
201
- InvalidOrderError: If the field or direction is invalid.
288
+ InvalidOrderError: If the field doesn't exist in the model fields
289
+ or if both 'direction' and 'reverse' are specified.
290
+
291
+ Returns:
292
+ QueryBuilder: The current query builder instance with updated
293
+ ordering.
202
294
  """
295
+ if direction:
296
+ warnings.warn(
297
+ "'direction' argument is deprecated and will be removed in a "
298
+ "future version. Use 'reverse' instead.",
299
+ DeprecationWarning,
300
+ stacklevel=2,
301
+ )
302
+
203
303
  if order_by_field not in self.model_class.model_fields:
204
304
  err = f"'{order_by_field}' does not exist in the model fields."
205
305
  raise InvalidOrderError(err)
206
-
207
- valid_directions = {"ASC", "DESC"}
208
- if direction.upper() not in valid_directions:
209
- err = f"'{direction}' is not a valid sorting direction."
306
+ # Raise an exception if both 'direction' and 'reverse' are specified
307
+ if direction and reverse:
308
+ err = (
309
+ "Cannot specify both 'direction' and 'reverse' as it "
310
+ "is ambiguous."
311
+ )
210
312
  raise InvalidOrderError(err)
211
313
 
212
- self._order_by = f'"{order_by_field}" {direction.upper()}'
314
+ # Determine the sorting direction
315
+ if reverse:
316
+ sort_order = "DESC"
317
+ elif direction:
318
+ sort_order = direction.upper()
319
+ if sort_order not in {"ASC", "DESC"}:
320
+ err = f"'{direction}' is not a valid sorting direction."
321
+ raise InvalidOrderError(err)
322
+ else:
323
+ sort_order = "ASC"
324
+
325
+ self._order_by = f'"{order_by_field}" {sort_order}'
213
326
  return self
214
327
 
215
328
  def _execute_query(
@@ -219,15 +332,20 @@ class QueryBuilder:
219
332
  count_only: bool = False,
220
333
  ) -> list[tuple[Any, ...]] | Optional[tuple[Any, ...]]:
221
334
  """Helper function to execute the query with filters."""
222
- fields = ", ".join(self.model_class.model_fields)
335
+ if count_only:
336
+ fields = "COUNT(*)"
337
+ elif self._fields:
338
+ fields = ", ".join(f'"{field}"' for field in self._fields)
339
+ else:
340
+ fields = ", ".join(
341
+ f'"{field}"' for field in self.model_class.model_fields
342
+ )
343
+
344
+ sql = f'SELECT {fields} FROM "{self.table_name}"' # noqa: S608 # nosec
223
345
 
224
346
  # Build the WHERE clause with special handling for None (NULL in SQL)
225
347
  values, where_clause = self._parse_filter()
226
348
 
227
- select_fields = fields if not count_only else "COUNT(*)"
228
-
229
- sql = f'SELECT {select_fields} FROM "{self.table_name}"' # noqa: S608 # nosec
230
-
231
349
  if self.filters:
232
350
  sql += f" WHERE {where_clause}"
233
351
 
@@ -269,61 +387,68 @@ class QueryBuilder:
269
387
  where_clause = " AND ".join(where_clauses)
270
388
  return values, where_clause
271
389
 
272
- def fetch_all(self) -> list[BaseDBModel]:
273
- """Fetch all results matching the filters."""
274
- results = self._execute_query()
275
-
276
- if not results:
277
- return []
278
-
279
- return [
280
- self.model_class(
281
- **{
282
- field: row[idx]
283
- for idx, field in enumerate(self.model_class.model_fields)
284
- }
390
+ def _convert_row_to_model(self, row: tuple[Any, ...]) -> BaseDBModel:
391
+ """Convert a result row tuple into a Pydantic model."""
392
+ if self._fields:
393
+ return self.model_class.model_validate_partial(
394
+ {field: row[idx] for idx, field in enumerate(self._fields)}
285
395
  )
286
- for row in results
287
- ]
288
-
289
- def fetch_one(self) -> BaseDBModel | None:
290
- """Fetch exactly one result."""
291
- result = self._execute_query(fetch_one=True)
292
- if not result:
293
- return None
294
396
  return self.model_class(
295
397
  **{
296
- field: result[idx]
398
+ field: row[idx]
297
399
  for idx, field in enumerate(self.model_class.model_fields)
298
400
  }
299
401
  )
300
402
 
301
- def fetch_first(self) -> BaseDBModel | None:
403
+ @overload
404
+ def _fetch_result(
405
+ self, *, fetch_one: Literal[True]
406
+ ) -> Optional[BaseDBModel]: ...
407
+
408
+ @overload
409
+ def _fetch_result(
410
+ self, *, fetch_one: Literal[False]
411
+ ) -> list[BaseDBModel]: ...
412
+
413
+ def _fetch_result(
414
+ self, *, fetch_one: bool = False
415
+ ) -> Union[list[BaseDBModel], Optional[BaseDBModel]]:
416
+ """Fetch one or all results and convert them to Pydantic models."""
417
+ result = self._execute_query(fetch_one=fetch_one)
418
+
419
+ if not result:
420
+ if fetch_one:
421
+ return None
422
+ return []
423
+
424
+ if fetch_one:
425
+ # Ensure we pass a tuple, not a list, to _convert_row_to_model
426
+ if isinstance(result, list):
427
+ result = result[
428
+ 0
429
+ ] # Get the first (and only) result if it's wrapped in a list.
430
+ return self._convert_row_to_model(result)
431
+
432
+ return [self._convert_row_to_model(row) for row in result]
433
+
434
+ def fetch_all(self) -> list[BaseDBModel]:
435
+ """Fetch all results matching the filters."""
436
+ return self._fetch_result(fetch_one=False)
437
+
438
+ def fetch_one(self) -> Optional[BaseDBModel]:
439
+ """Fetch exactly one result."""
440
+ return self._fetch_result(fetch_one=True)
441
+
442
+ def fetch_first(self) -> Optional[BaseDBModel]:
302
443
  """Fetch the first result of the query."""
303
444
  self._limit = 1
304
- result = self._execute_query()
305
- if not result:
306
- return None
307
- return self.model_class(
308
- **{
309
- field: result[0][idx]
310
- for idx, field in enumerate(self.model_class.model_fields)
311
- }
312
- )
445
+ return self._fetch_result(fetch_one=True)
313
446
 
314
- def fetch_last(self) -> BaseDBModel | None:
447
+ def fetch_last(self) -> Optional[BaseDBModel]:
315
448
  """Fetch the last result of the query (based on the insertion order)."""
316
449
  self._limit = 1
317
450
  self._order_by = "rowid DESC"
318
- result = self._execute_query()
319
- if not result:
320
- return None
321
- return self.model_class(
322
- **{
323
- field: result[0][idx]
324
- for idx, field in enumerate(self.model_class.model_fields)
325
- }
326
- )
451
+ return self._fetch_result(fetch_one=True)
327
452
 
328
453
  def count(self) -> int:
329
454
  """Return the count of records matching the filters."""
sqliter/sqliter.py CHANGED
@@ -27,9 +27,24 @@ if TYPE_CHECKING: # pragma: no cover
27
27
  class SqliterDB:
28
28
  """Class to manage SQLite database interactions."""
29
29
 
30
- def __init__(self, db_filename: str, *, auto_commit: bool = True) -> None:
30
+ def __init__(
31
+ self,
32
+ db_filename: Optional[str] = None,
33
+ *,
34
+ memory: bool = False,
35
+ auto_commit: bool = True,
36
+ ) -> None:
31
37
  """Initialize the class and options."""
32
- self.db_filename = db_filename
38
+ if memory:
39
+ self.db_filename = ":memory:"
40
+ elif db_filename:
41
+ self.db_filename = db_filename
42
+ else:
43
+ err = (
44
+ "Database name must be provided if not using an in-memory "
45
+ "database."
46
+ )
47
+ raise ValueError(err)
33
48
  self.auto_commit = auto_commit
34
49
  self.conn: Optional[sqlite3.Connection] = None
35
50
 
@@ -58,13 +73,13 @@ class SqliterDB:
58
73
  """Create a table based on the Pydantic model."""
59
74
  table_name = model_class.get_table_name()
60
75
  primary_key = model_class.get_primary_key()
61
- create_id = model_class.should_create_id()
76
+ create_pk = model_class.should_create_pk()
62
77
 
63
78
  fields = ", ".join(
64
79
  f"{field_name} TEXT" for field_name in model_class.model_fields
65
80
  )
66
81
 
67
- if create_id:
82
+ if create_pk:
68
83
  create_table_sql = f"""
69
84
  CREATE TABLE IF NOT EXISTS {table_name} (
70
85
  {primary_key} INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -97,16 +112,17 @@ class SqliterDB:
97
112
  model_class = type(model_instance)
98
113
  table_name = model_class.get_table_name()
99
114
 
100
- fields = ", ".join(model_class.model_fields)
101
- placeholders = ", ".join(["?"] * len(model_class.model_fields))
102
- values = tuple(
103
- getattr(model_instance, field) for field in model_class.model_fields
115
+ data = model_instance.model_dump()
116
+ fields = ", ".join(data.keys())
117
+ placeholders = ", ".join(
118
+ ["?" if value is not None else "NULL" for value in data.values()]
104
119
  )
120
+ values = tuple(value for value in data.values() if value is not None)
105
121
 
106
122
  insert_sql = f"""
107
123
  INSERT INTO {table_name} ({fields})
108
124
  VALUES ({placeholders})
109
- """ # noqa: S608
125
+ """ # noqa: S608
110
126
 
111
127
  try:
112
128
  with self.connect() as conn:
@@ -206,9 +222,32 @@ class SqliterDB:
206
222
  except sqlite3.Error as exc:
207
223
  raise RecordDeletionError(table_name) from exc
208
224
 
209
- def select(self, model_class: type[BaseDBModel]) -> QueryBuilder:
210
- """Start a query for the given model."""
211
- return QueryBuilder(self, model_class)
225
+ def select(
226
+ self,
227
+ model_class: type[BaseDBModel],
228
+ fields: Optional[list[str]] = None,
229
+ exclude: Optional[list[str]] = None,
230
+ ) -> QueryBuilder:
231
+ """Start a query for the given model.
232
+
233
+ Args:
234
+ model_class: The model class to query.
235
+ fields: Optional list of field names to select. If None, all fields
236
+ are selected.
237
+ exclude: Optional list of field names to exclude from the query
238
+ output.
239
+
240
+ Returns:
241
+ QueryBuilder: An instance of QueryBuilder for the given model and
242
+ fields.
243
+ """
244
+ query_builder = QueryBuilder(self, model_class, fields)
245
+
246
+ # If exclude is provided, apply the exclude method
247
+ if exclude:
248
+ query_builder.exclude(exclude)
249
+
250
+ return query_builder
212
251
 
213
252
  # --- Context manager methods ---
214
253
  def __enter__(self) -> Self:
@@ -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
@@ -0,0 +1,12 @@
1
+ sqliter/__init__.py,sha256=L8R0uvCbbbACwaI5xtd3khtvpNhlPRgHJAaYZvqjzig,134
2
+ sqliter/constants.py,sha256=QEUC6kPkwYItgFRUmV6qfK9YV1PcUyUoBwj34yhAyik,441
3
+ sqliter/exceptions.py,sha256=RP1T67PkJMOgkT7yIjES1xil832_UmuAeABtNiv-RKE,3756
4
+ sqliter/sqliter.py,sha256=upUrUmHW6Us8AlIRB6EHDL3cEkjO-tbaRz6q1yGkxGo,8916
5
+ sqliter/model/__init__.py,sha256=Ovpkbyx2-T6Oee0qFNgUBBc2M0uwK-cdG0pigG3mkd8,179
6
+ sqliter/model/model.py,sha256=_-vJ6E38GN8Sxao-etqd6mu5Sy-zkBYsRhFVz5k_yjI,3516
7
+ sqliter/query/__init__.py,sha256=BluNMJpuoo2PsYN-bL7fXlEc02O_8LgOMsvCmyv04ao,125
8
+ sqliter/query/query.py,sha256=nsOKocZk7HZQgTckyae2RGpCPG4Y4wui7nTvqOk510Y,15851
9
+ sqliter_py-0.3.0.dist-info/METADATA,sha256=2uDuEiSjE_2yNgt825liES8lnh5jKW9IjcAAY01KBMc,18890
10
+ sqliter_py-0.3.0.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
11
+ sqliter_py-0.3.0.dist-info/licenses/LICENSE.txt,sha256=-r4mvgoEWzkl1hPO5k8I_iMwJate7zDj8p_Fmn7dhVg,1078
12
+ sqliter_py-0.3.0.dist-info/RECORD,,
@@ -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,11 +0,0 @@
1
- sqliter/__init__.py,sha256=L8R0uvCbbbACwaI5xtd3khtvpNhlPRgHJAaYZvqjzig,134
2
- sqliter/constants.py,sha256=QEUC6kPkwYItgFRUmV6qfK9YV1PcUyUoBwj34yhAyik,441
3
- sqliter/exceptions.py,sha256=RP1T67PkJMOgkT7yIjES1xil832_UmuAeABtNiv-RKE,3756
4
- sqliter/sqliter.py,sha256=1MOa763OQdwkiAHHAitEKox5O9EV0FVMbMWC7pqyk9U,7823
5
- sqliter/model/__init__.py,sha256=Ovpkbyx2-T6Oee0qFNgUBBc2M0uwK-cdG0pigG3mkd8,179
6
- sqliter/model/model.py,sha256=t1w38om37gma1gRk01Z_9II0h4g-l734ijN_8M1SYoY,1247
7
- sqliter/query/__init__.py,sha256=BluNMJpuoo2PsYN-bL7fXlEc02O_8LgOMsvCmyv04ao,125
8
- sqliter/query/query.py,sha256=dRW-Y7X3qH4HrTw-oFbomnl4Kz7WOsImIfoKXZqkMKQ,11648
9
- sqliter_py-0.2.0.dist-info/METADATA,sha256=OBYavQg-H3HipYh_mVkaJ4cL_EUpzqPk1MtypWUpwlg,9880
10
- sqliter_py-0.2.0.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
11
- sqliter_py-0.2.0.dist-info/RECORD,,