xnuinside / omymodels

O!My Models (omymodels) is a library to generate Pydantic, Dataclasses, GinoORM Models, SqlAlchemy ORM, SqlAlchemy Core Table, Models from SQL DDL. And convert one models to another.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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.