superfunctions-core 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,513 @@
1
+ """Core type definitions for the database adapter system."""
2
+
3
+ from enum import Enum
4
+ from typing import Any, Dict, List, Literal, Optional, Protocol, Set, TypeVar
5
+
6
+ from pydantic import BaseModel, Field
7
+
8
+ # ============================================================================
9
+ # Enums
10
+ # ============================================================================
11
+
12
+
13
+ class Operator(str, Enum):
14
+ """Query operators."""
15
+
16
+ EQ = "eq"
17
+ NE = "ne"
18
+ GT = "gt"
19
+ GTE = "gte"
20
+ LT = "lt"
21
+ LTE = "lte"
22
+ IN = "in"
23
+ NOT_IN = "not_in"
24
+ LIKE = "like"
25
+ ILIKE = "ilike"
26
+ IS_NULL = "is_null"
27
+ IS_NOT_NULL = "is_not_null"
28
+ CONTAINS = "contains"
29
+ STARTS_WITH = "starts_with"
30
+ ENDS_WITH = "ends_with"
31
+
32
+
33
+ class Direction(str, Enum):
34
+ """Sort direction."""
35
+
36
+ ASC = "asc"
37
+ DESC = "desc"
38
+
39
+
40
+ class TransactionIsolation(str, Enum):
41
+ """Transaction isolation levels."""
42
+
43
+ READ_UNCOMMITTED = "read_uncommitted"
44
+ READ_COMMITTED = "read_committed"
45
+ REPEATABLE_READ = "repeatable_read"
46
+ SERIALIZABLE = "serializable"
47
+
48
+
49
+ # ============================================================================
50
+ # Query Parameters
51
+ # ============================================================================
52
+
53
+
54
+ class WhereClause(BaseModel):
55
+ """Database where clause."""
56
+
57
+ field: str
58
+ operator: Operator = Operator.EQ
59
+ value: Any
60
+ connector: Literal["AND", "OR"] = "AND"
61
+
62
+ class Config:
63
+ use_enum_values = True
64
+
65
+
66
+ class OrderBy(BaseModel):
67
+ """Order by clause."""
68
+
69
+ field: str
70
+ direction: Direction = Direction.ASC
71
+
72
+ class Config:
73
+ use_enum_values = True
74
+
75
+
76
+ class JoinConfig(BaseModel):
77
+ """Join configuration."""
78
+
79
+ model: str
80
+ on: List[WhereClause]
81
+ type: Literal["inner", "left", "right", "full"] = "inner"
82
+ select: Optional[List[str]] = None
83
+
84
+
85
+ # ============================================================================
86
+ # Operation Parameters
87
+ # ============================================================================
88
+
89
+
90
+ class CreateParams(BaseModel):
91
+ """Parameters for create operation."""
92
+
93
+ model: str
94
+ data: Dict[str, Any]
95
+ select: Optional[List[str]] = None
96
+ namespace: Optional[str] = None
97
+
98
+ class Config:
99
+ arbitrary_types_allowed = True
100
+
101
+
102
+ class FindOneParams(BaseModel):
103
+ """Parameters for findOne operation."""
104
+
105
+ model: str
106
+ where: List[WhereClause]
107
+ select: Optional[List[str]] = None
108
+ join: Optional[JoinConfig] = None
109
+ namespace: Optional[str] = None
110
+
111
+ class Config:
112
+ arbitrary_types_allowed = True
113
+
114
+
115
+ class FindManyParams(BaseModel):
116
+ """Parameters for findMany operation."""
117
+
118
+ model: str
119
+ where: Optional[List[WhereClause]] = None
120
+ select: Optional[List[str]] = None
121
+ join: Optional[JoinConfig] = None
122
+ order_by: Optional[List[OrderBy]] = Field(None, alias="orderBy")
123
+ limit: Optional[int] = None
124
+ offset: Optional[int] = None
125
+ namespace: Optional[str] = None
126
+
127
+ class Config:
128
+ populate_by_name = True
129
+ arbitrary_types_allowed = True
130
+
131
+
132
+ class UpdateParams(BaseModel):
133
+ """Parameters for update operation."""
134
+
135
+ model: str
136
+ where: List[WhereClause]
137
+ data: Dict[str, Any]
138
+ select: Optional[List[str]] = None
139
+ namespace: Optional[str] = None
140
+
141
+ class Config:
142
+ arbitrary_types_allowed = True
143
+
144
+
145
+ class DeleteParams(BaseModel):
146
+ """Parameters for delete operation."""
147
+
148
+ model: str
149
+ where: List[WhereClause]
150
+ namespace: Optional[str] = None
151
+
152
+ class Config:
153
+ arbitrary_types_allowed = True
154
+
155
+
156
+ class CreateManyParams(BaseModel):
157
+ """Parameters for createMany operation."""
158
+
159
+ model: str
160
+ data: List[Dict[str, Any]]
161
+ select: Optional[List[str]] = None
162
+ namespace: Optional[str] = None
163
+
164
+ class Config:
165
+ arbitrary_types_allowed = True
166
+
167
+
168
+ class UpdateManyParams(BaseModel):
169
+ """Parameters for updateMany operation."""
170
+
171
+ model: str
172
+ where: List[WhereClause]
173
+ data: Dict[str, Any]
174
+ namespace: Optional[str] = None
175
+
176
+ class Config:
177
+ arbitrary_types_allowed = True
178
+
179
+
180
+ class DeleteManyParams(BaseModel):
181
+ """Parameters for deleteMany operation."""
182
+
183
+ model: str
184
+ where: List[WhereClause]
185
+ namespace: Optional[str] = None
186
+
187
+ class Config:
188
+ arbitrary_types_allowed = True
189
+
190
+
191
+ class UpsertParams(BaseModel):
192
+ """Parameters for upsert operation."""
193
+
194
+ model: str
195
+ where: List[WhereClause]
196
+ create: Dict[str, Any]
197
+ update: Dict[str, Any]
198
+ select: Optional[List[str]] = None
199
+ namespace: Optional[str] = None
200
+
201
+ class Config:
202
+ arbitrary_types_allowed = True
203
+
204
+
205
+ class CountParams(BaseModel):
206
+ """Parameters for count operation."""
207
+
208
+ model: str
209
+ where: Optional[List[WhereClause]] = None
210
+ namespace: Optional[str] = None
211
+
212
+ class Config:
213
+ arbitrary_types_allowed = True
214
+
215
+
216
+ # ============================================================================
217
+ # Schema Management
218
+ # ============================================================================
219
+
220
+
221
+ class FieldType(str, Enum):
222
+ """Database field types."""
223
+
224
+ STRING = "string"
225
+ TEXT = "text"
226
+ INTEGER = "integer"
227
+ BIGINT = "bigint"
228
+ FLOAT = "float"
229
+ DECIMAL = "decimal"
230
+ BOOLEAN = "boolean"
231
+ DATE = "date"
232
+ DATETIME = "datetime"
233
+ TIMESTAMP = "timestamp"
234
+ JSON = "json"
235
+ JSONB = "jsonb"
236
+ BINARY = "binary"
237
+ UUID = "uuid"
238
+
239
+
240
+ class FieldSchema(BaseModel):
241
+ """Field schema definition."""
242
+
243
+ name: str
244
+ type: FieldType
245
+ nullable: bool = False
246
+ default: Optional[Any] = None
247
+ primary_key: bool = Field(False, alias="primaryKey")
248
+ auto_increment: bool = Field(False, alias="autoIncrement")
249
+ unique: bool = False
250
+ index: bool = False
251
+ references: Optional[str] = None
252
+ on_delete: Optional[Literal["cascade", "set_null", "restrict"]] = Field(None, alias="onDelete")
253
+ on_update: Optional[Literal["cascade", "set_null", "restrict"]] = Field(None, alias="onUpdate")
254
+
255
+ class Config:
256
+ populate_by_name = True
257
+
258
+
259
+ class IndexSchema(BaseModel):
260
+ """Index schema definition."""
261
+
262
+ name: str
263
+ fields: List[str]
264
+ unique: bool = False
265
+
266
+
267
+ class ConstraintSchema(BaseModel):
268
+ """Constraint schema definition."""
269
+
270
+ name: str
271
+ type: Literal["unique", "check", "foreign_key"]
272
+ fields: List[str]
273
+ check: Optional[str] = None
274
+ references: Optional[str] = None
275
+
276
+
277
+ class TableSchema(BaseModel):
278
+ """Table schema definition."""
279
+
280
+ name: str
281
+ fields: List[FieldSchema]
282
+ indexes: Optional[List[IndexSchema]] = None
283
+ constraints: Optional[List[ConstraintSchema]] = None
284
+ namespace: Optional[str] = None
285
+
286
+
287
+ class ValidationResult(BaseModel):
288
+ """Schema validation result."""
289
+
290
+ valid: bool
291
+ errors: List[str] = Field(default_factory=list)
292
+ warnings: List[str] = Field(default_factory=list)
293
+
294
+
295
+ class CreateSchemaParams(BaseModel):
296
+ """Parameters for schema creation."""
297
+
298
+ tables: List[TableSchema]
299
+ drop_existing: bool = Field(False, alias="dropExisting")
300
+
301
+ class Config:
302
+ populate_by_name = True
303
+
304
+
305
+ class SchemaCreation(BaseModel):
306
+ """Result of schema creation."""
307
+
308
+ success: bool
309
+ sql: Optional[str] = None
310
+ errors: List[str] = Field(default_factory=list)
311
+
312
+
313
+ # ============================================================================
314
+ # Health & Capabilities
315
+ # ============================================================================
316
+
317
+
318
+ class HealthStatus(BaseModel):
319
+ """Adapter health status."""
320
+
321
+ healthy: bool
322
+ connections: Optional[Dict[str, int]] = None
323
+ last_error: Optional[str] = Field(None, alias="lastError")
324
+ uptime: int
325
+
326
+ class Config:
327
+ populate_by_name = True
328
+
329
+
330
+ class AdapterCapabilities(BaseModel):
331
+ """Adapter capabilities."""
332
+
333
+ transactions: bool = True
334
+ nested_transactions: bool = Field(False, alias="nestedTransactions")
335
+ joins: bool = True
336
+ full_text_search: bool = Field(False, alias="fullTextSearch")
337
+ json_operations: bool = Field(False, alias="jsonOperations")
338
+ schema_management: bool = Field(False, alias="schemaManagement")
339
+ migration_support: bool = Field(False, alias="migrationSupport")
340
+ batch_operations: bool = Field(True, alias="batchOperations")
341
+
342
+ class Config:
343
+ populate_by_name = True
344
+
345
+
346
+ # ============================================================================
347
+ # Configuration
348
+ # ============================================================================
349
+
350
+
351
+ class NamespaceConfig(BaseModel):
352
+ """Namespace configuration."""
353
+
354
+ separator: str = "_"
355
+ use_schema: bool = Field(default=False, alias="useSchema")
356
+ default_namespace: str = Field(default="default", alias="defaultNamespace")
357
+ known_namespaces: Optional[Set[str]] = Field(default=None, alias="knownNamespaces")
358
+
359
+ class Config:
360
+ populate_by_name = True
361
+
362
+
363
+ class AdapterConfig(BaseModel):
364
+ """Base adapter configuration."""
365
+
366
+ namespace: Optional[NamespaceConfig] = None
367
+ debug: bool = False
368
+ pool_size: Optional[int] = Field(None, alias="poolSize")
369
+ max_overflow: Optional[int] = Field(None, alias="maxOverflow")
370
+ pool_timeout: Optional[int] = Field(None, alias="poolTimeout")
371
+
372
+ class Config:
373
+ populate_by_name = True
374
+ arbitrary_types_allowed = True
375
+
376
+
377
+ # ============================================================================
378
+ # Protocols
379
+ # ============================================================================
380
+
381
+ T = TypeVar("T")
382
+
383
+
384
+ class TransactionAdapter(Protocol):
385
+ """Transaction adapter protocol."""
386
+
387
+ async def commit(self) -> None:
388
+ """Commit the transaction."""
389
+ pass
390
+
391
+ async def rollback(self) -> None:
392
+ """Rollback the transaction."""
393
+ pass
394
+
395
+ async def create(self, params: Optional[CreateParams] = None, **kwargs: Any) -> Dict[str, Any]:
396
+ """Create a record within transaction."""
397
+ pass
398
+
399
+ async def find_one(self, params: Optional[FindOneParams] = None, **kwargs: Any) -> Optional[Dict[str, Any]]:
400
+ """Find one record within transaction."""
401
+ pass
402
+
403
+ async def find_many(self, params: Optional[FindManyParams] = None, **kwargs: Any) -> List[Dict[str, Any]]:
404
+ """Find many records within transaction."""
405
+ pass
406
+
407
+ async def update(self, params: Optional[UpdateParams] = None, **kwargs: Any) -> Dict[str, Any]:
408
+ """Update a record within transaction."""
409
+ pass
410
+
411
+ async def delete(self, params: Optional[DeleteParams] = None, **kwargs: Any) -> None:
412
+ """Delete a record within transaction."""
413
+ pass
414
+
415
+
416
+ class AtomicUpdateTransactionAdapter(TransactionAdapter, Protocol):
417
+ """Optional transaction extension; callers must feature-detect update_many."""
418
+
419
+ async def update_many(self, params: Optional[UpdateManyParams] = None, **kwargs: Any) -> int:
420
+ """Atomically update all matching rows, retaining every WHERE predicate.
421
+
422
+ Returns the backend's affected/matched row count. CAS callers must change
423
+ a revision field and require exactly one row; no select/write emulation.
424
+ """
425
+ pass
426
+
427
+
428
+ class Adapter(Protocol):
429
+ """Database adapter protocol."""
430
+
431
+ # Metadata
432
+ id: str
433
+ name: str
434
+ version: str
435
+ capabilities: AdapterCapabilities
436
+
437
+ # Core CRUD operations
438
+ async def create(self, params: Optional[CreateParams] = None, **kwargs: Any) -> Dict[str, Any]:
439
+ """Create a single record."""
440
+ pass
441
+
442
+ async def find_one(self, params: Optional[FindOneParams] = None, **kwargs: Any) -> Optional[Dict[str, Any]]:
443
+ """Find a single record."""
444
+ pass
445
+
446
+ async def find_many(self, params: Optional[FindManyParams] = None, **kwargs: Any) -> List[Dict[str, Any]]:
447
+ """Find multiple records."""
448
+ pass
449
+
450
+ async def update(self, params: Optional[UpdateParams] = None, **kwargs: Any) -> Dict[str, Any]:
451
+ """Update a single record."""
452
+ pass
453
+
454
+ async def delete(self, params: Optional[DeleteParams] = None, **kwargs: Any) -> None:
455
+ """Delete a single record."""
456
+ pass
457
+
458
+ # Batch operations
459
+ async def create_many(self, params: Optional[CreateManyParams] = None, **kwargs: Any) -> List[Dict[str, Any]]:
460
+ """Create multiple records."""
461
+ pass
462
+
463
+ async def update_many(self, params: Optional[UpdateManyParams] = None, **kwargs: Any) -> int:
464
+ """Update multiple records, returns count."""
465
+ pass
466
+
467
+ async def delete_many(self, params: Optional[DeleteManyParams] = None, **kwargs: Any) -> int:
468
+ """Delete multiple records, returns count."""
469
+ pass
470
+
471
+ # Advanced operations
472
+ async def upsert(self, params: Optional[UpsertParams] = None, **kwargs: Any) -> Dict[str, Any]:
473
+ """Upsert a record."""
474
+ pass
475
+
476
+ async def count(self, params: Optional[CountParams] = None, **kwargs: Any) -> int:
477
+ """Count records."""
478
+ pass
479
+
480
+ # Transaction support
481
+ async def transaction(self, callback: Any) -> Any:
482
+ """Execute operations within a transaction."""
483
+ pass
484
+
485
+ # Lifecycle management
486
+ async def initialize(self) -> None:
487
+ """Initialize the adapter."""
488
+ pass
489
+
490
+ async def is_healthy(self) -> HealthStatus:
491
+ """Check adapter health."""
492
+ pass
493
+
494
+ async def close(self) -> None:
495
+ """Close the adapter."""
496
+ pass
497
+
498
+ # Schema management
499
+ async def get_schema_version(self, namespace: str) -> int:
500
+ """Get the current schema version."""
501
+ pass
502
+
503
+ async def set_schema_version(self, namespace: str, version: int) -> None:
504
+ """Set the schema version."""
505
+ pass
506
+
507
+ async def validate_schema(self, schema: TableSchema) -> ValidationResult:
508
+ """Validate a schema."""
509
+ pass
510
+
511
+ async def create_schema(self, params: CreateSchemaParams) -> SchemaCreation:
512
+ """Create database schema."""
513
+ pass
@@ -0,0 +1,81 @@
1
+ """
2
+ superfunctions.http - HTTP abstraction layer.
3
+
4
+ Provides protocol-based HTTP abstractions for framework-agnostic code.
5
+
6
+ Example:
7
+ >>> from superfunctions.http import Request, Response, RouteContext
8
+ >>>
9
+ >>> async def handler(request: Request, context: RouteContext) -> Response:
10
+ ... return Response(status=200, body={"message": "Hello"})
11
+ """
12
+
13
+ from .executor import execute_route
14
+ from .openapi import OpenApiGenerationError, generate_openapi_document
15
+ from .types import (
16
+ AuthRouteMeta,
17
+ BadRequestError,
18
+ ConflictError,
19
+ CorsOptions,
20
+ ForbiddenError,
21
+ HttpError,
22
+ HttpMethod,
23
+ HttpNotImplementedError,
24
+ InternalServerError,
25
+ MethodNotAllowedError,
26
+ Middleware,
27
+ NotFoundError,
28
+ OpenApiRouteMeta,
29
+ Request,
30
+ RequestHandler,
31
+ Response,
32
+ Route,
33
+ RouteContext,
34
+ RouteMeta,
35
+ RouterOptions,
36
+ ServiceUnavailableError,
37
+ SetCookie,
38
+ TooManyRequestsError,
39
+ UnauthorizedError,
40
+ UnprocessableEntityError,
41
+ get_route_openapi_meta,
42
+ serialize_response_cookies,
43
+ serialize_set_cookie,
44
+ )
45
+
46
+ __all__ = [
47
+ # Core types
48
+ "Request",
49
+ "Response",
50
+ "Route",
51
+ "RouteMeta",
52
+ "RouteContext",
53
+ "RouterOptions",
54
+ "HttpMethod",
55
+ "RequestHandler",
56
+ "Middleware",
57
+ "SetCookie",
58
+ "AuthRouteMeta",
59
+ "OpenApiRouteMeta",
60
+ "get_route_openapi_meta",
61
+ "generate_openapi_document",
62
+ "OpenApiGenerationError",
63
+ "execute_route",
64
+ "serialize_set_cookie",
65
+ "serialize_response_cookies",
66
+ # CORS
67
+ "CorsOptions",
68
+ # Errors
69
+ "HttpError",
70
+ "BadRequestError",
71
+ "UnauthorizedError",
72
+ "ForbiddenError",
73
+ "NotFoundError",
74
+ "MethodNotAllowedError",
75
+ "ConflictError",
76
+ "UnprocessableEntityError",
77
+ "TooManyRequestsError",
78
+ "InternalServerError",
79
+ "HttpNotImplementedError",
80
+ "ServiceUnavailableError",
81
+ ]
@@ -0,0 +1,36 @@
1
+ """Framework-neutral route middleware execution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Awaitable, Callable, Optional, cast
6
+
7
+ from .types import Response, Route, RouteContext
8
+
9
+
10
+ async def execute_route(
11
+ route: Optional[Route],
12
+ handler: Callable[..., Awaitable[Response]],
13
+ request: Any,
14
+ context: RouteContext,
15
+ ) -> Response:
16
+ """Execute route middleware in declaration order, then the handler."""
17
+ next_handler: Callable[..., Awaitable[Response]] = handler
18
+ for middleware in reversed((route.middleware or []) if route else []):
19
+ downstream = next_handler
20
+
21
+ async def invoke(
22
+ current_request: Any,
23
+ current_context: RouteContext,
24
+ middleware: Any = middleware,
25
+ downstream: Callable[..., Awaitable[Response]] = downstream,
26
+ ) -> Response:
27
+ return cast(
28
+ Response,
29
+ await middleware(current_request, current_context, downstream),
30
+ )
31
+
32
+ next_handler = invoke
33
+ return cast(Response, await next_handler(request, context))
34
+
35
+
36
+ __all__ = ["execute_route"]