sqlobjects 2.1.0__tar.gz → 2.1.1__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.
Files changed (84) hide show
  1. {sqlobjects-2.1.0/sqlobjects.egg-info → sqlobjects-2.1.1}/PKG-INFO +9 -7
  2. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/README.md +7 -5
  3. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/docs/rules/01-database-session-guide.md +12 -4
  4. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/docs/rules/03-query-operations-guide.md +14 -9
  5. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/docs/rules/04-crud-operations-guide.md +1 -1
  6. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/docs/rules/05-relationships-guide.md +11 -8
  7. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/docs/rules/06-validation-signals-guide.md +15 -12
  8. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/docs/rules/07-performance-guide.md +3 -3
  9. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/pyproject.toml +2 -2
  10. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/__init__.py +1 -1
  11. sqlobjects-2.1.1/sqlobjects/_compat.py +61 -0
  12. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/fields/core.py +2 -2
  13. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/metadata.py +4 -7
  14. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/sql_logging.py +9 -2
  15. {sqlobjects-2.1.0 → sqlobjects-2.1.1/sqlobjects.egg-info}/PKG-INFO +9 -7
  16. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects.egg-info/SOURCES.txt +1 -1
  17. sqlobjects-2.1.1/sqlobjects.egg-info/requires.txt +4 -0
  18. sqlobjects-2.1.0/CHANGELOG.md +0 -314
  19. sqlobjects-2.1.0/sqlobjects.egg-info/requires.txt +0 -4
  20. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/LICENSE +0 -0
  21. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/docs/rules/02-model-definition-guide.md +0 -0
  22. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/docs/rules/README.md +0 -0
  23. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/setup.cfg +0 -0
  24. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/_install_rules.py +0 -0
  25. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/cascade.py +0 -0
  26. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/contrib/__init__.py +0 -0
  27. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/contrib/asgi.py +0 -0
  28. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/contrib/fastapi.py +0 -0
  29. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/database/__init__.py +0 -0
  30. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/database/config.py +0 -0
  31. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/database/manager.py +0 -0
  32. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/exceptions.py +0 -0
  33. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/expressions/__init__.py +0 -0
  34. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/expressions/aggregate.py +0 -0
  35. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/expressions/base.py +0 -0
  36. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/expressions/cte.py +0 -0
  37. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/expressions/explain.py +0 -0
  38. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/expressions/function.py +0 -0
  39. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/expressions/mixins.py +0 -0
  40. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/expressions/scalar.py +0 -0
  41. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/expressions/subquery.py +0 -0
  42. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/expressions/terminal.py +0 -0
  43. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/expressions/window.py +0 -0
  44. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/fields/__init__.py +0 -0
  45. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/fields/functions.py +0 -0
  46. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/fields/proxies.py +0 -0
  47. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/fields/relations/__init__.py +0 -0
  48. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/fields/relations/descriptors.py +0 -0
  49. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/fields/relations/managers.py +0 -0
  50. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/fields/relations/prefetch.py +0 -0
  51. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/fields/relations/strategies.py +0 -0
  52. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/fields/relations/utils.py +0 -0
  53. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/fields/shortcuts.py +0 -0
  54. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/fields/types/__init__.py +0 -0
  55. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/fields/types/base.py +0 -0
  56. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/fields/types/comparators.py +0 -0
  57. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/fields/types/registry.py +0 -0
  58. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/fields/utils.py +0 -0
  59. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/internal/__init__.py +0 -0
  60. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/internal/operations.py +0 -0
  61. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/internal/results.py +0 -0
  62. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/mixins.py +0 -0
  63. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/model.py +0 -0
  64. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/objects/__init__.py +0 -0
  65. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/objects/bulk.py +0 -0
  66. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/objects/core.py +0 -0
  67. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/objects/upsert.py +0 -0
  68. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/py.typed +0 -0
  69. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/queries/__init__.py +0 -0
  70. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/queries/builder.py +0 -0
  71. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/queries/dialect.py +0 -0
  72. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/queries/executor.py +0 -0
  73. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/queryset.py +0 -0
  74. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/session.py +0 -0
  75. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/signals.py +0 -0
  76. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/utils/__init__.py +0 -0
  77. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/utils/inspect.py +0 -0
  78. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/utils/naming.py +0 -0
  79. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/utils/pattern.py +0 -0
  80. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects/validators.py +0 -0
  81. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects.egg-info/dependency_links.txt +0 -0
  82. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects.egg-info/entry_points.txt +0 -0
  83. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/sqlobjects.egg-info/top_level.txt +0 -0
  84. {sqlobjects-2.1.0 → sqlobjects-2.1.1}/tests/test_config.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sqlobjects
3
- Version: 2.1.0
3
+ Version: 2.1.1
4
4
  Summary: Django-style async ORM library based on SQLAlchemy with chainable queries, Q objects, and relationship loading
5
5
  Author-email: XtraVisions <gitadmin@xtravisions.com>, Chen Hao <chenhao@xtravisions.com>
6
6
  Maintainer-email: XtraVisions <gitadmin@xtravisions.com>, Chen Hao <chenhao@xtravisions.com>
@@ -24,7 +24,7 @@ Classifier: Typing :: Typed
24
24
  Requires-Python: >=3.12
25
25
  Description-Content-Type: text/markdown
26
26
  License-File: LICENSE
27
- Requires-Dist: sqlalchemy[asyncio]>=2.0.44
27
+ Requires-Dist: sqlalchemy[asyncio]<2.2,>=2.0.44
28
28
  Provides-Extra: migrations
29
29
  Requires-Dist: alembic>=1.16.5; extra == "migrations"
30
30
  Dynamic: license-file
@@ -178,7 +178,7 @@ from sqlobjects.session import ctx_session, ctx_sessions
178
178
  # Single database transaction
179
179
  async with ctx_session() as session:
180
180
  user = await User.objects.using(session).create(username="bob")
181
- posts = await user.posts.using(session).all()
181
+ posts = await Post.objects.using(session).filter(author_id=user.id).all()
182
182
  # Automatic commit on success, rollback on error
183
183
 
184
184
  # Multi-database transactions
@@ -302,10 +302,12 @@ avg_age = User.objects.aggregate(avg_age=func.avg(User.age)).subquery(query_type
302
302
  older_users = await User.objects.filter(User.age > avg_age).all()
303
303
 
304
304
  # Manual joins and locking
305
- posts = await Post.objects.join(
306
- User, # Using Model class (recommended)
307
- Post.author_id == User.id
308
- ).select_for_update(nowait=True).all()
305
+ # Row locks need an explicit transaction on PostgreSQL/MySQL
306
+ async with ctx_session():
307
+ posts = await Post.objects.join(
308
+ User, # Using Model class (recommended)
309
+ Post.author_id == User.id
310
+ ).select_for_update(nowait=True).all()
309
311
 
310
312
  # Raw SQL when needed
311
313
  users = await User.objects.raw(
@@ -147,7 +147,7 @@ from sqlobjects.session import ctx_session, ctx_sessions
147
147
  # Single database transaction
148
148
  async with ctx_session() as session:
149
149
  user = await User.objects.using(session).create(username="bob")
150
- posts = await user.posts.using(session).all()
150
+ posts = await Post.objects.using(session).filter(author_id=user.id).all()
151
151
  # Automatic commit on success, rollback on error
152
152
 
153
153
  # Multi-database transactions
@@ -271,10 +271,12 @@ avg_age = User.objects.aggregate(avg_age=func.avg(User.age)).subquery(query_type
271
271
  older_users = await User.objects.filter(User.age > avg_age).all()
272
272
 
273
273
  # Manual joins and locking
274
- posts = await Post.objects.join(
275
- User, # Using Model class (recommended)
276
- Post.author_id == User.id
277
- ).select_for_update(nowait=True).all()
274
+ # Row locks need an explicit transaction on PostgreSQL/MySQL
275
+ async with ctx_session():
276
+ posts = await Post.objects.join(
277
+ User, # Using Model class (recommended)
278
+ Post.author_id == User.id
279
+ ).select_for_update(nowait=True).all()
278
280
 
279
281
  # Raw SQL when needed
280
282
  users = await User.objects.raw(
@@ -48,7 +48,7 @@ from sqlobjects.session import ctx_session, ctx_sessions
48
48
  # Single database transaction
49
49
  async with ctx_session() as session:
50
50
  user = await User.objects.using(session).create(username="bob")
51
- posts = await user.posts.using(session).all()
51
+ posts = await user.load_relation("posts")
52
52
  # Auto-commit on success, rollback on exception
53
53
 
54
54
  # Multi-database transaction
@@ -114,6 +114,11 @@ if has_session("analytics"):
114
114
  - `has_session()` reports only an open session usable by the current task.
115
115
  - A closed session cannot be reused. Background work must open a new context.
116
116
  - Cancellation rolls back request/context transactions and releases their connections.
117
+ - After an SQL error in an explicit transaction, call `rollback()` or wrap the
118
+ risky statement in `async with await session.begin_nested():`; otherwise later
119
+ statements raise `TransactionError`. Readonly sessions are unaffected by a failed
120
+ query. On an implicit (auto-commit) session the transaction opened by
121
+ `begin_nested()` commits when its outermost savepoint ends.
117
122
 
118
123
  ### ✅ Do
119
124
 
@@ -198,7 +203,7 @@ async with ctx_session() as session:
198
203
  # All operations share the same connection
199
204
  users = await User.objects.using(session).all()
200
205
  for user in users:
201
- await user.posts.using(session).all()
206
+ await user.load_relation("posts") # Uses the loading session
202
207
  ```
203
208
 
204
209
  ### Read/Write Separation
@@ -414,10 +419,13 @@ skips timing and frame inspection; enabled logging resolves the user frame
414
419
  across the async greenlet bridge.
415
420
 
416
421
  Each record carries `sql`, driver-format `params`, `duration_ms`, `db_name`,
417
- `dialect`, `executemany`, `rowcount`, `success`, and `error_type`. Parameters may
422
+ `dialect`, `executemany`, `rowcount`, `success`, `error_type`, and
423
+ `driver_error_type`. Parameters may
418
424
  be a dictionary, tuple or a sequence of parameter sets. `hide_parameters=True`
419
425
  in `init_db()` makes `params` null, including on failure; raw SQL literals are
420
- not redacted. Errors include only the exception class, not its message.
426
+ not redacted. Errors include only exception classes, not messages: `error_type` is the
427
+ SQLAlchemy class and is stable across drivers, `driver_error_type` is the
428
+ driver's own class and is not.
421
429
 
422
430
  Records count driver calls, not ORM methods or returned rows. Timing excludes
423
431
  pool checkout, compilation, later fetching, hydration and commit. `rowcount` can
@@ -314,17 +314,22 @@ posts = await Post.objects.outerjoin(
314
314
  ### Row Locking
315
315
 
316
316
  ```python
317
- # Pessimistic locking (FOR UPDATE)
318
- user = await User.objects.filter(
319
- User.id == 1
320
- ).select_for_update(nowait=True).first()
321
-
322
- # Shared locking (FOR SHARE)
323
- users = await User.objects.filter(
324
- User.department == "sales"
325
- ).select_for_share(skip_locked=True).all()
317
+ # Row locks require an explicit transaction on PostgreSQL/MySQL
318
+ async with ctx_session():
319
+ # Pessimistic locking (FOR UPDATE)
320
+ user = await User.objects.filter(
321
+ User.id == 1
322
+ ).select_for_update(nowait=True).first()
323
+
324
+ # Shared locking (FOR SHARE)
325
+ users = await User.objects.filter(
326
+ User.department == "sales"
327
+ ).select_for_share(skip_locked=True).all()
326
328
  ```
327
329
 
330
+ Outside SQLite, `select_for_update()` / `select_for_share()` must run inside an
331
+ explicit transaction; the lock is held until that transaction ends.
332
+
328
333
  ### Date/Time Extraction
329
334
 
330
335
  ```python
@@ -337,7 +337,7 @@ await User.objects.bulk_create(data, batch_size=100) # SQLite
337
337
  async with ctx_session() as session:
338
338
  # Quick database operations only
339
339
  user = await User.objects.using(session).create(username="alice")
340
- await user.posts.using(session).create(title="Post")
340
+ await Post.objects.using(session).create(title="Post", author_id=user.id)
341
341
  # Transaction commits here
342
342
 
343
343
  # Don't hold transactions during I/O
@@ -58,7 +58,7 @@ for post in posts:
58
58
  # prefetch_related (separate query) - for reverse relationships
59
59
  users = await User.objects.prefetch_related("posts").all()
60
60
  for user in users:
61
- posts = await user.posts.fetch() # No N+1 queries
61
+ posts = await user.load_relation("posts") # Prefetched list, no query
62
62
 
63
63
  # Combined loading
64
64
  posts = await Post.objects.select_related("author").prefetch_related("comments").all()
@@ -162,7 +162,9 @@ users = await User.objects.prefetch_related(
162
162
  ### ❌ Don't
163
163
 
164
164
  - **Don't use select_related** for reverse relationships (use prefetch_related)
165
- - **Don't forget to fetch()** lazy-loaded relationships
165
+ - **Don't forget to load** lazy relationships with `load_relation()`; after
166
+ `select_related`/`prefetch_related` the attribute is already an entity or list and
167
+ has no `.fetch()`
166
168
  - **Don't cause N+1 queries** by not using loading strategies
167
169
  - **Don't mix loading strategies** incorrectly
168
170
 
@@ -200,7 +202,7 @@ class Book(ObjectModel):
200
202
 
201
203
  # Usage
202
204
  author = await Author.objects.prefetch_related("books").get(Author.id == 1)
203
- books = await author.books.fetch()
205
+ books = await author.load_relation("books") # Prefetched list, no extra query
204
206
  ```
205
207
 
206
208
  ### One-to-One
@@ -233,7 +235,7 @@ class Course(ObjectModel):
233
235
 
234
236
  # Usage
235
237
  student = await Student.objects.prefetch_related("courses").get(Student.id == 1)
236
- courses = await student.courses.fetch()
238
+ courses = await student.load_relation("courses") # Prefetched list, no extra query
237
239
  ```
238
240
 
239
241
  ### Self-Referential
@@ -369,11 +371,11 @@ posts = await Post.objects.select_related("author").defer(
369
371
  "author__bio" # Heavy field from related model
370
372
  ).all()
371
373
 
372
- # Filter prefetched relationships
374
+ # Filter prefetched relationships (slicing the prefetch queryset is rejected)
373
375
  users = await User.objects.prefetch_related(
374
376
  posts=Post.objects.filter(
375
377
  Post.created_at >= datetime.now(timezone.utc) - timedelta(days=7)
376
- ).order_by('-created_at').limit(10)
378
+ ).order_by('-created_at')
377
379
  ).all()
378
380
  ```
379
381
 
@@ -416,9 +418,10 @@ users = await User.objects.prefetch_related("posts").all()
416
418
 
417
419
  **Solution**:
418
420
  ```python
419
- # Use fetch() for lazy-loaded relationships
421
+ # Use load_relation() for lazy relationships (works whether or not the
422
+ # relationship was eagerly loaded; .fetch() exists only on the lazy proxy)
420
423
  post = await Post.objects.get(Post.id == 1)
421
- author = await post.author.fetch() # Explicit load
424
+ author = await post.load_relation("author") # Explicit load
422
425
 
423
426
  # Or use select_related
424
427
  post = await Post.objects.select_related("author").get(Post.id == 1)
@@ -233,7 +233,9 @@ async def before_save(self, context: SignalContext):
233
233
  self.updated_at = datetime.now(timezone.utc) # Fast
234
234
 
235
235
  async def after_save(self, context: SignalContext):
236
- asyncio.create_task(self.process_large_file()) # Background task
236
+ # after_* hooks run before the transaction commits; defer external side
237
+ # effects until the commit succeeds
238
+ await context.on_commit(self.process_large_file)
237
239
  ```
238
240
 
239
241
  ## Signal Execution Flow
@@ -323,22 +325,23 @@ class User(ObjectModel):
323
325
  ### Signal Performance
324
326
 
325
327
  ```python
326
- # Group related operations
328
+ # ORM writes that belong to the same transaction: await them sequentially.
329
+ # Hooks run inside the operation's session, which belongs to the current task;
330
+ # asyncio.create_task()/gather() would run them in other tasks and raise
331
+ # TransactionError.
327
332
  async def after_create(self, context: SignalContext):
328
- await asyncio.gather(
329
- self.send_welcome_email(),
330
- self.create_default_preferences(),
331
- self.log_user_creation()
332
- )
333
+ await self.create_default_preferences()
334
+ await self.log_user_creation()
333
335
 
334
- # Background tasks for non-critical operations
336
+ # External side effects: defer until the transaction has committed.
337
+ # after_* hooks fire before commit, so a rollback would otherwise leave
338
+ # emails sent or indexes updated for data that never persisted.
335
339
  async def after_save(self, context: SignalContext):
336
- # Critical operations (blocking)
337
340
  self.updated_at = datetime.now(timezone.utc)
338
-
339
- # Non-critical operations (background)
341
+
340
342
  if not context.is_bulk:
341
- asyncio.create_task(self.update_search_index())
343
+ await context.on_commit(self.update_search_index)
344
+ await context.on_commit(self.send_welcome_email)
342
345
  ```
343
346
 
344
347
  ### Validation Performance
@@ -66,7 +66,7 @@ for post in posts:
66
66
  # prefetch_related for reverse relationships (fast - 2 queries)
67
67
  users = await User.objects.prefetch_related("posts").all()
68
68
  for user in users:
69
- posts = await user.posts.fetch() # No N+1 queries
69
+ posts = await user.load_relation("posts") # Returns the prefetched list, no query
70
70
  ```
71
71
 
72
72
  ### Query Optimization
@@ -106,7 +106,7 @@ async with ctx_session() as session:
106
106
  # All operations share the same connection
107
107
  users = await User.objects.using(session).all()
108
108
  for user in users:
109
- await user.posts.using(session).all()
109
+ await user.load_relation("posts") # Uses the loading session
110
110
  ```
111
111
 
112
112
  ## Best Practices
@@ -297,7 +297,7 @@ print(f"Query took {duration:.3f} seconds")
297
297
  start = time.time()
298
298
  posts = await Post.objects.all()
299
299
  for post in posts[:10]:
300
- author = await post.author.fetch()
300
+ author = await post.load_relation("author")
301
301
  time_without = time.time() - start
302
302
 
303
303
  # With select_related
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sqlobjects"
3
- version = "2.1.0"
3
+ version = "2.1.1"
4
4
  description = "Django-style async ORM library based on SQLAlchemy with chainable queries, Q objects, and relationship loading"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -34,7 +34,7 @@ classifiers = [
34
34
  ]
35
35
  requires-python = ">=3.12"
36
36
  dependencies = [
37
- "sqlalchemy[asyncio]>=2.0.44",
37
+ "sqlalchemy[asyncio]>=2.0.44,<2.2",
38
38
  ]
39
39
 
40
40
  [project.optional-dependencies]
@@ -19,7 +19,7 @@ from .queryset import Q, QuerySet
19
19
  from .sql_logging import ObjectLogger, get_caller_frame
20
20
 
21
21
 
22
- __version__ = "2.1.0"
22
+ __version__ = "2.1.1"
23
23
 
24
24
  __all__ = [
25
25
  # Core classes
@@ -0,0 +1,61 @@
1
+ """SQLAlchemy version compatibility helpers.
2
+
3
+ Everything that depends on SQLAlchemy internals differing between supported
4
+ release series lives here, so that an upgrade breaks in one tested place
5
+ instead of at import time in user code.
6
+
7
+ Supported series: 2.0 (>= 2.0.44) and 2.1.
8
+ """
9
+
10
+ from typing import Any
11
+
12
+ from sqlalchemy import ForeignKey
13
+
14
+
15
+ __all__ = ["foreign_key_copy_target", "foreign_key_target_tokens", "retarget_foreign_key"]
16
+
17
+ # SQLAlchemy 2.1 stores a name-based foreign key target as a
18
+ # ``ForeignKeyTarget(schema, table_name, column_name)`` tuple exposed through
19
+ # the public ``ForeignKey.target_tokens``; ``_colspec`` became a read-only
20
+ # legacy accessor. 2.0 stores the dotted string in a writable ``_colspec``.
21
+ _HAS_TARGET_TOKENS = hasattr(ForeignKey, "target_tokens")
22
+
23
+
24
+ def foreign_key_target_tokens(fk: ForeignKey) -> tuple[str | None, str, str | None]:
25
+ """Return the ``(schema, table_name, column_name)`` target of a foreign key."""
26
+ raw: Any = fk # version-specific attributes; see _HAS_TARGET_TOKENS
27
+ schema, table_name, column_name = raw.target_tokens if _HAS_TARGET_TOKENS else raw._column_tokens # noqa: SLF001
28
+ return schema, table_name, column_name
29
+
30
+
31
+ def foreign_key_copy_target(fk: ForeignKey) -> Any:
32
+ """Return a value that builds an equivalent ``ForeignKey`` when passed to its constructor.
33
+
34
+ A target given as a ``Column`` is returned as that column; a target given
35
+ by name is returned in the form the running SQLAlchemy version stores it,
36
+ so names containing dots survive the copy on 2.1.
37
+ """
38
+ raw: Any = fk
39
+ if _HAS_TARGET_TOKENS:
40
+ column = raw.target_column
41
+ return raw.target_tokens if column is None else column
42
+ return raw._colspec # noqa: SLF001
43
+
44
+
45
+ def retarget_foreign_key(fk: ForeignKey, table_name: str) -> None:
46
+ """Point a name-based foreign key at another table, keeping schema and column.
47
+
48
+ Used to replace a model class name with the model's actual table name once
49
+ the referenced model is registered. SQLAlchemy has no public API for
50
+ changing the target of an existing ``ForeignKey``, so this is the single
51
+ place allowed to rewrite its private state.
52
+ """
53
+ raw: Any = fk
54
+ if _HAS_TARGET_TOKENS:
55
+ raw._given_tokens = raw.target_tokens._replace(table_name=table_name) # noqa: SLF001
56
+ else:
57
+ schema, _, column_name = raw._column_tokens # noqa: SLF001
58
+ prefix = f"{schema}." if schema else ""
59
+ raw._colspec = f"{prefix}{table_name}.{column_name}" # noqa: SLF001
60
+ # Memoized on 2.0; drop it so the new target is parsed again.
61
+ raw.__dict__.pop("_column_tokens", None)
@@ -10,6 +10,7 @@ from sqlalchemy.sql.elements import ColumnElement
10
10
 
11
11
  from sqlobjects.fields.proxies import RelatedCollection, RelatedObject
12
12
 
13
+ from .._compat import foreign_key_copy_target
13
14
  from ..cascade import OnDelete
14
15
  from ..expressions.mixins import ColumnAttributeFunctionMixin
15
16
  from .types import create_type_instance
@@ -514,9 +515,8 @@ class ColumnAttribute(ColumnAttributeFunctionMixin, Generic[T]):
514
515
  foreign_keys = []
515
516
  if self.__column__.foreign_keys:
516
517
  for fk in self.__column__.foreign_keys:
517
- # Use original string reference instead of column attribute
518
518
  new_fk = ForeignKey(
519
- fk._colspec, # noqa # Use original string reference
519
+ foreign_key_copy_target(fk),
520
520
  name=fk.name,
521
521
  onupdate=fk.onupdate,
522
522
  ondelete=fk.ondelete,
@@ -8,6 +8,7 @@ from sqlalchemy import MetaData as SqlAlchemyMetaData
8
8
  from sqlalchemy.exc import CompileError
9
9
  from sqlalchemy.sql.elements import conv
10
10
 
11
+ from ._compat import foreign_key_target_tokens, retarget_foreign_key
11
12
  from .fields import ColumnAttribute
12
13
  from .fields.relations import M2MTable, RelationshipDescriptor, RelationshipResolver
13
14
  from .fields.utils import get_column_from_field, is_field_definition
@@ -954,7 +955,7 @@ class ModelProcessor(type):
954
955
  def _resolve_class_foreign_keys(mcs, registry):
955
956
  """延迟解析外键引用:优先按类名匹配,匹配不到则视为表名。
956
957
 
957
- foreign_key("User.id") 传入时原样交给 SQLAlchemy(_colspec="User.id")。
958
+ foreign_key("User.id") 传入时原样交给 SQLAlchemy(目标为 "User.id")。
958
959
  每次新模型注册后,此方法遍历所有 FK:
959
960
  1. 取出 info["_fk_ref"](即 "." 前的那段,如 "User")
960
961
  2. 尝试在 registry 中按类名查找模型
@@ -975,13 +976,9 @@ class ModelProcessor(type):
975
976
  continue
976
977
  # Found matching model — rewrite _colspec to actual table name
977
978
  actual_table = model.__table__.name
978
- schema, tname, colname = fk._column_tokens
979
+ _, tname, _ = foreign_key_target_tokens(fk)
979
980
  if tname != actual_table:
980
- if schema:
981
- fk._colspec = f"{schema}.{actual_table}.{colname}"
982
- else:
983
- fk._colspec = f"{actual_table}.{colname}"
984
- fk.__dict__.pop("_column_tokens", None)
981
+ retarget_foreign_key(fk, actual_table)
985
982
  fk_info["_fk_resolved"] = True
986
983
 
987
984
  @classmethod
@@ -244,7 +244,7 @@ def _install_query_logging(engine: Engine, db_name: str) -> None:
244
244
  def do_execute_no_params(cursor, statement, context):
245
245
  start(context, statement, None, False)
246
246
 
247
- def emit(context, cursor=None, error=None):
247
+ def emit(context, cursor=None, error=None, driver_error=None):
248
248
  if context is None:
249
249
  return
250
250
  timing = context.__dict__.pop(timing_key, None)
@@ -265,6 +265,7 @@ def _install_query_logging(engine: Engine, db_name: str) -> None:
265
265
  "rowcount": cursor.rowcount if cursor is not None and error is None else None,
266
266
  "success": error is None,
267
267
  "error_type": type(error).__name__ if error is not None else None,
268
+ "driver_error_type": type(driver_error).__name__ if driver_error is not None else None,
268
269
  },
269
270
  )
270
271
  except Exception:
@@ -275,9 +276,15 @@ def _install_query_logging(engine: Engine, db_name: str) -> None:
275
276
  emit(context, cursor)
276
277
 
277
278
  def handle_error(exception_context):
279
+ # The driver exception class differs across drivers and SQLAlchemy versions
280
+ # (asyncpg reports UniqueViolationError on 2.1, IntegrityError on 2.0), so
281
+ # error_type uses SQLAlchemy's own class when the error was wrapped.
282
+ # Non-DBAPI errors such as CancelledError are not wrapped.
283
+ original = exception_context.original_exception
278
284
  emit(
279
285
  exception_context.execution_context,
280
- error=exception_context.original_exception,
286
+ error=exception_context.sqlalchemy_exception or original,
287
+ driver_error=original,
281
288
  )
282
289
 
283
290
  # Dialect events receive each batch's actual SQL/params. For insertmanyvalues,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sqlobjects
3
- Version: 2.1.0
3
+ Version: 2.1.1
4
4
  Summary: Django-style async ORM library based on SQLAlchemy with chainable queries, Q objects, and relationship loading
5
5
  Author-email: XtraVisions <gitadmin@xtravisions.com>, Chen Hao <chenhao@xtravisions.com>
6
6
  Maintainer-email: XtraVisions <gitadmin@xtravisions.com>, Chen Hao <chenhao@xtravisions.com>
@@ -24,7 +24,7 @@ Classifier: Typing :: Typed
24
24
  Requires-Python: >=3.12
25
25
  Description-Content-Type: text/markdown
26
26
  License-File: LICENSE
27
- Requires-Dist: sqlalchemy[asyncio]>=2.0.44
27
+ Requires-Dist: sqlalchemy[asyncio]<2.2,>=2.0.44
28
28
  Provides-Extra: migrations
29
29
  Requires-Dist: alembic>=1.16.5; extra == "migrations"
30
30
  Dynamic: license-file
@@ -178,7 +178,7 @@ from sqlobjects.session import ctx_session, ctx_sessions
178
178
  # Single database transaction
179
179
  async with ctx_session() as session:
180
180
  user = await User.objects.using(session).create(username="bob")
181
- posts = await user.posts.using(session).all()
181
+ posts = await Post.objects.using(session).filter(author_id=user.id).all()
182
182
  # Automatic commit on success, rollback on error
183
183
 
184
184
  # Multi-database transactions
@@ -302,10 +302,12 @@ avg_age = User.objects.aggregate(avg_age=func.avg(User.age)).subquery(query_type
302
302
  older_users = await User.objects.filter(User.age > avg_age).all()
303
303
 
304
304
  # Manual joins and locking
305
- posts = await Post.objects.join(
306
- User, # Using Model class (recommended)
307
- Post.author_id == User.id
308
- ).select_for_update(nowait=True).all()
305
+ # Row locks need an explicit transaction on PostgreSQL/MySQL
306
+ async with ctx_session():
307
+ posts = await Post.objects.join(
308
+ User, # Using Model class (recommended)
309
+ Post.author_id == User.id
310
+ ).select_for_update(nowait=True).all()
309
311
 
310
312
  # Raw SQL when needed
311
313
  users = await User.objects.raw(
@@ -1,4 +1,3 @@
1
- CHANGELOG.md
2
1
  LICENSE
3
2
  README.md
4
3
  pyproject.toml
@@ -11,6 +10,7 @@ docs/rules/06-validation-signals-guide.md
11
10
  docs/rules/07-performance-guide.md
12
11
  docs/rules/README.md
13
12
  sqlobjects/__init__.py
13
+ sqlobjects/_compat.py
14
14
  sqlobjects/_install_rules.py
15
15
  sqlobjects/cascade.py
16
16
  sqlobjects/exceptions.py
@@ -0,0 +1,4 @@
1
+ sqlalchemy[asyncio]<2.2,>=2.0.44
2
+
3
+ [migrations]
4
+ alembic>=1.16.5
@@ -1,314 +0,0 @@
1
- ## 2.1.0 (2026-10-08)
2
-
3
- ### Feat
4
-
5
- - **queries**: support aggregation over grouped querysets
6
- - **relations**: implement scoped async dynamic collections
7
- - **migrations**: add async Alembic integration and isolated registries
8
- - **logging**: observe SQL execution across database engines
9
- - **session**: add transaction commit callbacks
10
-
11
- ### Fix
12
-
13
- - **orm**: close review follow-ups in sessions, upsert attribution and dynamic proxies
14
- - **metadata**: preserve distinct index definitions during deduplication
15
- - **metadata**: generate portable collision-safe schema names
16
- - **queries**: preserve composed queryset aggregation semantics
17
- - **database**: align event registration with SQLAlchemy Core
18
- - **orm**: preserve distinct semantics and transaction-bound signals
19
- - **session**: enforce task ownership and cancellation cleanup
20
- - **orm**: enforce persistence and transaction contracts
21
-
22
- ## 2.0.1 (2026-08-31)
23
-
24
- ### Fix
25
-
26
- - **metadata**: include dialect kwargs in index dedup signature
27
-
28
- ## 2.0.0 (2026-08-19)
29
-
30
- ### BREAKING CHANGE
31
-
32
- - annotate().group_by().all() with non-primary-key
33
- grouping and group_by().aggregate() now raise QueryError; both
34
- previously returned silently wrong results. QuerySet.create() removed
35
- (never wrote to the database) — use Model.objects.create().
36
-
37
- ### Feat
38
-
39
- - **rules**: stamp installed rule files with the package version
40
- - **query**: strict GROUP BY semantics, values-mode aggregation, manager-only hints
41
- - **orm**: support SQLAlchemy expressions as write values
42
- - **bulk**: make BulkResult a sequence and guarantee insert RETURNING order
43
- - **session**: add join_ambient option to ctx_session and warn on nested sessions
44
- - **build**: ship py.typed marker so type checkers see the package as typed
45
-
46
- ## 1.10.0 (2026-07-24)
47
-
48
- ### Feat
49
-
50
- - **model**: add public get_dirty_fields() accessor on BaseMixin
51
-
52
- ### Fix
53
-
54
- - **build**: sync __version__ with pyproject and auto-update via cz version_files
55
-
56
- ## 1.9.1 (2026-04-09)
57
-
58
- ### Fix
59
-
60
- - **query**: order_by uses replace semantics instead of append
61
-
62
- ## 1.9.0 (2026-03-27)
63
-
64
- ### Feat
65
-
66
- - **logging**: wire ObjectLogger into QueryExecutor, zero-config caller rewriting
67
- - **logging**: replace SQLCallerFilter with ObjectLogger, remove SQLCallerFilter
68
- - **logging**: add ObjectLogger and _install_object_logger
69
-
70
- ### Fix
71
-
72
- - **logging**: skip stdlib logging frames in _should_skip_frame, add end-to-end test
73
- - **logging**: use logging._lock context manager for Python 3.13 compatibility
74
- - **logging**: add _should_skip_frame tests and fix assertion quality
75
-
76
- ### Refactor
77
-
78
- - **logging**: extract _should_skip_frame and add _find_user_frame
79
-
80
- ## 1.8.0 (2026-03-26)
81
-
82
- ### Feat
83
-
84
- - **logging**: export SQLCallerFilter and get_caller_frame in public API
85
- - **logging**: emit SQL log records in QueryExecutor
86
- - **logging**: add SQLCallerFilter
87
- - **logging**: add get_caller_frame() helper
88
-
89
- ### Fix
90
-
91
- - **logging**: eliminate isEnabledFor race and fix test name
92
- - **logging**: restore logger level in test_no_log_when_logger_disabled
93
- - **logging**: guard timing code with isEnabledFor check
94
- - **logging**: simplify SQLCallerFilter extra_skip_packages handling
95
- - **logging**: fix frame-skip edge cases and improve code quality
96
-
97
- ## 1.7.0 (2026-03-26)
98
-
99
- ### Feat
100
-
101
- - **metadata**: add foreignkey() constraint builder
102
-
103
- ### Fix
104
-
105
- - **raw**: allow SA expressions as arguments in raw() methods
106
-
107
- ## 1.6.0 (2026-03-18)
108
-
109
- ### Feat
110
-
111
- - **metadata**: add foreignkey() constraint builder
112
-
113
- ## 1.5.0 (2026-03-16)
114
-
115
- ### Feat
116
-
117
- - **cascade**: unify cascade strategy with auto-detection for Model.delete()
118
-
119
- ## 1.4.0 (2026-03-11)
120
-
121
- ### Feat
122
-
123
- - **session**: fix nested ctx_session() and add ASGI/FastAPI integration
124
-
125
- ## 1.3.0 (2026-03-10)
126
-
127
- ### Feat
128
-
129
- - **fields**: support class name reference in foreign_key() with delayed matching
130
-
131
- ## 1.2.5 (2026-03-06)
132
-
133
- ### Fix
134
-
135
- - **examples,docs**: fix PGVECTOR type definition and documentation errors
136
- - **types**: fix JSON/JSONB field containment query generating wrong SQL
137
-
138
- ## 1.2.4 (2026-02-28)
139
-
140
- ### Fix
141
-
142
- - handle nested Q objects in Q._to_sqlalchemy
143
-
144
- ### Refactor
145
-
146
- - **relationships**: overhaul relationship resolution and prefetch system
147
-
148
- ## 1.2.3 (2026-02-26)
149
-
150
- ### Fix
151
-
152
- - resolve PostgreSQL test failures and cross-test data pollution
153
- - **executor**: add overloads to execute() and fix iterator type narrowing
154
- - **queryset**: replace non-existent executor.session with _get_session()
155
- - enhance exception handling to surface detailed SQLAlchemy errors
156
-
157
- ### Refactor
158
-
159
- - **metadata**: simplify index handling and config parsing
160
-
161
- ## 1.2.2 (2026-02-26)
162
-
163
- ### Fix
164
-
165
- - clone Column descriptor per subclass to prevent shared ColumnAttribute binding
166
-
167
- ## 1.2.1 (2026-02-25)
168
-
169
- ### Refactor
170
-
171
- - centralize session resolution in get_session()
172
-
173
- ## 1.2.0 (2026-02-25)
174
-
175
- ### Feat
176
-
177
- - **metadata**: improve constraint and index naming conventions
178
-
179
- ## 1.1.0 (2026-02-14)
180
-
181
- ### Feat
182
-
183
- - update custom field type imports to use sqlobjects.fields.types
184
- - implement CTE (Common Table Expressions) support
185
- - add support for SQL window functions
186
- - add EXPLAIN support with dialect-based architecture
187
-
188
- ### Fix
189
-
190
- - update test imports to use DeferredObject instead of DeferredFieldProxy
191
-
192
- ## 1.0.16 (2025-11-18)
193
-
194
- ### Fix
195
-
196
- - correct ModelMixin inheritance
197
-
198
- ## 1.0.15 (2025-11-18)
199
-
200
- ### Feat
201
-
202
- - preserve annotate fields and add serialization options
203
-
204
- ## 1.0.14 (2025-11-18)
205
-
206
- ### Feat
207
-
208
- - add has_session() to check explicit session availability
209
-
210
- ## 1.0.13 (2025-11-18)
211
-
212
- ## 1.0.12 (2025-11-18)
213
-
214
- ### Refactor
215
-
216
- - move rules installer to independent scripts
217
-
218
- ## 1.0.11 (2025-11-18)
219
-
220
- ### Feat
221
-
222
- - add AI assistant rules with auto-install support
223
-
224
- ## 1.0.10 (2025-11-17)
225
-
226
- ### Feat
227
-
228
- - support Model class in join methods for cleaner API
229
-
230
- ## 1.0.9 (2025-11-14)
231
-
232
- ### Feat
233
-
234
- - add optional tables parameter to create_tables/drop_tables
235
-
236
- ## 1.0.8 (2025-11-11)
237
-
238
- ### Feat
239
-
240
- - add model-level relationship loading methods
241
- - improve relation field type inference
242
- - refactor relationship proxies
243
-
244
- ## 1.0.7 (2025-10-14)
245
-
246
- ### Feat
247
-
248
- - add upsert support for PostgreSQL
249
-
250
- ### Fix
251
-
252
- - identity support for PostgreSQL
253
-
254
- ### Refactor
255
-
256
- - consolidate bulk and queryset logic
257
-
258
- ### Perf
259
-
260
- - improve bulk delete performance
261
-
262
- ## 1.0.6 (2025-10-08)
263
-
264
- ### Feat
265
-
266
- - optimize field cache and state manager
267
- - implement relationship prefetch support
268
- - add kwargs parameter support to filter/exclude/get methods
269
-
270
- ### Refactor
271
-
272
- - unify cascade for model and queryset operations
273
-
274
- ## 1.0.5 (2025-09-25)
275
-
276
- ### Fix
277
-
278
- - generate DDL using column definition order
279
-
280
- ## 1.0.4 (2025-09-25)
281
-
282
- ### Feat
283
-
284
- - remove unnecessary exception catching
285
- - implement insert or update using database upsert
286
-
287
- ### Fix
288
-
289
- - use pk column name instead of column instance for pgsql upsert
290
-
291
- ### Refactor
292
-
293
- - move field default value related methods to DataConversionMixin
294
-
295
- ## 1.0.3 (2025-09-25)
296
-
297
- ### Fix
298
-
299
- - field default/default_factory not working
300
-
301
- ## 1.0.2 (2025-09-24)
302
-
303
- ### Feat
304
-
305
- - add type support for StringColumn
306
- - add support for cascade delete in relationships
307
- - add cascade support to relationship fields
308
- - add type checking for __registry__
309
- - use base model to create database tables
310
- - init public commit
311
-
312
- ### Fix
313
-
314
- - foreign key type inference issue
@@ -1,4 +0,0 @@
1
- sqlalchemy[asyncio]>=2.0.44
2
-
3
- [migrations]
4
- alembic>=1.16.5
File without changes
File without changes