python - 在 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 )。
解决方案
我找到了一种以“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”,因为我在删除表后无法重现此行为。所以这个解决方案看起来不错:)!!!
推荐阅读
- php - Telegram Bot 和 Mysqli_fetch_assoc 问题
- karate - java.lang.NoSuchFieldError:使用空手道时的 toStringWriter
- python - 在将代码段分配到子程序之前的程序工作
- java - 如何从 Groovy 中的字符串中获取列表?
- multithreading - 如何从 TThread 显示“请稍候”模式表单并在工作完成后释放它?
- matlab - MATLAB - 无法导入 cv2 库
- java - 数据库错误:预分配序列号时出错
- google-calendar-api - 在某个日期之后更新重复事件
- virtual-machine - 内存大小增加的 Windows 10 沙盒自定义配置
- php - 在 php stripe 上获取“无法向没有活动卡的客户收费”