Comparing SQLAlchemy Column Types

I do a lot of introspection of the database for different types of databases, and I would like to compare two types of columns. For example, a field that is defined as Booleanusing declarative_base()is then converted to a MySQL- specific TINYINTdialog , so check as follows:

model_a.__table__.columns['col'].type == model_b.__table__.columns['col'].type

does not work, and not one of them:

(type_a == type_b) or issubclass(type_b, type_a)

How to compare two columns for the "affinity" data type? (While checking the code, I saw that the column types have a class Comparator, but I'm not sure if it can help and how to use it) Can I also force the column type in the SQLAlchemy configuration (avoiding dialect-dependent conversions)?

+5
source share
3 answers

(Answering an old question, because I studied just that).

The quickest solution is to compare str () types:

assert str(type_a) == (type_b)

This will work for simple types, but if you have types Variantor wrappers (e.g. MutableDictwrapping Postgres JSON), you will have to handle a special case.

+2
source

For example, to check if the type is BLOB. Use this code:

import sqlalchemy as db
some code..
if type(column.type) is db.types.BLOB:
    something..
0
source

2019 - , - .

SQLAlchemy 'col', model_a model_b, :

isinstance(model_a.columns['col'].type, type(model_b.columns['col'].type)) and
isinstance(model_b.columns['col'].type, type(model_a.columns['col'].type))

isinstance (.. " A a B?" " B a A?"), , , .

, , isinstance.

0
source

Source: https://habr.com/ru/post/1624250/


All Articles