Skip to content

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

@dargueta

Description

@dargueta

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions