Service
Bases: Generic[TModel, TCreate, TUpdate, TPrimaryKey]
Base service implementation.
It's a wrapper sqlmodel's Session. When using the service, use the practices
that are recommended in sqlmodel's documentation.
For example don't reuse the same service instance across multiple requests.
Generic types:
- TModel: The SQLModel class on which table=True is set.
- TCreate: The instance creation model. It may be the same as TModel, although it is
usually different. The TCreate -> TModel conversion happens in _prepare_for_create(),
which you may override.
- TUpdate: The instance update model. It may be the same as TModel, although it is
usually different. The TUpdate -> dict conversion for update operation happens in
_prepare_for_update(), which you may override.
- TPrimaryKey: The type definition of the primary key of TModel. Often simply int or
str, or tuple for complex keys.
Source code in sqlmodelservice/service.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 | |
__init__(session, *, model)
Initialization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session |
Session
|
The session instance the service will use. When the service is created, it becomes the sole owner of the session, it should only be used through the service from then on. |
required |
model |
Type[TModel]
|
The database table model. |
required |
Source code in sqlmodelservice/service.py
_apply_changes_to_item(item, data)
Applies the given changes to the given item without committing anything.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item |
TModel
|
The item to update. |
required |
data |
TUpdate
|
The changes to make to |
required |
Returns:
| Type | Description |
|---|---|
TModel
|
The received item. |
Source code in sqlmodelservice/service.py
_format_primary_key(pk)
Returns the string-formatted version of the primary key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pk |
TPrimaryKey
|
The primary key to format. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If formatting fails. |
Source code in sqlmodelservice/service.py
_prepare_for_create(data)
Hook that is called before applying creating a model.
The methods role is to convert certain attributes of the given model's before creating it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data |
TCreate
|
The model to be created. |
required |
Source code in sqlmodelservice/service.py
_prepare_for_update(data)
Hook that is called before applying the given update.
The method's role is to convert the given data into a dict of
attribute name - new value pairs, omitting unchanged values.
The default implementation is data.model_dump(exclude_unset=True).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data |
TUpdate
|
The update data. |
required |
Source code in sqlmodelservice/service.py
_safe_commit(error_msg)
Commits the session, making sure it is rolled back in case the commit fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error_msg |
str
|
The message for the raised exception. |
required |
Raises:
| Type | Description |
|---|---|
CommitFailed
|
If committing the session failed. |
Source code in sqlmodelservice/service.py
add_to_session(items, *, commit=False, operation)
Adds all items to the session using the same flow as create() or update(),
depending on the selected operation.
If commit is True, the method will commit the transaction even if items is empty.
The reason for this is to allow chaining add_to_session() calls without special
attention to when and how the session must be committed at the end.
Note: even if commit is True, the method will not perform a refresh on the items
as it has to be done one by one which would be very inefficient with many items.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items |
Iterable[TCreate] | Iterable[tuple[TModel, TUpdate]]
|
The items to add to the session. |
required |
commit |
bool
|
Whether to also commit the changes to the database. |
False
|
operation |
Literal['create', 'update']
|
The desired operation. |
required |
Returns:
| Type | Description |
|---|---|
list[TModel]
|
The list of items that were added to the session. |
Raises:
| Type | Description |
|---|---|
CommitFailed
|
If the service fails to commit the operation. |
Source code in sqlmodelservice/service.py
create(data)
Creates a new database entry from the given data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data |
TCreate
|
Creation data. |
required |
Raises:
| Type | Description |
|---|---|
CommitFailed
|
If the service fails to commit the operation. |
Source code in sqlmodelservice/service.py
delete_by_pk(pk)
Deletes the item with the given primary key from the database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pk |
TPrimaryKey
|
The primary key. |
required |
Raises:
| Type | Description |
|---|---|
CommitFailed
|
If the service fails to commit the operation. |
NotFound
|
If the document with the given primary key does not exist. |
Source code in sqlmodelservice/service.py
exec(statement)
get_all()
Returns all items from the database.
Deprecated. Use all() instead.
get_by_pk(pk)
Returns the item with the given primary key if it exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pk |
PrimaryKey
|
The primary key. |
required |
one(where)
Returns item that matches the given where clause.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
where |
ColumnElement[bool] | bool
|
The where clause of the query. |
required |
Raises:
| Type | Description |
|---|---|
MultipleResultsFound
|
If multiple items match the where clause. |
NotFound
|
If no items match the where clause. |
Source code in sqlmodelservice/service.py
one_or_none(where)
Returns item that matches the given where clause, if there is such an item.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
where |
ColumnElement[bool] | bool
|
The where clause of the query. |
required |
Raises:
| Type | Description |
|---|---|
MultipleResultsFound
|
If multiple items match the where clause. |
Source code in sqlmodelservice/service.py
refresh(instance)
select(*joined)
Creates a select statement on the service's table.
Positional arguments (SQLModel table definitions) will be included in the select statement. You must specify the join condition for each included positional argument though.
If joined is not empty, then a tuple will be returned with len(joined) + 1 values
in it. The first value will be an instance of TModel, the rest of the values will
correspond to the positional arguments that were passed to the method.
Example:
class A(SQLModel, table=True):
id: int | None = Field(primary_key=True)
a: str
class B(SQLModel, table=True):
id: int | None = Field(primary_key=True)
b: str
class AService(Service[A, A, A, int]):
def __init__(self, session: Session) -> None:
super().__init__(session, model=A)
with Session(engine) as session:
a_svc = AService(session)
q = a_svc.select(B).where(A.a == B.b)
result = svc.exec(q).one()
print(result[0]) # A instance
print(result[1]) # B instance
Source code in sqlmodelservice/service.py
update(pk, data)
Updates the item with the given primary key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pk |
TPrimaryKey
|
The primary key. |
required |
data |
TUpdate
|
Update data. |
required |
Raises:
| Type | Description |
|---|---|
CommitFailed
|
If the service fails to commit the operation. |
NotFound
|
If the record with the given primary key does not exist. |
Source code in sqlmodelservice/service.py
update_item(item, data)
Updates the given item.
The same as update() but without data fetching.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item |
TModel
|
The item to update. |
required |
data |
TUpdate
|
Update data. |
required |
Raises:
| Type | Description |
|---|---|
CommitFailed
|
If the service fails to commit the operation. |
NotFound
|
If the record with the given primary key does not exist. |