Get table columns in SQL Alchemy (1.0.4)

I realized that in the latest version of SQLAlchemy (v1.0.4) I get errors when using table.c.keys () to select columns.

from sqlalchemy import MetaData
from sqlalchemy import (Column, Integer, Table, String, PrimaryKeyConstraint)

metadata = MetaData()

table = Table('test', metadata,
        Column('id', Integer,nullable=False),
        Column('name', String(20)),
        PrimaryKeyConstraint('id')
    )

stmt = select(table.c.keys()).select_from(table).where(table.c.id == 1)

In previous versions, it worked fine, but now it causes the following errors:

sqlalchemy/sql/elements.py:3851: SAWarning: Textual column expression 'id' should be explicitly declared with text('id'), or use column('id') for more specificity.
sqlalchemy/sql/elements.py:3851: SAWarning: Textual column expression 'name' should be explicitly declared with text('name'), or use column('name') for more specificity.

Is there a function to extract all of these table columns, and not to use list comprehension, for example: [text(x) for x in table.c.keys()]

+4
source share
1 answer

No, but you can always use your own.

def all_columns(model_or_table, wrap=text):
    table = getattr(model_or_table, '__table__', model_or_table)
    return [wrap(col) for col in table.c.keys()]

then you would use it as

stmt = select(all_columns(table)).where(table.c.id == 1)

or

stmt = select(all_columns(Model)).where(Model.id == 1)

Please note that in most cases you do not need select_from, i.e. when you are not actually joining any other table.

0
source

All Articles