Madalin Popa
Madalin Popa

Reputation: 71

SQLAlchemy version_id_col and version_id_generator not working with classical mapping

I am struggling to create a classical mapping using SQLAlchemy and Python and to use version_id_col and version_id_generator but something I am doing wrong because it doesn't work.

I have the following example:

# metadata
metadata = MetaData()

# define the engine
engine = create_engine("sqlite:///demo.db", echo=True)

# define the session
session = sessionmaker(bind=engine)()

class User:
    def __init__(self, username, version=None):
        self._username = username
        self._version_uuid = version

user = Table(
    "user",
    metadata,
    Column("id", Integer, primary_key=True, autoincrement=True),
    Column("_username", String(30), nullable=False),
    Column("_version_id", String(32), nullable=False),
)

def start_mapper():
    mapper(
        User,
        user,
        order_by="user._username",
        version_id_col="_version_id",
        version_id_generator=lambda version: uuid.uuid4().hex,
    )

def main():

    start_mapper()

    metadata.create_all(bind=engine)

    user = User("madalin")
    session.add(user)
    session.commit()


if __name__ == "__main__":
    main()

And this is the error message I got:

 cursor.execute(statement, parameters)
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: user._version_id
[SQL: INSERT INTO user (_username, _version_id) VALUES (?, ?)]
[parameters: ('madalin', None)]
(Background on this error at: http://sqlalche.me/e/gkpj)

What I am looking for is to have the version_id column auto-populated by the following version_id_generator=lambda version: uuid.uuid4().hex, property within the mapper function

What I am doing wrong here?

Thank you

Upvotes: 1

Views: 697

Answers (1)

Madalin Popa
Madalin Popa

Reputation: 71

I have managed to solve it by changing this:

def start_mapper():
    mapper(
        User,
        user,
        order_by="user._username",
        version_id_col="_version_id",
        version_id_generator=lambda version: uuid.uuid4().hex,
    )

to this:


def start_mapper():
    mapper(
        User,
        user,
        order_by=user.c._username,
        version_id_col=user.c._version_id,
        version_id_generator=lambda version: uuid.uuid4().hex,
    )

Upvotes: 1

Related Questions