pjdev-postgres 3.5.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pjdev_postgres/__about__.py +4 -0
- pjdev_postgres/__init__.py +3 -0
- pjdev_postgres/concurrency_service.py +33 -0
- pjdev_postgres/model_validators.py +58 -0
- pjdev_postgres/models.py +57 -0
- pjdev_postgres/postgres_service.py +95 -0
- pjdev_postgres/postgres_settings.py +35 -0
- pjdev_postgres-3.5.0.dist-info/METADATA +47 -0
- pjdev_postgres-3.5.0.dist-info/RECORD +11 -0
- pjdev_postgres-3.5.0.dist-info/WHEEL +4 -0
- pjdev_postgres-3.5.0.dist-info/licenses/LICENSE.txt +9 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from typing import TypeVar, Optional
|
|
2
|
+
from uuid import UUID, uuid4
|
|
3
|
+
from loguru import logger
|
|
4
|
+
|
|
5
|
+
from pjdev_postgres.models import Versioned, ConcurrencyException
|
|
6
|
+
|
|
7
|
+
T = TypeVar("T", bound=Versioned)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def parse_concurrency_token(token: str) -> Optional[UUID]:
|
|
11
|
+
try:
|
|
12
|
+
concurrency_token = UUID(token) if token is not None else None
|
|
13
|
+
return concurrency_token
|
|
14
|
+
except TypeError as e:
|
|
15
|
+
logger.warning(f"{e}")
|
|
16
|
+
logger.warning(f"Tried parsing invalid uuid: {token}")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def increment_version(obj: T) -> T:
|
|
20
|
+
obj.concurrency_token = uuid4()
|
|
21
|
+
|
|
22
|
+
return obj
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def validate_version(obj: T, token: Optional[str | UUID] = None) -> T:
|
|
26
|
+
concurrency_token = token
|
|
27
|
+
if not isinstance(token, UUID):
|
|
28
|
+
concurrency_token = parse_concurrency_token(token)
|
|
29
|
+
|
|
30
|
+
if obj.concurrency_token is not None and obj.concurrency_token != concurrency_token:
|
|
31
|
+
raise ConcurrencyException("Stale data detected")
|
|
32
|
+
|
|
33
|
+
return increment_version(obj)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
from datetime import date, datetime, UTC
|
|
2
|
+
from typing import Callable, List, Optional, Type, Any
|
|
3
|
+
from loguru import logger
|
|
4
|
+
from pydantic import BeforeValidator
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def make_date_validator(
|
|
8
|
+
date_format: str, date_obj_type: Type[date | datetime] = datetime
|
|
9
|
+
) -> Callable[[str], Optional[date]]:
|
|
10
|
+
def validator(v: Optional[Any]) -> Optional[date]:
|
|
11
|
+
if not v:
|
|
12
|
+
return None
|
|
13
|
+
|
|
14
|
+
if isinstance(v, datetime):
|
|
15
|
+
formatted_value = v
|
|
16
|
+
if date_format == "iso":
|
|
17
|
+
formatted_value = v.astimezone(UTC)
|
|
18
|
+
return (
|
|
19
|
+
formatted_value if date_obj_type is datetime else formatted_value.date()
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
if isinstance(v, date):
|
|
23
|
+
return v
|
|
24
|
+
|
|
25
|
+
if not isinstance(v, str):
|
|
26
|
+
return None
|
|
27
|
+
|
|
28
|
+
stripped_value = v.strip()
|
|
29
|
+
|
|
30
|
+
if stripped_value in ["-", ""]:
|
|
31
|
+
return None
|
|
32
|
+
|
|
33
|
+
if date_format == "iso":
|
|
34
|
+
value = datetime.fromisoformat(v).replace(tzinfo=UTC)
|
|
35
|
+
else:
|
|
36
|
+
value = datetime.strptime(v, date_format)
|
|
37
|
+
return value.date() if date_obj_type is date else value
|
|
38
|
+
|
|
39
|
+
return validator
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def make_date_validator_for_formats(
|
|
43
|
+
date_formats: List[str], date_obj_type: Type[date | datetime] = datetime
|
|
44
|
+
) -> Callable[[str], Optional[date]]:
|
|
45
|
+
def validator(v: Optional[Any]) -> Optional[date]:
|
|
46
|
+
for fmt in date_formats:
|
|
47
|
+
try:
|
|
48
|
+
return make_date_validator(fmt, date_obj_type)(v)
|
|
49
|
+
except ValueError as e:
|
|
50
|
+
logger.warning(e)
|
|
51
|
+
continue
|
|
52
|
+
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
return validator
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
date_validator = BeforeValidator(make_date_validator_for_formats(["iso"], date))
|
pjdev_postgres/models.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
from datetime import datetime, UTC
|
|
2
|
+
from typing import Optional, Annotated
|
|
3
|
+
from uuid import UUID
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel
|
|
6
|
+
from sqlmodel import SQLModel, Field, Index
|
|
7
|
+
|
|
8
|
+
from pjdev_postgres.model_validators import date_validator
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ConnectionOptions(BaseModel):
|
|
12
|
+
echo: bool = False
|
|
13
|
+
pool_size: int = 5
|
|
14
|
+
max_overflow: int = 10
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Versioned(BaseModel):
|
|
18
|
+
concurrency_token: Optional[UUID] = None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Auditable(BaseModel):
|
|
22
|
+
created_by_id: Optional[str] = None
|
|
23
|
+
created_by: Optional[str] = None
|
|
24
|
+
created_datetime: Annotated[
|
|
25
|
+
datetime, date_validator, Field(default_factory=lambda: datetime.now(UTC))
|
|
26
|
+
]
|
|
27
|
+
last_modified_by_id: Optional[str] = None
|
|
28
|
+
last_modified_by: Optional[str] = None
|
|
29
|
+
last_modified_datetime: Annotated[Optional[datetime], date_validator] = None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class TableModel(SQLModel):
|
|
33
|
+
row_id: Optional[int] = Field(default=None, primary_key=True)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Savable(Versioned, Auditable, TableModel):
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class History(TableModel, table=True):
|
|
41
|
+
entity_name: str
|
|
42
|
+
entity_id: int
|
|
43
|
+
value: str
|
|
44
|
+
timestamp: Annotated[
|
|
45
|
+
datetime, date_validator, Field(default_factory=lambda: datetime.now(UTC))
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
__table_args__ = (
|
|
49
|
+
Index("ix_history_entity_id", "entity_id"),
|
|
50
|
+
Index("ix_history_entity_name", "entity_name"),
|
|
51
|
+
Index("ix_history_timestamp", "timestamp"),
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ConcurrencyException(BaseException):
|
|
56
|
+
def __init__(self, message: str):
|
|
57
|
+
super().__init__(message)
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
from contextlib import contextmanager
|
|
2
|
+
from datetime import datetime, UTC
|
|
3
|
+
from typing import List, Optional, Type, TypeVar, Callable, Tuple
|
|
4
|
+
from uuid import UUID
|
|
5
|
+
|
|
6
|
+
from sqlalchemy import Engine
|
|
7
|
+
from sqlmodel import SQLModel, create_engine, Session as SQLModelSession
|
|
8
|
+
|
|
9
|
+
from pjdev_postgres import postgres_settings, concurrency_service
|
|
10
|
+
from pjdev_postgres.models import ConnectionOptions, Savable, History
|
|
11
|
+
|
|
12
|
+
T = TypeVar("T", bound=Savable)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Context:
|
|
16
|
+
engine: Optional[Engine] = None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
__ctx = Context()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def initialize_engine(
|
|
23
|
+
tables: List[Type[SQLModel]],
|
|
24
|
+
options: Optional[ConnectionOptions] = None,
|
|
25
|
+
) -> Engine:
|
|
26
|
+
if options is None:
|
|
27
|
+
options = ConnectionOptions()
|
|
28
|
+
|
|
29
|
+
settings = postgres_settings.get_settings()
|
|
30
|
+
|
|
31
|
+
if len(tables) == 0:
|
|
32
|
+
raise ValueError("Must specify at least one table")
|
|
33
|
+
|
|
34
|
+
db_url = f"postgresql+psycopg://{settings.username}:{settings.password}@{settings.host}/{settings.name}"
|
|
35
|
+
|
|
36
|
+
engine = create_engine(
|
|
37
|
+
db_url,
|
|
38
|
+
echo=options.echo,
|
|
39
|
+
pool_size=options.pool_size,
|
|
40
|
+
max_overflow=options.max_overflow,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
for t in tables:
|
|
44
|
+
t.__table__.create(bind=engine, checkfirst=True)
|
|
45
|
+
|
|
46
|
+
return engine
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def configure_single_context(
|
|
50
|
+
tables: List[Type[SQLModel]], options: Optional[ConnectionOptions] = None
|
|
51
|
+
):
|
|
52
|
+
__ctx.engine = initialize_engine(tables, options)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@contextmanager
|
|
56
|
+
def session_context() -> SQLModelSession:
|
|
57
|
+
with SQLModelSession(__ctx.engine) as session:
|
|
58
|
+
try:
|
|
59
|
+
yield session
|
|
60
|
+
finally:
|
|
61
|
+
session.close()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def get_session() -> SQLModelSession:
|
|
65
|
+
with SQLModelSession(__ctx.engine) as session:
|
|
66
|
+
yield session
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def save(
|
|
70
|
+
obj: T,
|
|
71
|
+
user_resolver: Callable[[], Tuple[Optional[str], str]],
|
|
72
|
+
session: SQLModelSession,
|
|
73
|
+
concurrency_token: Optional[UUID] = None,
|
|
74
|
+
commit: bool = True,
|
|
75
|
+
) -> T:
|
|
76
|
+
updated_obj = concurrency_service.validate_version(obj, concurrency_token)
|
|
77
|
+
updated_obj.last_modified_datetime = datetime.now(UTC)
|
|
78
|
+
user_oid, username = user_resolver()
|
|
79
|
+
updated_obj.last_modified_by_id = user_oid
|
|
80
|
+
updated_obj.last_modified_by = username
|
|
81
|
+
|
|
82
|
+
session.flush([updated_obj])
|
|
83
|
+
|
|
84
|
+
history = History(
|
|
85
|
+
entity_name=updated_obj.__class__.__name__.lower(),
|
|
86
|
+
entity_id=updated_obj.row_id,
|
|
87
|
+
value=updated_obj.model_dump_json(),
|
|
88
|
+
)
|
|
89
|
+
session.add(history)
|
|
90
|
+
|
|
91
|
+
if commit:
|
|
92
|
+
session.commit()
|
|
93
|
+
session.refresh(updated_obj)
|
|
94
|
+
|
|
95
|
+
return updated_obj
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import Optional
|
|
3
|
+
|
|
4
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class PostgresSettings(BaseSettings):
|
|
8
|
+
host: str = "localhost"
|
|
9
|
+
name: str
|
|
10
|
+
password: Optional[str] = None
|
|
11
|
+
username: Optional[str] = None
|
|
12
|
+
model_config = SettingsConfigDict(
|
|
13
|
+
case_sensitive=False,
|
|
14
|
+
extra="ignore",
|
|
15
|
+
env_nested_delimiter="__",
|
|
16
|
+
env_prefix="db_",
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Context:
|
|
21
|
+
settings: Optional[PostgresSettings] = None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
__ctx = Context()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def init_settings(root: Path):
|
|
28
|
+
__ctx.settings = PostgresSettings(_env_file=root / ".env")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def get_settings() -> PostgresSettings:
|
|
32
|
+
if __ctx.settings is None:
|
|
33
|
+
msg = "Settings are not initialized -- call init_settings()"
|
|
34
|
+
raise Exception(msg)
|
|
35
|
+
return __ctx.settings
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: pjdev-postgres
|
|
3
|
+
Version: 3.5.0
|
|
4
|
+
Project-URL: Documentation, https://gitlab.purplejay.net/keystone/python/-/tree/main/keystone-postgres/README.md
|
|
5
|
+
Project-URL: Issues, https://gitlab.purplejay.net/keystone/python/-/issues
|
|
6
|
+
Project-URL: Source, https://gitlab.purplejay.net/keystone/python
|
|
7
|
+
Author-email: Purple Jay LLC <it@purplejay.io>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE.txt
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Programming Language :: Python
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
14
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
15
|
+
Requires-Python: >=3.12
|
|
16
|
+
Requires-Dist: loguru
|
|
17
|
+
Requires-Dist: psycopg[binary,pool]>=3.1.19
|
|
18
|
+
Requires-Dist: pydantic-settings>=2.3.1
|
|
19
|
+
Requires-Dist: sqlmodel>=0.0.19
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: ruff; extra == 'dev'
|
|
22
|
+
Provides-Extra: test
|
|
23
|
+
Requires-Dist: coverage; extra == 'test'
|
|
24
|
+
Requires-Dist: pytest; extra == 'test'
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# keystone-postgres
|
|
28
|
+
|
|
29
|
+
[](https://pypi.org/project/pjdev-postgres)
|
|
30
|
+
[](https://pypi.org/project/pjdev-postgres)
|
|
31
|
+
|
|
32
|
+
-----
|
|
33
|
+
|
|
34
|
+
**Table of Contents**
|
|
35
|
+
|
|
36
|
+
- [Installation](#installation)
|
|
37
|
+
- [License](#license)
|
|
38
|
+
|
|
39
|
+
## Installation
|
|
40
|
+
|
|
41
|
+
```console
|
|
42
|
+
pip install pjdev-postgres
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## License
|
|
46
|
+
|
|
47
|
+
`pjdev-postgres` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
pjdev_postgres/__about__.py,sha256=-OJwVAONjchMJifFqKPLSg4cwo1wWGkZ5Mdg8P0ReWc,129
|
|
2
|
+
pjdev_postgres/__init__.py,sha256=p8HS8DuMfFNAzuLS_PWRIyHOQdNes0L5TqNE9M-L7nc,107
|
|
3
|
+
pjdev_postgres/concurrency_service.py,sha256=_FdPc4i40OZmEkREPv-rL3fkmey1ct55qCkUpLxhmqQ,960
|
|
4
|
+
pjdev_postgres/model_validators.py,sha256=p2sxXcs-wWjRGbUByMjwoM8IiposWGu23Sr7bISLD8U,1688
|
|
5
|
+
pjdev_postgres/models.py,sha256=6Gk-GeLrt6CRydsKrFqA7azcWPzIdx2xsFYuwTUmEdY,1491
|
|
6
|
+
pjdev_postgres/postgres_service.py,sha256=obJ3wm6RTYFUbuItNds7WWH81nCLBHv9MILeN4PPm60,2464
|
|
7
|
+
pjdev_postgres/postgres_settings.py,sha256=oDgMVQuir-XC-x1YssBgmYKBAW9kRCHUSZv7yWwaxJg,807
|
|
8
|
+
pjdev_postgres-3.5.0.dist-info/METADATA,sha256=1iaBZuyQn0Yvqi97L-PO1q64UQfT8nVzZK2UP5i3xTw,1570
|
|
9
|
+
pjdev_postgres-3.5.0.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
|
|
10
|
+
pjdev_postgres-3.5.0.dist-info/licenses/LICENSE.txt,sha256=0wYf-NtzsFHBi7LG7ANo5X1v8sZfdv-7ZoslV6Vy3nA,1099
|
|
11
|
+
pjdev_postgres-3.5.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024-present Chris O'Neill <chris@purplejay.io>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|