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
Unexpected model create behaviour for non-integer primary keys #47
Comments
Does somebody has an update on this? I have the same issue. using a str uuid as PK, but the id is always an integer before the new object is read from DB |
seems it's asyncpg issue - MagicStack/asyncpg#526 |
Noticed same issue, ended up writing own class BaseModel(orm.Model):
__abstract__ = True
@classmethod
async def create(cls, **kwargs):
fields = cls.fields
required = [key for key, value in fields.items() if not value.has_default()]
validator = typesystem.Object(
properties=fields, required=required, additional_properties=False
)
kwargs = validator.validate(kwargs)
pk_column = getattr(cls.__table__.c, cls.__pkname__)
expr = cls.__table__.insert().returning(pk_column)
expr = expr.values(**kwargs)
instance = cls(kwargs)
instance.pk = await cls.__database__.execute(expr)
return instance |
@Nipsuli That's really helpful thanks - we probably ought to update the |
I am able to reproduce this using sqlite.
The script:
The results:
As you can see, the returned results are an integer. If the data was fetched again, it'd be present. The database is created correctly:
and as you can see above in the dump, the correct data is in the database, just the object was created incorrectly. |
Just ran a test, and it goes wrong here:
a print of the instance before that line has the data being correct. An option is that if pk is present in kwargs, simply don't do the assignment. I don't know the layers well enough to say what is correct though. Also, not sure how/if this addresses the case where multiple fields are the primary key. |
@tomchristie @Nipsuli For anyone interested, the reason this is happening is that SQLite uses a virtual column As far as I know MySQL doesn't support that either. Any feedback is appreciated. |
When primary key is i.e.
String
, model instance returned frommodel.object.create
has primary key as sequential integer. Once instance is fetched again, primary key is as expected - type and value wise.Postgres behaviour is similar. Returned instance primary key in this case is actually
None
. Same forUUID
type. Once fetched again, everything is as expected.Could be that problem originates from
databases
library or incorrect usage of it.Two copy/paste tests.
The text was updated successfully, but these errors were encountered: