Title: Improper UUID serialisation dropping leading zeros ▶️ "ValueError: badly formed hexadecimal UUID string" · Issue #25 · fastapi/sqlmodel · GitHub
Open Graph Title: Improper UUID serialisation dropping leading zeros ▶️ "ValueError: badly formed hexadecimal UUID string" · Issue #25 · fastapi/sqlmodel
X Title: Improper UUID serialisation dropping leading zeros ▶️ "ValueError: badly formed hexadecimal UUID string" · Issue #25 · fastapi/sqlmodel
Description: First Check I added a very descriptive title to this issue. I used the GitHub search to find a similar issue and didn't find it. I searched the SQLModel documentation, with the integrated search. I already searched in Google "How to X in...
Open Graph Description: First Check I added a very descriptive title to this issue. I used the GitHub search to find a similar issue and didn't find it. I searched the SQLModel documentation, with the integrated search. I...
X Description: First Check I added a very descriptive title to this issue. I used the GitHub search to find a similar issue and didn't find it. I searched the SQLModel documentation, with the integrated searc...
Opengraph URL: https://github.com/fastapi/sqlmodel/issues/25
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Improper UUID serialisation dropping leading zeros ▶️ \"ValueError: badly formed hexadecimal UUID string\"","articleBody":"### First Check\r\n\r\n- [X] I added a very descriptive title to this issue.\r\n- [X] I used the GitHub search to find a similar issue and didn't find it.\r\n- [X] I searched the SQLModel documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in SQLModel\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to SQLModel but to [Pydantic](https://github.com/samuelcolvin/pydantic).\r\n- [X] I already checked if it is not related to SQLModel but to [SQLAlchemy](https://github.com/sqlalchemy/sqlalchemy).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nimport uuid\r\nfrom typing import Optional\r\n\r\nimport sqlalchemy.exc\r\nfrom sqlmodel import SQLModel, Field\r\nfrom sqlmodel import create_engine, Session, select\r\n\r\n\r\nclass Hero(SQLModel, table=True):\r\n id: Optional[uuid.UUID] = Field(primary_key=True,\r\n default_factory=uuid.uuid4)\r\n name: str\r\n secret_name: str\r\n age: Optional[int] = None\r\n\r\n def __str__(self):\r\n return f'{self.name} (AKA {self.secret_name}) [{self.age if self.age is not None else \"Unknown\"}]'\r\n\r\n\r\nsqlite_file_name = \"database.db\"\r\nsqlite_url = f\"sqlite:///{sqlite_file_name}\"\r\n\r\nengine = create_engine(sqlite_url, echo=True) # remove echo for prod\r\n\r\n\r\ndef create_db_and_tables():\r\n try:\r\n Hero.__table__.drop(engine)\r\n except sqlalchemy.exc.OperationalError: # table doesn't exist yet\r\n pass\r\n SQLModel.metadata.create_all(engine)\r\n\r\n\r\ndef create_heroes():\r\n heros = [\r\n Hero(name=\"Deadpond\", secret_name=\"Dive Wilson\"),\r\n Hero(name=\"Spider-Boy\", secret_name=\"Pedro Parqueador\"),\r\n Hero(name=\"Rusty-Man\", secret_name=\"Tommy Sharp\", age=48),\r\n Hero(name=\"Tarantula\", secret_name=\"Natalia Roman-on\", age=32),\r\n Hero(name=\"Black Lion\", secret_name=\"Trevor Challa\", age=35),\r\n Hero(name=\"Dr. Weird\", secret_name=\"Steve Weird\", age=36),\r\n Hero(name=\"Captain North America\", secret_name=\"Esteban Rogelios\", age=93),\r\n ]\r\n\r\n with Session(engine) as session:\r\n for hero in heros:\r\n session.add(hero)\r\n session.commit()\r\n\r\n\r\ndef select_heroes():\r\n with Session(engine) as session:\r\n for hero in session.exec(select(Hero)):\r\n print(hero.id)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n while True:\r\n try:\r\n create_db_and_tables()\r\n create_heroes()\r\n select_heroes()\r\n except ValueError:\r\n raise\r\n```\r\n\r\n#### Cleansed Traceback\r\n\r\n```\r\nTraceback (most recent call last):\r\n File “/…/sqlmodel_tutorial/minimal_example.py\", line 89, in \u003cmodule>\r\n select_heroes()\r\n File “/…/sqlmodel_tutorial/minimal_example.py\", line 80, in select_heroes\r\n for hero in session.exec(select(Hero)):\r\n File \"/.../lib/python3.8/site-packages/sqlalchemy/engine/result.py\", line 381, in iterrows\r\n for row in self._fetchiter_impl():\r\n File \"/.../lib/python3.8/site-packages/sqlalchemy/orm/loading.py\", line 147, in chunks\r\n fetch = cursor._raw_all_rows()\r\n File \"/.../lib/python3.8/site-packages/sqlalchemy/engine/result.py\", line 392, in _raw_all_rows\r\n return [make_row(row) for row in rows]\r\n File \"/.../lib/python3.8/site-packages/sqlalchemy/engine/result.py\", line 392, in \u003clistcomp>\r\n return [make_row(row) for row in rows]\r\n File \"/.../lib/python3.8/site-packages/sqlalchemy/sql/type_api.py\", line 1430, in process\r\n return process_value(value, dialect)\r\n File \"/.../lib/python3.8/site-packages/sqlmodel/sql/sqltypes.py\", line 61, in process_result_value\r\n value = uuid.UUID(value)\r\n File “/…/lib/python3.8/uuid.py\", line 171, in __init__\r\n raise ValueError('badly formed hexadecimal UUID string')\r\nValueError: badly formed hexadecimal UUID string\r\n```\r\n\r\n\r\n### Description\r\n\r\nRunning through the tutorial up until around [this point](https://sqlmodel.tiangolo.com/tutorial/select/), I tried swapping out the `int` id key for a `UUID` key.\r\n\r\nThis works _except_ whenever the `uuid.uuid4` default factory creates a UUID with a hexstring that starts with a zero. \r\n\r\nIt appears that [here](https://github.com/tiangolo/sqlmodel/blob/02da85c9ec39b0ebb7ff91de3045e0aea28dc998/sqlmodel/sql/sqltypes.py#L52) in `sqltypes.py` that, rather than using [`UUID().hex`](https://docs.python.org/3/library/uuid.html#uuid.UUID.hex), `sqltypes.py` carries on sqlalchemy's [integer stringification apprach](https://docs.sqlalchemy.org/en/14/core/custom_types.html?highlight=guid#backend-agnostic-guid-type), however, doesn't include any padding declaration.\r\n\r\nIMO there are two options; \r\n1. faithfully fix the replication of SQLAlchemy's `UUID` ▶️ `int` ▶️ `str` approach with the padding fixed (`f\"{v.int:032x}\"`)\r\n2. switch to using the stdlib `UUID.hex` implementation for serialisation\r\n\r\nPersonally I'm a fan of the latter so will spin up a PR \r\n\r\n### Operating System\r\n\r\nmacOS\r\n\r\n### Operating System Details\r\n\r\n_No response_\r\n\r\n### SQLModel Version\r\n\r\n0.0.4\r\n\r\n### Python Version\r\n\r\n3.8.8\r\n\r\n### Additional Context\r\n\r\n_No response_","author":{"url":"https://github.com/andrewbolster","@type":"Person","name":"andrewbolster"},"datePublished":"2021-08-26T05:55:25Z","url":"https://github.com/fastapi/sqlmodel/issues/25"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:59128df7-b619-877c-6dbe-fb629fe0ad4c |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | C4B0:3D7683:44F4DB:61D9D9:6AFDEA6F |
| html-safe-nonce | ee37753783f52931fb5e9dbaf87c95587db4189c8c4d8fb0c37a131a345b0a2f |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJDNEIwOjNENzY4Mzo0NEY0REI6NjFEOUQ5OjZBRkRFQTZGIiwidmlzaXRvcl9pZCI6IjczODc4NTk0NjA1MjMxNTgxMjciLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 8087f395c11ba52b2f69ebdbfb2a00b3df81ae9947614a62edc872bde1d62969 |
| hovercard-subject-tag | issue:979863543 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/fastapi/sqlmodel/25/issue_layout |
| twitter:image | https://opengraph.githubassets.com/9f67d1512db5fafce7ea7421e0182cbc7cb7b0f2a7f71b8f4a6e1093acdbc368/fastapi/sqlmodel/issues/25 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/9f67d1512db5fafce7ea7421e0182cbc7cb7b0f2a7f71b8f4a6e1093acdbc368/fastapi/sqlmodel/issues/25 |
| og:image:alt | First Check I added a very descriptive title to this issue. I used the GitHub search to find a similar issue and didn't find it. I searched the SQLModel documentation, with the integrated search. I... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | andrewbolster |
| hostname | github.com |
| expected-hostname | github.com |
| None | 91ef1a291a064ac31ac459ab3f75261dbdd924c41ea5bd027e591c5b46cc9ce7 |
| turbo-cache-control | no-preview |
| go-import | github.com/fastapi/sqlmodel git https://github.com/fastapi/sqlmodel.git |
| octolytics-dimension-user_id | 156354296 |
| octolytics-dimension-user_login | fastapi |
| octolytics-dimension-repository_id | 399495186 |
| octolytics-dimension-repository_nwo | fastapi/sqlmodel |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 399495186 |
| octolytics-dimension-repository_network_root_nwo | fastapi/sqlmodel |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | d62bc98ce2346f4006e4a2810e9e22f37e7e6422 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width