首页 > 解决方案 > 在 sql alchemy 中转义表名

问题描述

我需要自动转义任何sqlalchemy 引擎的表名(我想扩展我为除 postgres 之外的其他数据库创建的库,请参阅帖子末尾的详细信息部分)。

像这样的列是可能的:

from sqlalchemy.sql import column
from sqlalchemy import create_engine

engine = create_engine("sqlite:///test.db")
escaped_column = column('%"my_column123?').compile(dialect=engine.dialect)
str(escaped_column)
'"%""my_column123?"'

我(天真地)尝试了以下但它不起作用(返回一个空字符串):

from sqlalchemy.sql import table
from sqlalchemy import create_engine

engine = create_engine("sqlite:///test.db")
escaped_table_name = table("%table?&;").compile(dialect=engine.dialect)
str(escaped_table_name)
''

提前致谢!

细节

我创建了一个库来使用 pandas DataFrames 更新 PostGres 表(请参阅https://github.com/ThibTrip/pangres)并意识到部分代码不是 SQL 注入安全的(如果您对此感到好奇,这是我正在谈论的部分关于:https ://github.com/ThibTrip/pangres/blob/7cfa2d2190cf65a1ede8ef30868883f0da3fa5fc/pangres/helpers.py#L270-L290 )。

标签: pythonsqlalchemy

解决方案


我找到了一种以“sqlalchemy 方式”添加列的方法(向任何表添加列是我想要转义表名的原因)。不幸的是,它并不完美,因为它创建了一个表“alembic_version”,原因如下:

# alembic is a library from the creator of sqlalchemy to migrate databases
from alembic.runtime.migration import MigrationContext # pip install alembic
from alembic.operations import Operations
from sqlalchemy import Column, TEXT, create_engine # pip install sqlalchemy

# create engine
engine = create_engine('sqlite:///test.db')

# add column "some_new_column" of type TEXT in the table 'test'
with engine.connect() as con:
    ctx = MigrationContext.configure(con, )
    op = Operations(ctx)
    op.add_column('test', column=Column('some_new_column', TEXT))

编辑:以前的测试似乎以某种方式添加了表“alembic_version”,因为我在删除表后无法重现此行为。所以这个解决方案看起来不错:)!!!


推荐阅读