Default value of `now()` always returns same time
dargueta opened this issue · comments
Describe the bug
Using now()
as the default value of a timestamp column in the DDL results in a hard-coded default timestamp.
To Reproduce
Run the following:
ddl = """
CREATE TABLE asdf (
t TIMESTAMP DEFAULT now()
);
"""
print(omymodels.create_models(ddl=ddl, models_type="dataclass")["code"])
The output is
import datetime
from dataclasses import dataclass
@dataclass
class Asdf:
t: datetime.datetime = datetime.datetime.now()
Using the returned code, run the following:
>>> a = Asdf()
>>> a.t
datetime.datetime(2021, 7, 12, 9, 26, 27, 251799)
# Wait several seconds, then
>>> b = Asdf()
>>> b.t
datetime.datetime(2021, 7, 12, 9, 26, 27, 251799)
Note that the timestamps are identical, even though I waited several seconds between the two. This is because the default value is evaluated upon class creation, and doesn't change after that. The proper solution (for dataclasses, at least), would use field()
to define the column, like so:
import datetime
from dataclasses import dataclass
from dataclasses import field
@dataclass
class Asdf:
t: datetime.datetime = field(default_factory=datetime.datetime.now)
This will result in the correct behavior, where the timestamp changes for every instantiation.
Expected behavior
The default value should be the time when the instance of the class was created, not when the module defining its class was first imported.
Additional context
Python: 3.8.2
Version: 0.8.1
@dargueta, awesome, you right! I will also fix this.
Thanks for the fast response! I could really use this at work.
@dargueta I released version 0.8.3 with fix - https://pypi.org/project/omymodels/0.8.3/. Tests - https://github.com/xnuinside/omymodels/blob/main/tests/test_dataclasses.py#L64