Houman
Houman

Reputation: 66320

How to represent Longtext in SqlAlchemy?

I have a trouble saving large text into MySQL database.

The model looks like this (see column receipt):

class Receipt(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    product_id = db.Column(db.String(200))
    type = db.Column(Enum(ReceiptType), nullable=False)
    receipt = db.Column(db.Text(), nullable=False)
    source = db.Column(Enum(ReceiptSource), nullable=False)
    expiry_date = db.Column(db.TIMESTAMP(), nullable=False)
    account_id = db.Column(db.Integer, db.ForeignKey(Account.id), unique=True)
    account = db.relationship('Account', back_populates="receipt")

There seem to be no LongText() in SQLALchemy, so I did the migration like this:

def upgrade():
    connection = op.get_bind()
    connection.execute("""
                ALTER TABLE main_db.receipt MODIFY COLUMN receipt LONGTEXT NOT NULL;
                """)

This is the error thrown:

sqlalchemy.exc.DataError: (MySQLdb._exceptions.DataError) (1406, "Data too long for column 'receipt' at row 1")
[SQL: INSERT INTO main_db.receipt (product_id, type, receipt, source, expiry_date, account_id) VALUES (%s, %s, %s, %s, %s, %s)]
[parameters: ('com.myCompany.myApp.ios.standard.weekly', 'STANDARD', 'MILEegYJKoZIhvcNAQcCoILEazCCxGcCAQExCzAJBgUrDgMCGgUAMIK0GwYJKoZIhvcNAQcBoIK0DASCtAgxgrQEMAoCAQgCAQEEAhYAMAoCARQCAQEEAgwAMAsCAQECAQEEAwIBADALAgEDAgEBB ... (66774 characters truncated) ... FAMZIuVFjBSqfQ0dZ0FJGtSU1dwEHJW2B8Z4uj0IzJIAlQmFcZ57lIpAlTo3zDUlTOtbZmuyhpgFlB6MQXbgm+Ewm2nCnwWwoF8v7/ZNtcma96i1X3vuujgYDYoZ/EeMWPc3Rkoea6D7POigeTg==', 'IOS', datetime.datetime(2020, 5, 8, 16, 37, 6), 14)]
(Background on this error at: http://sqlalche.me/e/9h9h)

What am I missing please?

Upvotes: 4

Views: 8978

Answers (1)

Peter Moore
Peter Moore

Reputation: 2086

The way to represent longtext type in SQLAlchemy for MySQL is:

from sqlalchemy.dialects.mysql import LONGTEXT

class Receipt(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    long_text = db.Column(LONGTEXT)

For other types refer to the SQLAlchemy documentation: https://docs.sqlalchemy.org/en/14/dialects/mysql.html#mysql-data-types

(SQLAlchemy v2.0 version: https://docs.sqlalchemy.org/en/20/dialects/mysql.html#mysql-data-types)

This works with flask-sqlalchemy too.

Upvotes: 8

Related Questions