The following code snippet is an SQL Alchemy ORM table definition class.
class HtmlData(MyBase):
__tablename__ = 'html_data_table_name'
html_id: Mapped[int] = mapped_column(primary_key=True)
html_div: Mapped[str]
html_div_md5: Mapped[str]
If I run the create_all
command from within Python code, this will create a table where the column html_div_md5
has the type varchar
.
However, this is a varchar
of unconstrained length.
This doesn’t make a huge amount of sense, since md5
hashes are all 128 bits in length, or 16 bytes long.
It is likely that specifying the length to be fixed to be 16 bytes will improve performance, and it will almost certainly reduce the required data storage size. (I might be able to test this.)
How can I fix the length of html_div_md5
using the Mapped[str]
syntax?
The solution is to use the SQL Alchemy String
datatype, which can be imported and used as follows.
from sqlalchemy import String
class HtmlData(MyBase):
__tablename__ = 'html_data_table_name'
html_id: Mapped[int] = mapped_column(primary_key=True)
html_div: Mapped[str]
html_div_md5: Mapped[str] = mapped_column(String(16))