Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Default value of now() always returns same time #19

Closed
dargueta opened this issue Jul 12, 2021 · 3 comments
Closed

Default value of now() always returns same time #19

dargueta opened this issue Jul 12, 2021 · 3 comments

Comments

@dargueta
Copy link

dargueta commented Jul 12, 2021

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

@xnuinside
Copy link
Owner

@dargueta, awesome, you right! I will also fix this.

@dargueta
Copy link
Author

Thanks for the fast response! I could really use this at work.

@xnuinside
Copy link
Owner

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants