ormar icon indicating copy to clipboard operation
ormar copied to clipboard

model.save() with server_default is failing on refreshing server_default values

Open cmflynn opened this issue 2 years ago • 0 comments

Describe the bug

model.save() is raising NoMatch when it tries to refresh a server_default that is a PK. I was able to fix this locally by just setting self.pk = pk in https://github.com/collerek/ormar/blob/master/ormar/models/model.py#L85-L96. happy to open a PR if the issue is valid.

To Reproduce Steps to reproduce the behavior:

import asyncio
import uuid
from datetime import date, datetime
from typing import Optional

import ormar
import sqlalchemy
from databases import Database
from sqlalchemy import func, text


database = Database(url="postgresql://[email protected]:5432/postgres", force_rollback=True)
engine = sqlalchemy.create_engine("postgresql://[email protected]:5432/postgres")
metadata = sqlalchemy.MetaData()


class BaseMeta:
    metadata = metadata
    database = database


class Jimmy(ormar.Model):
    class Meta(BaseMeta):
        tablename = "jimmy_rus"

    id: uuid.UUID = ormar.UUID(
        primary_key=True, server_default=text("gen_random_uuid()"), uuid_format="string"
    )


async def main():
    await database.connect()
    metadata.drop_all(bind=engine)
    metadata.create_all(bind=engine)
    jimmy = Jimmy()
    await jimmy.save()


if __name__ == '__main__':
    asyncio.run(main())

Expected behavior should not raise an exception after the item is already persisted to the db.

Versions (please complete the following information):

  • Database backend used (mysql/sqlite/postgress) postgres
  • Python version 3.9
  • ormar version 0.11.2
  • pydantic version 1.9

Additional context I've tracked the offending code down: https://github.com/collerek/ormar/blob/master/ormar/models/model.py#L85-L96

from what I can tell, the pk is correctly returned via insert expr, however self.pk never gets set. so when self.load is called it doesnt correctly select for item that was insert since self.pk is None.

cmflynn avatar Jul 15 '22 21:07 cmflynn