Skip to content

Commit f508e93

Browse files
malmans2alex75
andauthored
created_at and updated_at columns (#121)
* created_at and updated_at columns * add test * more testing * alembic logic integrated in code * style and type-check * import init_database * add default value --------- Co-authored-by: Alessio Siniscalchi <[email protected]>
1 parent fe57496 commit f508e93

15 files changed

+371
-15
lines changed

README.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,25 @@ Before pushing to GitHub, run the following commands:
104104
1. Run the static type checker: `make type-check`
105105
1. Build the documentation (see [Sphinx tutorial](https://www.sphinx-doc.org/en/master/tutorial/)): `make docs-build`
106106

107+
### Instructions for database updating
108+
109+
In case of database structure upgrade, developers must follow these steps:
110+
111+
1. Update the new database structure modifying [/cacholote/database.py](/cacholote/database.py), using
112+
[SQLAlchemy ORM technologies](https://docs.sqlalchemy.org/en/latest/orm/)
113+
1. Execute from the cacholote work folder:
114+
```
115+
alembic revision -m "message about the db modification"
116+
```
117+
1. The last command will create a new python file inside [/alembic/versions](/alembic/versions). Fill the `upgrade`
118+
function with the operations that must be executed to migrate the database from the old structure to the new one.
119+
Keep in mind both DDL (structure modification) and DML (data modification) instructions. For reference,
120+
use https://alembic.sqlalchemy.org/en/latest/ops.html#ops.
121+
Similarly, do the same with the `downgrade` function.
122+
1. Commit and push the modifications and the new file.
123+
124+
For details about the alembic migration tool, see the [Alembic tutorial](https://alembic.sqlalchemy.org/en/latest/tutorial.html).
125+
107126
## License
108127

109128
```

alembic.ini

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
# A generic, single database configuration.
2+
3+
[alembic]
4+
# path to migration scripts
5+
# Use forward slashes (/) also on windows to provide an os agnostic path
6+
script_location = alembic
7+
8+
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
9+
# Uncomment the line below if you want the files to be prepended with date and time
10+
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
11+
# for all available tokens
12+
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
13+
14+
# sys.path path, will be prepended to sys.path if present.
15+
# defaults to the current working directory.
16+
prepend_sys_path = .
17+
18+
# timezone to use when rendering the date within the migration file
19+
# as well as the filename.
20+
# If specified, requires the python>=3.9 or backports.zoneinfo library.
21+
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
22+
# string value is passed to ZoneInfo()
23+
# leave blank for localtime
24+
# timezone =
25+
26+
# max length of characters to apply to the "slug" field
27+
# truncate_slug_length = 40
28+
29+
# set to 'true' to run the environment during
30+
# the 'revision' command, regardless of autogenerate
31+
# revision_environment = false
32+
33+
# set to 'true' to allow .pyc and .pyo files without
34+
# a source .py file to be detected as revisions in the
35+
# versions/ directory
36+
# sourceless = false
37+
38+
# version location specification; This defaults
39+
# to alembic/versions. When using multiple version
40+
# directories, initial revisions must be specified with --version-path.
41+
# The path separator used here should be the separator specified by "version_path_separator" below.
42+
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
43+
44+
# version path separator; As mentioned above, this is the character used to split
45+
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
46+
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
47+
# Valid values for version_path_separator are:
48+
#
49+
# version_path_separator = :
50+
# version_path_separator = ;
51+
# version_path_separator = space
52+
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
53+
54+
# set to 'true' to search source files recursively
55+
# in each "version_locations" directory
56+
# new in Alembic version 1.10
57+
# recursive_version_locations = false
58+
59+
# the output encoding used when revision files
60+
# are written from script.py.mako
61+
# output_encoding = utf-8
62+
63+
drivername =
64+
username =
65+
password =
66+
host =
67+
port =
68+
database =
69+
sqlalchemy.url = %(drivername)s://%(username)s:%(password)s@%(host)s:%(port)s/%(database)s
70+
71+
72+
[post_write_hooks]
73+
# post_write_hooks defines scripts or Python functions that are run
74+
# on newly generated revision scripts. See the documentation for further
75+
# detail and examples
76+
77+
# format using "black" - use the console_scripts runner, against the "black" entrypoint
78+
# hooks = black
79+
# black.type = console_scripts
80+
# black.entrypoint = black
81+
# black.options = -l 79 REVISION_SCRIPT_FILENAME
82+
83+
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
84+
# hooks = ruff
85+
# ruff.type = exec
86+
# ruff.executable = %(here)s/.venv/bin/ruff
87+
# ruff.options = --fix REVISION_SCRIPT_FILENAME
88+
89+
# Logging configuration
90+
[loggers]
91+
keys = root,sqlalchemy,alembic
92+
93+
[handlers]
94+
keys = console
95+
96+
[formatters]
97+
keys = generic
98+
99+
[logger_root]
100+
level = WARN
101+
handlers = console
102+
qualname =
103+
104+
[logger_sqlalchemy]
105+
level = WARN
106+
handlers =
107+
qualname = sqlalchemy.engine
108+
109+
[logger_alembic]
110+
level = INFO
111+
handlers =
112+
qualname = alembic
113+
114+
[handler_console]
115+
class = StreamHandler
116+
args = (sys.stderr,)
117+
level = NOTSET
118+
formatter = generic
119+
120+
[formatter_generic]
121+
format = %(levelname)-5.5s [%(name)s] %(message)s
122+
datefmt = %H:%M:%S

alembic/README

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Generic single-database configuration.

alembic/env.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
"""module for entry points."""
2+
3+
import sqlalchemy as sa
4+
5+
import alembic.context
6+
import cacholote
7+
8+
config = alembic.context.config
9+
10+
11+
def run_migrations_offline() -> None:
12+
"""Run migrations in 'offline' mode.
13+
14+
This configures the context with just a URL
15+
and not an Engine, though an Engine is acceptable
16+
here as well. By skipping the Engine creation
17+
we don't even need a DBAPI to be available.
18+
19+
Calls to context.execute() here emit the given string to the
20+
script output.
21+
22+
"""
23+
url_props = dict()
24+
for prop in ["drivername", "username", "password", "host", "port", "database"]:
25+
url_props[prop] = config.get_main_option(prop)
26+
url_props["port"] = url_props["port"] and int(url_props["port"]) or None # type: ignore
27+
url = sa.engine.URL.create(**url_props) # type: ignore
28+
alembic.context.configure(
29+
url=url,
30+
target_metadata=cacholote.database.Base.metadata,
31+
literal_binds=True,
32+
dialect_opts={"paramstyle": "named"},
33+
)
34+
with alembic.context.begin_transaction():
35+
alembic.context.run_migrations()
36+
37+
38+
def run_migrations_online() -> None:
39+
"""Run migrations in 'online' mode.
40+
41+
In this scenario we need to create an Engine
42+
and associate a connection with the context.
43+
44+
"""
45+
url_props = dict()
46+
for prop in ["drivername", "username", "password", "host", "port", "database"]:
47+
url_props[prop] = config.get_main_option(prop)
48+
url_props["port"] = url_props["port"] and int(url_props["port"]) or None # type: ignore
49+
url = sa.engine.URL.create(**url_props) # type: ignore
50+
engine = sa.create_engine(url, poolclass=sa.pool.NullPool)
51+
with engine.connect() as connection:
52+
alembic.context.configure(
53+
connection=connection,
54+
target_metadata=cacholote.database.Base.metadata,
55+
version_table="alembic_version_cacholote",
56+
)
57+
58+
with alembic.context.begin_transaction():
59+
alembic.context.run_migrations()
60+
61+
62+
if alembic.context.is_offline_mode():
63+
run_migrations_offline()
64+
else:
65+
run_migrations_online()

alembic/script.py.mako

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""${message}
2+
3+
Revision ID: ${up_revision}
4+
Revises: ${down_revision | comma,n}
5+
Create Date: ${create_date}
6+
7+
"""
8+
from typing import Sequence, Union
9+
10+
from alembic import op
11+
import sqlalchemy as sa
12+
${imports if imports else ""}
13+
14+
# revision identifiers, used by Alembic.
15+
revision: str = ${repr(up_revision)}
16+
down_revision: Union[str, None] = ${repr(down_revision)}
17+
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
18+
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
19+
20+
21+
def upgrade() -> None:
22+
${upgrades if upgrades else "pass"}
23+
24+
25+
def downgrade() -> None:
26+
${downgrades if downgrades else "pass"}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""add created_at and rename timestamp column.
2+
3+
Revision ID: a38663d192e5
4+
Revises:
5+
Create Date: 2024-07-24 15:53:43.989464
6+
7+
"""
8+
9+
from typing import Sequence, Union
10+
11+
import sqlalchemy as sa
12+
13+
import cacholote
14+
from alembic import op
15+
16+
# revision identifiers, used by Alembic.
17+
revision: str = "a38663d192e5"
18+
down_revision: Union[str, None] = None
19+
branch_labels: Union[str, Sequence[str], None] = None
20+
depends_on: Union[str, Sequence[str], None] = None
21+
22+
23+
def upgrade() -> None:
24+
op.add_column(
25+
"cache_entries",
26+
sa.Column("created_at", sa.DateTime, default=cacholote.utils.utcnow),
27+
)
28+
op.execute(f"UPDATE cache_entries SET created_at='{cacholote.utils.utcnow()!s}'")
29+
30+
op.alter_column("cache_entries", "timestamp", new_column_name="updated_at")
31+
32+
33+
def downgrade() -> None:
34+
op.drop_column("cache_entries", "created_at")
35+
op.alter_column("cache_entries", "updated_at", new_column_name="timestamp")

cacholote/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
delete,
2424
expire_cache_entries,
2525
)
26+
from .database import init_database
2627
from .decode import loads
2728
from .encode import dumps
2829

@@ -47,6 +48,7 @@
4748
"dumps",
4849
"expire_cache_entries",
4950
"extra_encoders",
51+
"init_database",
5052
"loads",
5153
"utils",
5254
]

cacholote/cache.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ def wrapper(*args: Any, **kwargs: Any) -> Any:
7676
for cache_entry in session.scalars(
7777
sa.select(database.CacheEntry)
7878
.filter(*filters)
79-
.order_by(database.CacheEntry.timestamp.desc())
79+
.order_by(database.CacheEntry.updated_at.desc())
8080
):
8181
try:
8282
return _decode_and_update(session, cache_entry, settings)

cacholote/clean.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -196,9 +196,13 @@ def _get_method_sorters(
196196
) -> list[sa.orm.InstrumentedAttribute[Any]]:
197197
sorters: list[sa.orm.InstrumentedAttribute[Any]] = []
198198
if method == "LRU":
199-
sorters.extend([database.CacheEntry.timestamp, database.CacheEntry.counter])
199+
sorters.extend(
200+
[database.CacheEntry.updated_at, database.CacheEntry.counter]
201+
)
200202
elif method == "LFU":
201-
sorters.extend([database.CacheEntry.counter, database.CacheEntry.timestamp])
203+
sorters.extend(
204+
[database.CacheEntry.counter, database.CacheEntry.updated_at]
205+
)
202206
else:
203207
raise ValueError(f"{method=}")
204208
sorters.append(database.CacheEntry.expiration)
@@ -368,9 +372,9 @@ def expire_cache_entries(
368372
if tags is not None:
369373
filters.append(database.CacheEntry.tag.in_(tags))
370374
if before is not None:
371-
filters.append(database.CacheEntry.timestamp < before)
375+
filters.append(database.CacheEntry.created_at < before)
372376
if after is not None:
373-
filters.append(database.CacheEntry.timestamp > after)
377+
filters.append(database.CacheEntry.created_at > after)
374378

375379
count = 0
376380
with config.get().instantiated_sessionmaker() as session:

0 commit comments

Comments
 (0)