lenapi 0.1.4.2__tar.gz → 0.1.4.4__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 (52) hide show
  1. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/PKG-INFO +80 -45
  2. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/README.md +79 -44
  3. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/__init__.py +3 -2
  4. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/application.py +83 -6
  5. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/auth.py +105 -20
  6. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/authentication.py +62 -4
  7. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/cli.py +224 -2
  8. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/model.py +2 -1
  9. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/models.py +415 -20
  10. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/security.py +245 -28
  11. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi.egg-info/PKG-INFO +80 -45
  12. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/pyproject.toml +1 -1
  13. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/tests/test_framework_features.py +156 -0
  14. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/tests/test_security_patch.py +49 -2
  15. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/tests/test_user_model_extension.py +24 -0
  16. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/LICENSE +0 -0
  17. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/admin.py +0 -0
  18. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/authorization.py +0 -0
  19. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/background.py +0 -0
  20. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/concurrency.py +0 -0
  21. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/database.py +0 -0
  22. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/dependencies.py +0 -0
  23. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/docs_guard.py +0 -0
  24. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/logging.py +0 -0
  25. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/middleware.py +0 -0
  26. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/mongodb.py +0 -0
  27. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/openapi.py +0 -0
  28. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/parameters.py +0 -0
  29. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/project.py +0 -0
  30. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/request.py +0 -0
  31. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/response.py +0 -0
  32. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/security_store.py +0 -0
  33. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/sentinels.py +0 -0
  34. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/service.py +0 -0
  35. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/throttling.py +0 -0
  36. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi/transaction.py +0 -0
  37. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi.egg-info/SOURCES.txt +0 -0
  38. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi.egg-info/dependency_links.txt +0 -0
  39. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi.egg-info/entry_points.txt +0 -0
  40. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi.egg-info/requires.txt +0 -0
  41. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi.egg-info/top_level.txt +0 -0
  42. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/lenapi_bootstrap.py +0 -0
  43. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/setup.cfg +0 -0
  44. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/tests/test_admin_console.py +0 -0
  45. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/tests/test_cli_settings_recovery.py +0 -0
  46. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/tests/test_docs_guard.py +0 -0
  47. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/tests/test_media_upload.py +0 -0
  48. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/tests/test_mongodb.py +0 -0
  49. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/tests/test_platform_services.py +0 -0
  50. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/tests/test_project_isolation.py +0 -0
  51. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/tests/test_sentinels.py +0 -0
  52. {lenapi-0.1.4.2 → lenapi-0.1.4.4}/tests/test_throttle.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lenapi
3
- Version: 0.1.4.2
3
+ Version: 0.1.4.4
4
4
  Summary: A modern ASGI framework with Pydantic validation, sync and async database access, WebSockets, authentication, and integrated API documentation.
5
5
  Author: Maekandex Communication Limitation
6
6
  Author-email: "Ifeanyi M. Onovo" <ifeanyi@maekandex.com.ng>
@@ -1471,6 +1471,8 @@ def oidc_profile(identity=Depends(provider_auth)):
1471
1471
  ```python
1472
1472
  # settings.py — replace with the exact origin serving your frontend.
1473
1473
  SOCIAL_AUTH_ALLOWED_ORIGINS = ["https://myapp.com"]
1474
+ SOCIAL_AUTH_SUCCESS_CALLBACK = "https://api.example.com/auth/social/success"
1475
+ FRONTEND_REDIRECT_URI = "https://app.example.com/login/success"
1474
1476
 
1475
1477
  # main.py
1476
1478
  from lenapi import LENAPI
@@ -1479,7 +1481,7 @@ from lenapi.security import SocialAuth
1479
1481
  auth = SocialAuth(
1480
1482
  providers=["google", "github", "linkedin"],
1481
1483
  auto_register=True,
1482
- jwt_enabled=True,
1484
+ jwt_enabled=False, # Your success endpoint owns session/JWT issuance.
1483
1485
  )
1484
1486
 
1485
1487
  app = LENAPI()
@@ -1492,23 +1494,38 @@ This mounts routes such as `/auth/google/login` and `/auth/google/callback` only
1492
1494
  2. The provider authenticates the person and redirects the browser to the registered callback URL.
1493
1495
  3. LenAPI validates OAuth state (and PKCE where supported), exchanges the authorization code, and fetches the provider profile.
1494
1496
  4. With `auto_register=True`, LenAPI finds or creates the local user and stores the provider-to-user mapping.
1495
- 5. With `jwt_enabled=True`, LenAPI issues **one LenAPI JWT access token** for use on protected application routes.
1497
+ 5. LenAPI sends the verified identity to `SOCIAL_AUTH_SUCCESS_CALLBACK`; your backend applies its account rules and handles session/JWT issuance.
1496
1498
 
1497
- `jwt_enabled` controls only that final LenAPI credential. SocialAuth currently issues a JWT access token; it does not issue an API key, session cookie, opaque bearer token, or refresh token. The provider's OAuth access token is used internally during the callback and is not returned to the client. With `jwt_enabled=False`, the callback response contains the provider `identity` and includes `user_id` when a local user was resolved, but no LenAPI token. For sessions, API keys, or opaque tokens, implement the desired credential issuance after the provider callback using the matching LenAPI auth dependency/store, or build a custom callback flow. Google and LinkedIn use OIDC identity endpoints in this integration; GitHub uses OAuth 2.0 and its profile/email APIs, not OIDC.
1499
+ The provider's OAuth access token is used internally and is never returned. A successful social login requires `SOCIAL_AUTH_SUCCESS_CALLBACK`; without it the callback returns a generic `503` and no identity data. The browser callback never returns provider identity or a LenAPI token. `jwt_enabled` remains accepted for compatibility but credential issuance belongs to your backend callback. Google and LinkedIn use OIDC identity endpoints in this integration; GitHub uses OAuth 2.0 and its profile/email APIs, not OIDC.
1498
1500
 
1499
- For example, with both flags enabled, the callback response includes fields in this shape (identity claims vary by provider):
1501
+ To keep provider identity out of the browser response and let your backend own login/session handling, configure `SOCIAL_AUTH_SUCCESS_CALLBACK`. LenAPI validates the provider callback and POSTs the verified identity as JSON to your backend. After any successful webhook response, LenAPI redirects the callback tab to `FRONTEND_REDIRECT_URI`; the webhook may optionally return JSON containing `redirect_url` to override that setting for this login. LenAPI forwards any `Set-Cookie` headers from the webhook response. The configured callback URL and redirect URL must use HTTPS; HTTP is accepted only for localhost development. Redirect URLs may not include query strings or fragments. When callback mode is enabled, your backend owns JWT/session issuance; `jwt_enabled` does not cause LenAPI to create or return a JWT.
1500
1502
 
1501
- ```json
1502
- {
1503
- "identity": {"sub": "provider-subject", "email": "ada@example.com"},
1504
- "user_id": 42,
1505
- "access_token": "<LenAPI JWT>",
1506
- "token_type": "bearer",
1507
- "expires_in": 3600
1508
- }
1503
+ ```python
1504
+ # Developer backend endpoint (the SOCIAL_AUTH_SUCCESS_CALLBACK URL)
1505
+ from lenapi import JSONResponse, LENAPI, Request
1506
+ import settings
1507
+
1508
+ app = LENAPI()
1509
+
1510
+ @app.post("/auth/social/success")
1511
+ async def social_success(request: Request):
1512
+ data = await request.json()
1513
+ identity = data["identity"]
1514
+ user_id = data.get("user_id")
1515
+
1516
+ # Implement your own account rules and issue your own session/JWT here.
1517
+ user = await find_or_create_user(identity, user_id)
1518
+ session_id = await create_session(user)
1519
+
1520
+ response = JSONResponse({"accepted": True})
1521
+ response.set_cookie(
1522
+ "session_id", session_id, max_age=3600, path="/",
1523
+ httponly=True, secure=True, samesite="lax",
1524
+ )
1525
+ return response
1509
1526
  ```
1510
1527
 
1511
- The client then sends `Authorization: Bearer <access_token>` to routes protected with LenAPI JWT authentication. Store and transmit the token securely; do not use the provider token in place of the LenAPI token.
1528
+ The webhook body is `{"provider": "google", "identity": {...}, "user_id": "..."}`; `user_id` is omitted when auto-registration is disabled. This is a plain HTTPS server-to-server POST; the receiving application is responsible for protecting its endpoint. The backend's `Set-Cookie` is forwarded to the browser with LenAPI's redirect response, so choose cookie domain and frontend/API domains accordingly. The redirect destination comes from the configured `FRONTEND_REDIRECT_URI` or the webhook's optional `redirect_url`, never a browser-supplied URL. The helper functions in the sample are application code, not LenAPI built-ins.
1512
1529
 
1513
1530
  `allowed_origins` can also be passed directly to `SocialAuth`; otherwise it reads `SOCIAL_AUTH_ALLOWED_ORIGINS` from `settings.py`. When a browser sends an `Origin` header to a provider login route, LenApi requires an exact match in this list and returns `403` otherwise. Replace `https://myapp.com` with the exact origin serving your frontend. Top-level navigations can omit `Origin`; those still rely on the required, random, browser-cookie-bound OAuth `state` check on callback. Do not treat the origin allowlist as a replacement for OAuth state validation, HTTPS, or correct provider callback URL registration. The provider callback itself is not checked against the browser `Origin` header because providers may omit it or send a different origin.
1514
1531
 
@@ -1885,11 +1902,17 @@ from lenapi import User, model
1885
1902
 
1886
1903
  class Classroom(model.Model):
1887
1904
  name = model.StringField(max_length=120)
1905
+ learners = model.OneToManyField("Learner", foreign_key="classroom_id")
1888
1906
 
1889
1907
  class Student(model.Model):
1890
1908
  person_name = model.StringField(max_length=120, unique=True)
1891
1909
  course = model.StringField(max_length=120)
1892
- classroom_id = model.ForeignKeyField("classroom.id", nullable=True, model=model.null)
1910
+ classroom_id = model.ForeignKeyField(
1911
+ Classroom,
1912
+ relation_name="classroom",
1913
+ nullable=True,
1914
+ model=model.null,
1915
+ )
1893
1916
 
1894
1917
  class Course(model.Model):
1895
1918
  name = model.StringField(max_length=120)
@@ -1908,11 +1931,24 @@ class Invoice(model.Model):
1908
1931
  user_id = model.ForeignKeyField("user.id", model=model.protected)
1909
1932
  ```
1910
1933
 
1934
+ `ForeignKeyField` accepts either a model class or the existing `"table.column"` string target. With an `_id` field name, LenAPI resolves its related object through the matching attribute (for example, `student.classroom`). Use `relation_name` when you want to choose that attribute explicitly. `.special()` accepts either the foreign-key column name or relation name and returns the related model through that name:
1935
+
1936
+ ```python
1937
+ student = Student.get(id=student_id).special("classroom")
1938
+ print(student.classroom.name)
1939
+
1940
+ # The original string target remains supported:
1941
+ class LegacyStudent(model.Model):
1942
+ classroom_id = model.ForeignKeyField("classroom.id", relation_name="classroom")
1943
+ ```
1944
+
1911
1945
  Table names are inferred from model class names in lowercase (`Student` becomes `student`); no table-name declaration is needed. Import `model` from `lenapi` and access the model base class, fields, and relationship behaviors through it, such as `model.Model`, `model.StringField`, and `model.ForeignKeyField`.
1912
1946
 
1913
1947
  `model.Model` is the base class for SQL-backed models. Subclass it to declare a table; each field assignment declares a database column, and the framework supplies an integer `id` primary key unless you define one yourself. Field declarations describe storage and database constraints; use Pydantic schemas to validate API input.
1914
1948
 
1915
- The field helpers include `AutoField`, signed `IntegerField` and `BigIntegerField`/`BigIntField`, nonnegative `PositiveIntegerField` and `PositiveBigIntegerField`, `StringField`, `TextField`, `EmailField`, `PhoneField`, `IPField`, `URLField`, `BooleanField`, `FloatField`, `DecimalField`, `DateField`, `TimeField`, `DateTimeField`, `DurationField`, `JSONField`/`Json`, `UUIDField`, `ImageField`, `FileField`, `FileImageField`, `ForeignKeyField`, `OneToOneField`, and `ManyToManyField`. Fields normally default to `nullable=True` and `blank=True`; `BooleanField` defaults to `True`. `JSONField` and its alias `Json` store JSON-compatible Python values. Use a factory such as `default=dict` for a fresh mutable value on each new row:
1949
+ `User` and `AdminUser` are reserved LenAPI model names. If an application declares a separate model with either name, migration stops with guidance to rename the application model before changing the database. Use a distinct name such as `Customer` or `ProjectAdmin`; to extend the built-in user model, subclass LenAPI's `User` without declaring a separate table.
1950
+
1951
+ The field helpers include `AutoField`, signed `IntegerField` and `BigIntegerField`/`BigIntField`, nonnegative `PositiveIntegerField` and `PositiveBigIntegerField`, `StringField`, `TextField`, `EmailField`, `PhoneField`, `IPField`, `URLField`, `BooleanField`, `FloatField`, `DecimalField`, `DateField`, `TimeField`, `DateTimeField`, `DurationField`, `JSONField`/`Json`, `UUIDField`, `ImageField`, `FileField`, `FileImageField`, `ForeignKeyField`, `OneToOneField`, `OneToManyField`, and `ManyToManyField`. Fields normally default to `nullable=True` and `blank=True`; `null=` is accepted as an alias for `nullable=`. `BooleanField` defaults to `True`. `JSONField` and its alias `Json` store JSON-compatible Python values. Use a factory such as `default=dict` for a fresh mutable value on each new row:
1916
1952
 
1917
1953
  ```python
1918
1954
  class Student(model.Model):
@@ -2128,13 +2164,11 @@ if classroom is not None:
2128
2164
  print(classroom.name)
2129
2165
  ```
2130
2166
 
2131
- For async code, use the stored foreign-key ID for a second async lookup. `.special()` is a sync helper:
2167
+ Use the async relationship loader to resolve foreign keys and one-to-one fields in a batch:
2132
2168
 
2133
2169
  ```python
2134
- student = await Student.aget(id=1)
2135
- classroom = None
2136
- if student is not None and student.classroom_id is not None:
2137
- classroom = await Classroom.aget(id=student.classroom_id)
2170
+ student = await Student.afilter(id=1).special("classroom_id").all()
2171
+ classroom = student[0].classroom_id if student else None
2138
2172
  ```
2139
2173
 
2140
2174
  For `ManyToManyField`, the related collection is available as an attribute. In sync code, call `.all()` to get its related model instances:
@@ -2147,30 +2181,30 @@ courses = teacher.courses.all()
2147
2181
  print([course.name for course in courses])
2148
2182
  ```
2149
2183
 
2150
- In async routes, eager-load the collection with SQLAlchemy's `selectinload` and the injected `AsyncSession` before reading it. Direct lazy access would try to perform database I/O during ordinary attribute access:
2184
+ In async routes, use `.amany()` on loaded rows or `.many(...).all()` on the query. LenAPI eagerly loads the collection for you:
2151
2185
 
2152
2186
  ```python
2153
- from sqlalchemy import select
2154
- from sqlalchemy.ext.asyncio import AsyncSession
2155
- from sqlalchemy.orm import selectinload
2156
- from lenapi import HTTPException
2157
- from app.models import Teacher
2187
+ teachers = await Teacher.afilter(id=1).many("courses").all()
2188
+ courses = teachers[0].courses.all() if teachers else []
2189
+ ```
2158
2190
 
2159
- @app.get("/teachers/{teacher_id}/courses")
2160
- async def teacher_courses(teacher_id: int, db: AsyncSession):
2161
- result = await db.scalars(
2162
- select(Teacher)
2163
- .options(selectinload(Teacher.courses))
2164
- .where(Teacher.id == teacher_id)
2165
- )
2166
- teacher = result.one_or_none()
2167
- if teacher is None:
2168
- raise HTTPException(404, "Teacher not found")
2169
- return [{"id": course.id, "name": course.name}
2170
- for course in teacher.courses.all()]
2191
+ Declare the relationships in `app/models.py` and run `python lenora.py migration` before querying them. For one-to-many collections, declare `OneToManyField` on the parent and use `.batch()` / `.abatch()`. Sync and async filter and get-all queries support these loaders:
2192
+
2193
+ ```python
2194
+ class Classroom(model.Model):
2195
+ learners = model.OneToManyField("Learner", foreign_key="classroom_id")
2196
+
2197
+ # Sync filtered query and all-row query
2198
+ rooms = Classroom.filter(name="Room A").batch("learners").all()
2199
+ all_rooms = Classroom.get.all().batch("learners")
2200
+
2201
+ # Async equivalents
2202
+ rooms = await Classroom.afilter(name="Room A").batch("learners").all()
2203
+ all_rooms = await Classroom.aget.all()
2204
+ all_rooms = await all_rooms.abatch("learners")
2171
2205
  ```
2172
2206
 
2173
- Declare the relationships in `app/models.py` and run `python lenora.py migration` before querying them. Async relationship loading requires `ACTIVATE_ASYNC = True` and the matching async driver.
2207
+ Use `.special("foreign_key")` for a foreign-key or one-to-one relation, `.many("collection")` for a many-to-many collection, and `.batch("collection")` for a one-to-many collection. Their async counterparts are `.aspecial()`, `.amany()`, and `.abatch()` when loading an already retrieved list. Async relationship loading requires `ACTIVATE_ASYNC = True` and the matching async driver.
2174
2208
 
2175
2209
  `filter(...)` accepts equality filters and lookups such as `course__icontains="py"`, `id__gte=10`, `id__in=[1, 2]`, and `classroom_id__isnull=True`. Supported lookup suffixes are `exact`, `iexact`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `notin`, `contains`, `icontains`, `startswith`, `istartswith`, `endswith`, `iendswith`, and `isnull`. Query methods include `.values(...)`, `.order(field)` (prefix with `-` for descending), `.limit(n)`, `.offset(n)`, and terminal operations `.all()`, `.first()`, `.one_or_none()`, `.count()`, `.aggregate(...)`, and `.delete()`. Async query builders use `afilter()`, `asearch()`, and `asearch_any()`; await terminal methods such as `.all()`, `.get()`, `.count()`, `.aggregate()`, or `.delete()`.
2176
2210
 
@@ -2329,7 +2363,7 @@ classroom_name = student.classroom_id.name
2329
2363
 
2330
2364
  Here, the field name must be a `ForeignKeyField` targeting a registered lenApi model. The value at `student.classroom_id` is the related model instance; the project example defines this as `classroom_id`.
2331
2365
 
2332
- Use `OneToOneField` when a dependent row must have exactly one owner and the owner may have at most one dependent row. It is a foreign key with a database unique constraint. A one-to-many relation uses an ordinary `ForeignKeyField` on the many-side; query matching rows with `filter()`:
2366
+ Use `OneToOneField` when a dependent row must have exactly one owner and the owner may have at most one dependent row. It is a foreign key with a database unique constraint. Use `OneToManyField` on the parent side to expose a child collection; the child still declares the matching `ForeignKeyField`:
2333
2367
 
2334
2368
  ```python
2335
2369
  class Classroom(model.Model):
@@ -2343,15 +2377,16 @@ class LearnerProfile(model.Model):
2343
2377
  learner_id = model.OneToOneField("learner.id", nullable=False)
2344
2378
  biography = model.TextField()
2345
2379
 
2346
- classroom = Classroom.get_or_404(id=1)
2347
- learners = Learner.filter(classroom_id=classroom.id).all()
2380
+ classrooms = Classroom.get(id=1).batch("learners").all()
2381
+ classroom = classrooms[0] if classrooms else None
2382
+ learners = classroom.learners if classroom else []
2348
2383
  learner = Learner.get_or_404(id=1).special("classroom_id")
2349
2384
  print(learner.classroom_id.name)
2350
2385
 
2351
2386
  profile = LearnerProfile.get(learner_id=learner.id).get()
2352
2387
  ```
2353
2388
 
2354
- For many-to-many queries, load the owning model and access its set-like collection. With async routes, await model query methods; use eager loading with SQLAlchemy `selectinload()` when traversing async relationships.
2389
+ For many-to-many queries, load the owning model with `.many("courses")` or `.amany("courses")`, then access its set-like collection. `OneToManyField` collections use `.batch("learners")` or `.abatch("learners")`.
2355
2390
 
2356
2391
  Choose what happens to dependent records when their referenced model is deleted with `model`:
2357
2392
 
@@ -2378,7 +2413,7 @@ teacher.courses.remove(course)
2378
2413
  teacher.save()
2379
2414
  ```
2380
2415
 
2381
- Pass `table_name="teacher_courses"` to `ManyToManyField` to choose the association table name. Use `back_populates="teachers"` to pair it with a reciprocal `teachers = ManyToManyField("Teacher", table_name="teacher_courses", back_populates="courses")` field on `Course`.
2416
+ Pass `table_name="teacher_courses"` to `ManyToManyField` to choose the association table name. Use `back_populates="teachers"` to pair it with a reciprocal `teachers = ManyToManyField("Teacher", table_name="teacher_courses", back_populates="courses")` field on `Course`, or use `related_name="teachers"` to declare a reverse collection from one side.
2382
2417
 
2383
2418
  ```python
2384
2419
  from lenapi import Application, Database
@@ -1419,6 +1419,8 @@ def oidc_profile(identity=Depends(provider_auth)):
1419
1419
  ```python
1420
1420
  # settings.py — replace with the exact origin serving your frontend.
1421
1421
  SOCIAL_AUTH_ALLOWED_ORIGINS = ["https://myapp.com"]
1422
+ SOCIAL_AUTH_SUCCESS_CALLBACK = "https://api.example.com/auth/social/success"
1423
+ FRONTEND_REDIRECT_URI = "https://app.example.com/login/success"
1422
1424
 
1423
1425
  # main.py
1424
1426
  from lenapi import LENAPI
@@ -1427,7 +1429,7 @@ from lenapi.security import SocialAuth
1427
1429
  auth = SocialAuth(
1428
1430
  providers=["google", "github", "linkedin"],
1429
1431
  auto_register=True,
1430
- jwt_enabled=True,
1432
+ jwt_enabled=False, # Your success endpoint owns session/JWT issuance.
1431
1433
  )
1432
1434
 
1433
1435
  app = LENAPI()
@@ -1440,23 +1442,38 @@ This mounts routes such as `/auth/google/login` and `/auth/google/callback` only
1440
1442
  2. The provider authenticates the person and redirects the browser to the registered callback URL.
1441
1443
  3. LenAPI validates OAuth state (and PKCE where supported), exchanges the authorization code, and fetches the provider profile.
1442
1444
  4. With `auto_register=True`, LenAPI finds or creates the local user and stores the provider-to-user mapping.
1443
- 5. With `jwt_enabled=True`, LenAPI issues **one LenAPI JWT access token** for use on protected application routes.
1445
+ 5. LenAPI sends the verified identity to `SOCIAL_AUTH_SUCCESS_CALLBACK`; your backend applies its account rules and handles session/JWT issuance.
1444
1446
 
1445
- `jwt_enabled` controls only that final LenAPI credential. SocialAuth currently issues a JWT access token; it does not issue an API key, session cookie, opaque bearer token, or refresh token. The provider's OAuth access token is used internally during the callback and is not returned to the client. With `jwt_enabled=False`, the callback response contains the provider `identity` and includes `user_id` when a local user was resolved, but no LenAPI token. For sessions, API keys, or opaque tokens, implement the desired credential issuance after the provider callback using the matching LenAPI auth dependency/store, or build a custom callback flow. Google and LinkedIn use OIDC identity endpoints in this integration; GitHub uses OAuth 2.0 and its profile/email APIs, not OIDC.
1447
+ The provider's OAuth access token is used internally and is never returned. A successful social login requires `SOCIAL_AUTH_SUCCESS_CALLBACK`; without it the callback returns a generic `503` and no identity data. The browser callback never returns provider identity or a LenAPI token. `jwt_enabled` remains accepted for compatibility but credential issuance belongs to your backend callback. Google and LinkedIn use OIDC identity endpoints in this integration; GitHub uses OAuth 2.0 and its profile/email APIs, not OIDC.
1446
1448
 
1447
- For example, with both flags enabled, the callback response includes fields in this shape (identity claims vary by provider):
1449
+ To keep provider identity out of the browser response and let your backend own login/session handling, configure `SOCIAL_AUTH_SUCCESS_CALLBACK`. LenAPI validates the provider callback and POSTs the verified identity as JSON to your backend. After any successful webhook response, LenAPI redirects the callback tab to `FRONTEND_REDIRECT_URI`; the webhook may optionally return JSON containing `redirect_url` to override that setting for this login. LenAPI forwards any `Set-Cookie` headers from the webhook response. The configured callback URL and redirect URL must use HTTPS; HTTP is accepted only for localhost development. Redirect URLs may not include query strings or fragments. When callback mode is enabled, your backend owns JWT/session issuance; `jwt_enabled` does not cause LenAPI to create or return a JWT.
1448
1450
 
1449
- ```json
1450
- {
1451
- "identity": {"sub": "provider-subject", "email": "ada@example.com"},
1452
- "user_id": 42,
1453
- "access_token": "<LenAPI JWT>",
1454
- "token_type": "bearer",
1455
- "expires_in": 3600
1456
- }
1451
+ ```python
1452
+ # Developer backend endpoint (the SOCIAL_AUTH_SUCCESS_CALLBACK URL)
1453
+ from lenapi import JSONResponse, LENAPI, Request
1454
+ import settings
1455
+
1456
+ app = LENAPI()
1457
+
1458
+ @app.post("/auth/social/success")
1459
+ async def social_success(request: Request):
1460
+ data = await request.json()
1461
+ identity = data["identity"]
1462
+ user_id = data.get("user_id")
1463
+
1464
+ # Implement your own account rules and issue your own session/JWT here.
1465
+ user = await find_or_create_user(identity, user_id)
1466
+ session_id = await create_session(user)
1467
+
1468
+ response = JSONResponse({"accepted": True})
1469
+ response.set_cookie(
1470
+ "session_id", session_id, max_age=3600, path="/",
1471
+ httponly=True, secure=True, samesite="lax",
1472
+ )
1473
+ return response
1457
1474
  ```
1458
1475
 
1459
- The client then sends `Authorization: Bearer <access_token>` to routes protected with LenAPI JWT authentication. Store and transmit the token securely; do not use the provider token in place of the LenAPI token.
1476
+ The webhook body is `{"provider": "google", "identity": {...}, "user_id": "..."}`; `user_id` is omitted when auto-registration is disabled. This is a plain HTTPS server-to-server POST; the receiving application is responsible for protecting its endpoint. The backend's `Set-Cookie` is forwarded to the browser with LenAPI's redirect response, so choose cookie domain and frontend/API domains accordingly. The redirect destination comes from the configured `FRONTEND_REDIRECT_URI` or the webhook's optional `redirect_url`, never a browser-supplied URL. The helper functions in the sample are application code, not LenAPI built-ins.
1460
1477
 
1461
1478
  `allowed_origins` can also be passed directly to `SocialAuth`; otherwise it reads `SOCIAL_AUTH_ALLOWED_ORIGINS` from `settings.py`. When a browser sends an `Origin` header to a provider login route, LenApi requires an exact match in this list and returns `403` otherwise. Replace `https://myapp.com` with the exact origin serving your frontend. Top-level navigations can omit `Origin`; those still rely on the required, random, browser-cookie-bound OAuth `state` check on callback. Do not treat the origin allowlist as a replacement for OAuth state validation, HTTPS, or correct provider callback URL registration. The provider callback itself is not checked against the browser `Origin` header because providers may omit it or send a different origin.
1462
1479
 
@@ -1833,11 +1850,17 @@ from lenapi import User, model
1833
1850
 
1834
1851
  class Classroom(model.Model):
1835
1852
  name = model.StringField(max_length=120)
1853
+ learners = model.OneToManyField("Learner", foreign_key="classroom_id")
1836
1854
 
1837
1855
  class Student(model.Model):
1838
1856
  person_name = model.StringField(max_length=120, unique=True)
1839
1857
  course = model.StringField(max_length=120)
1840
- classroom_id = model.ForeignKeyField("classroom.id", nullable=True, model=model.null)
1858
+ classroom_id = model.ForeignKeyField(
1859
+ Classroom,
1860
+ relation_name="classroom",
1861
+ nullable=True,
1862
+ model=model.null,
1863
+ )
1841
1864
 
1842
1865
  class Course(model.Model):
1843
1866
  name = model.StringField(max_length=120)
@@ -1856,11 +1879,24 @@ class Invoice(model.Model):
1856
1879
  user_id = model.ForeignKeyField("user.id", model=model.protected)
1857
1880
  ```
1858
1881
 
1882
+ `ForeignKeyField` accepts either a model class or the existing `"table.column"` string target. With an `_id` field name, LenAPI resolves its related object through the matching attribute (for example, `student.classroom`). Use `relation_name` when you want to choose that attribute explicitly. `.special()` accepts either the foreign-key column name or relation name and returns the related model through that name:
1883
+
1884
+ ```python
1885
+ student = Student.get(id=student_id).special("classroom")
1886
+ print(student.classroom.name)
1887
+
1888
+ # The original string target remains supported:
1889
+ class LegacyStudent(model.Model):
1890
+ classroom_id = model.ForeignKeyField("classroom.id", relation_name="classroom")
1891
+ ```
1892
+
1859
1893
  Table names are inferred from model class names in lowercase (`Student` becomes `student`); no table-name declaration is needed. Import `model` from `lenapi` and access the model base class, fields, and relationship behaviors through it, such as `model.Model`, `model.StringField`, and `model.ForeignKeyField`.
1860
1894
 
1861
1895
  `model.Model` is the base class for SQL-backed models. Subclass it to declare a table; each field assignment declares a database column, and the framework supplies an integer `id` primary key unless you define one yourself. Field declarations describe storage and database constraints; use Pydantic schemas to validate API input.
1862
1896
 
1863
- The field helpers include `AutoField`, signed `IntegerField` and `BigIntegerField`/`BigIntField`, nonnegative `PositiveIntegerField` and `PositiveBigIntegerField`, `StringField`, `TextField`, `EmailField`, `PhoneField`, `IPField`, `URLField`, `BooleanField`, `FloatField`, `DecimalField`, `DateField`, `TimeField`, `DateTimeField`, `DurationField`, `JSONField`/`Json`, `UUIDField`, `ImageField`, `FileField`, `FileImageField`, `ForeignKeyField`, `OneToOneField`, and `ManyToManyField`. Fields normally default to `nullable=True` and `blank=True`; `BooleanField` defaults to `True`. `JSONField` and its alias `Json` store JSON-compatible Python values. Use a factory such as `default=dict` for a fresh mutable value on each new row:
1897
+ `User` and `AdminUser` are reserved LenAPI model names. If an application declares a separate model with either name, migration stops with guidance to rename the application model before changing the database. Use a distinct name such as `Customer` or `ProjectAdmin`; to extend the built-in user model, subclass LenAPI's `User` without declaring a separate table.
1898
+
1899
+ The field helpers include `AutoField`, signed `IntegerField` and `BigIntegerField`/`BigIntField`, nonnegative `PositiveIntegerField` and `PositiveBigIntegerField`, `StringField`, `TextField`, `EmailField`, `PhoneField`, `IPField`, `URLField`, `BooleanField`, `FloatField`, `DecimalField`, `DateField`, `TimeField`, `DateTimeField`, `DurationField`, `JSONField`/`Json`, `UUIDField`, `ImageField`, `FileField`, `FileImageField`, `ForeignKeyField`, `OneToOneField`, `OneToManyField`, and `ManyToManyField`. Fields normally default to `nullable=True` and `blank=True`; `null=` is accepted as an alias for `nullable=`. `BooleanField` defaults to `True`. `JSONField` and its alias `Json` store JSON-compatible Python values. Use a factory such as `default=dict` for a fresh mutable value on each new row:
1864
1900
 
1865
1901
  ```python
1866
1902
  class Student(model.Model):
@@ -2076,13 +2112,11 @@ if classroom is not None:
2076
2112
  print(classroom.name)
2077
2113
  ```
2078
2114
 
2079
- For async code, use the stored foreign-key ID for a second async lookup. `.special()` is a sync helper:
2115
+ Use the async relationship loader to resolve foreign keys and one-to-one fields in a batch:
2080
2116
 
2081
2117
  ```python
2082
- student = await Student.aget(id=1)
2083
- classroom = None
2084
- if student is not None and student.classroom_id is not None:
2085
- classroom = await Classroom.aget(id=student.classroom_id)
2118
+ student = await Student.afilter(id=1).special("classroom_id").all()
2119
+ classroom = student[0].classroom_id if student else None
2086
2120
  ```
2087
2121
 
2088
2122
  For `ManyToManyField`, the related collection is available as an attribute. In sync code, call `.all()` to get its related model instances:
@@ -2095,30 +2129,30 @@ courses = teacher.courses.all()
2095
2129
  print([course.name for course in courses])
2096
2130
  ```
2097
2131
 
2098
- In async routes, eager-load the collection with SQLAlchemy's `selectinload` and the injected `AsyncSession` before reading it. Direct lazy access would try to perform database I/O during ordinary attribute access:
2132
+ In async routes, use `.amany()` on loaded rows or `.many(...).all()` on the query. LenAPI eagerly loads the collection for you:
2099
2133
 
2100
2134
  ```python
2101
- from sqlalchemy import select
2102
- from sqlalchemy.ext.asyncio import AsyncSession
2103
- from sqlalchemy.orm import selectinload
2104
- from lenapi import HTTPException
2105
- from app.models import Teacher
2135
+ teachers = await Teacher.afilter(id=1).many("courses").all()
2136
+ courses = teachers[0].courses.all() if teachers else []
2137
+ ```
2106
2138
 
2107
- @app.get("/teachers/{teacher_id}/courses")
2108
- async def teacher_courses(teacher_id: int, db: AsyncSession):
2109
- result = await db.scalars(
2110
- select(Teacher)
2111
- .options(selectinload(Teacher.courses))
2112
- .where(Teacher.id == teacher_id)
2113
- )
2114
- teacher = result.one_or_none()
2115
- if teacher is None:
2116
- raise HTTPException(404, "Teacher not found")
2117
- return [{"id": course.id, "name": course.name}
2118
- for course in teacher.courses.all()]
2139
+ Declare the relationships in `app/models.py` and run `python lenora.py migration` before querying them. For one-to-many collections, declare `OneToManyField` on the parent and use `.batch()` / `.abatch()`. Sync and async filter and get-all queries support these loaders:
2140
+
2141
+ ```python
2142
+ class Classroom(model.Model):
2143
+ learners = model.OneToManyField("Learner", foreign_key="classroom_id")
2144
+
2145
+ # Sync filtered query and all-row query
2146
+ rooms = Classroom.filter(name="Room A").batch("learners").all()
2147
+ all_rooms = Classroom.get.all().batch("learners")
2148
+
2149
+ # Async equivalents
2150
+ rooms = await Classroom.afilter(name="Room A").batch("learners").all()
2151
+ all_rooms = await Classroom.aget.all()
2152
+ all_rooms = await all_rooms.abatch("learners")
2119
2153
  ```
2120
2154
 
2121
- Declare the relationships in `app/models.py` and run `python lenora.py migration` before querying them. Async relationship loading requires `ACTIVATE_ASYNC = True` and the matching async driver.
2155
+ Use `.special("foreign_key")` for a foreign-key or one-to-one relation, `.many("collection")` for a many-to-many collection, and `.batch("collection")` for a one-to-many collection. Their async counterparts are `.aspecial()`, `.amany()`, and `.abatch()` when loading an already retrieved list. Async relationship loading requires `ACTIVATE_ASYNC = True` and the matching async driver.
2122
2156
 
2123
2157
  `filter(...)` accepts equality filters and lookups such as `course__icontains="py"`, `id__gte=10`, `id__in=[1, 2]`, and `classroom_id__isnull=True`. Supported lookup suffixes are `exact`, `iexact`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `notin`, `contains`, `icontains`, `startswith`, `istartswith`, `endswith`, `iendswith`, and `isnull`. Query methods include `.values(...)`, `.order(field)` (prefix with `-` for descending), `.limit(n)`, `.offset(n)`, and terminal operations `.all()`, `.first()`, `.one_or_none()`, `.count()`, `.aggregate(...)`, and `.delete()`. Async query builders use `afilter()`, `asearch()`, and `asearch_any()`; await terminal methods such as `.all()`, `.get()`, `.count()`, `.aggregate()`, or `.delete()`.
2124
2158
 
@@ -2277,7 +2311,7 @@ classroom_name = student.classroom_id.name
2277
2311
 
2278
2312
  Here, the field name must be a `ForeignKeyField` targeting a registered lenApi model. The value at `student.classroom_id` is the related model instance; the project example defines this as `classroom_id`.
2279
2313
 
2280
- Use `OneToOneField` when a dependent row must have exactly one owner and the owner may have at most one dependent row. It is a foreign key with a database unique constraint. A one-to-many relation uses an ordinary `ForeignKeyField` on the many-side; query matching rows with `filter()`:
2314
+ Use `OneToOneField` when a dependent row must have exactly one owner and the owner may have at most one dependent row. It is a foreign key with a database unique constraint. Use `OneToManyField` on the parent side to expose a child collection; the child still declares the matching `ForeignKeyField`:
2281
2315
 
2282
2316
  ```python
2283
2317
  class Classroom(model.Model):
@@ -2291,15 +2325,16 @@ class LearnerProfile(model.Model):
2291
2325
  learner_id = model.OneToOneField("learner.id", nullable=False)
2292
2326
  biography = model.TextField()
2293
2327
 
2294
- classroom = Classroom.get_or_404(id=1)
2295
- learners = Learner.filter(classroom_id=classroom.id).all()
2328
+ classrooms = Classroom.get(id=1).batch("learners").all()
2329
+ classroom = classrooms[0] if classrooms else None
2330
+ learners = classroom.learners if classroom else []
2296
2331
  learner = Learner.get_or_404(id=1).special("classroom_id")
2297
2332
  print(learner.classroom_id.name)
2298
2333
 
2299
2334
  profile = LearnerProfile.get(learner_id=learner.id).get()
2300
2335
  ```
2301
2336
 
2302
- For many-to-many queries, load the owning model and access its set-like collection. With async routes, await model query methods; use eager loading with SQLAlchemy `selectinload()` when traversing async relationships.
2337
+ For many-to-many queries, load the owning model with `.many("courses")` or `.amany("courses")`, then access its set-like collection. `OneToManyField` collections use `.batch("learners")` or `.abatch("learners")`.
2303
2338
 
2304
2339
  Choose what happens to dependent records when their referenced model is deleted with `model`:
2305
2340
 
@@ -2326,7 +2361,7 @@ teacher.courses.remove(course)
2326
2361
  teacher.save()
2327
2362
  ```
2328
2363
 
2329
- Pass `table_name="teacher_courses"` to `ManyToManyField` to choose the association table name. Use `back_populates="teachers"` to pair it with a reciprocal `teachers = ManyToManyField("Teacher", table_name="teacher_courses", back_populates="courses")` field on `Course`.
2364
+ Pass `table_name="teacher_courses"` to `ManyToManyField` to choose the association table name. Use `back_populates="teachers"` to pair it with a reciprocal `teachers = ManyToManyField("Teacher", table_name="teacher_courses", back_populates="courses")` field on `Course`, or use `related_name="teachers"` to declare a reverse collection from one side.
2330
2365
 
2331
2366
  ```python
2332
2367
  from lenapi import Application, Database
@@ -8,7 +8,7 @@ if sys.version_info < (3, 11):
8
8
  "on 2026-10-01 and is no longer supported."
9
9
  )
10
10
 
11
- __version__ = "0.1.4.2"
11
+ __version__ = "0.1.4.4"
12
12
 
13
13
  from .application import Application, LENAPI, Router
14
14
  from .background import BackgroundQueue, BackgroundTasks
@@ -46,6 +46,7 @@ from .models import (
46
46
  PositiveIntegerField,
47
47
  JSONField,
48
48
  ManyToManyField,
49
+ OneToManyField,
49
50
  OneToOneField,
50
51
  Max,
51
52
  Min,
@@ -98,6 +99,6 @@ from . import model
98
99
  __all__ = [
99
100
  "Application", "LENAPI", "Router", "Depends", "BackgroundTasks", "BackgroundQueue", "Cache", "Faker", "OpenAI", "Ollama", "CORSMiddleware", "DocsAuthMiddleware", "GZipMiddleware", "RequestIDMiddleware", "TimingMiddleware", "require_role", "require_permission", "require_owner", "Database", "AsyncDatabase", "transaction", "MongoDatabase", "MongoDocument", "MultipleDocumentsFound", "Body", "File", "Model", "AdminUser", "AutoField", "logger", "get_logger", "WebSocket", "WebSocketConnection", "WebSocketDisconnect", "WebSocketService",
100
101
  "IntegerField", "PositiveIntegerField", "BigIntField", "BigIntegerField", "PositiveBigIntegerField", "DecimalField", "StringField", "EmailField", "IPField", "PhoneField", "TextField", "UUIDField", "ImageField", "FileField", "FileImageField", "URLField", "BooleanField", "FloatField", "User",
101
- "DateTimeField", "DateField", "TimeField", "DurationField", "JSONField", "ForeignKeyField", "OneToOneField", "ManyToManyField", "Count", "Sum", "Min", "Max", "Avg", "Request", "UploadFile", "Response", "JSONResponse",
102
+ "DateTimeField", "DateField", "TimeField", "DurationField", "JSONField", "ForeignKeyField", "OneToOneField", "OneToManyField", "ManyToManyField", "Count", "Sum", "Min", "Max", "Avg", "Request", "UploadFile", "Response", "JSONResponse",
102
103
  "HTTPException", "JWTAuth", "APIKeyAuth", "BasicAuth", "CSRFProtect", "SessionAuth", "OpaqueBearerAuth", "HMACAuth", "OIDCAuth", "WebhookAuth", "hmac_request_signature", "session_auth", "opaque_bearer_auth", "hmac_auth", "oidc_auth", "webhook_auth", "create_authenticator", "authentication", "SocialAuth", "hash_password", "verify_password", "make_password", "check_password", "make_api_key", "hash_api_key", "UNSET", "model", "CASCADE", "SET_NULL", "PROTECT", "cascade", "null", "protected",
103
104
  ]
@@ -14,7 +14,7 @@ from pathlib import Path
14
14
  from typing import Any, get_args
15
15
 
16
16
  from pydantic import BaseModel, TypeAdapter, ValidationError
17
- from sqlalchemy.exc import IntegrityError, MultipleResultsFound
17
+ from sqlalchemy.exc import DBAPIError, IntegrityError, MultipleResultsFound, NoSuchTableError
18
18
  from sqlalchemy.engine import make_url
19
19
  from sqlalchemy.ext.asyncio import AsyncSession
20
20
 
@@ -50,6 +50,63 @@ from .sentinels import UNSET
50
50
  logger = get_logger("websocket")
51
51
 
52
52
 
53
+ def _is_missing_table_error(exc: BaseException) -> bool:
54
+ """Recognize common missing-table errors without exposing database details."""
55
+ current: BaseException | None = exc
56
+ seen: set[int] = set()
57
+ while current is not None and id(current) not in seen:
58
+ seen.add(id(current))
59
+ if isinstance(current, NoSuchTableError):
60
+ return True
61
+ if isinstance(current, DBAPIError):
62
+ original = current.orig
63
+ code = getattr(original, "sqlstate", None) or getattr(original, "pgcode", None)
64
+ args = getattr(original, "args", ())
65
+ if code == "42P01" or (args and args[0] == 1146):
66
+ return True
67
+ message = str(original).lower()
68
+ if any(marker in message for marker in (
69
+ "no such table", "undefined table", "doesn't exist", "does not exist",
70
+ )):
71
+ return True
72
+ current = current.__cause__ or current.__context__
73
+ return False
74
+
75
+
76
+ def _database_type_mismatch_detail(exc: BaseException) -> str | None:
77
+ """Return a safe validation hint for PostgreSQL integer/string comparisons."""
78
+ current: BaseException | None = exc
79
+ seen: set[int] = set()
80
+ while current is not None and id(current) not in seen:
81
+ seen.add(id(current))
82
+ if isinstance(current, DBAPIError):
83
+ original = current.orig
84
+ code = getattr(original, "sqlstate", None) or getattr(original, "pgcode", None)
85
+ message = str(original).lower()
86
+ type_match = re.search(
87
+ r"(?:operator does not exist:\s*)?"
88
+ r"(smallint|integer|bigint|int2|int4|int8)\s*=\s*"
89
+ r"(character varying|varchar|text)",
90
+ message,
91
+ )
92
+ if code == "42883" or "no operator matches the given name and argument types" in message:
93
+ if type_match:
94
+ statement = current.statement or ""
95
+ field_match = re.search(
96
+ r"(?:\.|\")([A-Za-z_][A-Za-z0-9_]*)\"?\s*=\s*%\(",
97
+ statement,
98
+ )
99
+ field_name = field_match.group(1) if field_match else "value"
100
+ required_type = (
101
+ "int" if type_match.group(1) in {
102
+ "smallint", "integer", "bigint", "int2", "int4", "int8"
103
+ } else "number"
104
+ )
105
+ return f"{field_name} requires {required_type} but received string"
106
+ current = current.__cause__ or current.__context__
107
+ return None
108
+
109
+
53
110
  def _uses_basic_auth(endpoint: Callable, auth: Any) -> bool:
54
111
  """Detect BasicAuth supplied directly or through endpoint dependencies."""
55
112
  from .security import BasicAuth
@@ -689,12 +746,32 @@ class Application(Router):
689
746
  )
690
747
  except DatabaseBackendMismatch as exc:
691
748
  response = JSONResponse({"detail": str(exc)}, status_code=500)
692
- except Exception:
693
- if self.debug:
694
- logger.exception("Unhandled application error for %s %s", method, path)
749
+ except Exception as exc:
750
+ if _is_missing_table_error(exc):
751
+ logger.error(
752
+ "Model or table not found. Check model registration and apply pending migrations."
753
+ )
754
+ response = JSONResponse(
755
+ {
756
+ "detail": (
757
+ "Model or table not found. Check that the model is registered "
758
+ "and its migrations have been applied."
759
+ )
760
+ },
761
+ status_code=500,
762
+ )
763
+ elif type_detail := _database_type_mismatch_detail(exc):
764
+ logger.error(
765
+ "Invalid query value type: %s. Check the request value against the model field type.",
766
+ type_detail,
767
+ )
768
+ response = JSONResponse({"detail": type_detail}, status_code=422)
695
769
  else:
696
- logger.error("Unhandled application error for %s %s", method, path)
697
- response = JSONResponse({"detail": "Internal Server Error"}, status_code=500)
770
+ if self.debug:
771
+ logger.exception("Unhandled application error for %s %s", method, path)
772
+ else:
773
+ logger.error("Unhandled application error for %s %s", method, path)
774
+ response = JSONResponse({"detail": "Internal Server Error"}, status_code=500)
698
775
  finally:
699
776
  reset_current_request(request_token)
700
777
  reset_current_database_backend(database_backend_token)