【问题标题】:Prevent non-ASCII strings being written to Column防止将非 ASCII 字符串写入 Column
【发布时间】:2016-12-09 11:17:22
【问题描述】:

我想防止将非 ASCII 字符串写入我的 postgres db 表中的特定列。我考虑过使用constrains,但在尝试使用任何编码转换函数时都会收到错误消息。使用 lowerbtrim 等其他字符串函数没有问题。

metadata = MetaData()
constrains = [CheckConstraint('lower(name) = name', name='enforce_lower'),
            CheckConstraint('utf8_to_ascii(name) = name', name='prevent_non_ascii')]
concepts_table = Table('test20', metadata,
                       Column('name', Text, *constrains))
metadata.create_all(engine, checkfirst=False)    

错误信息是:

(ProgrammingError) function utf8_to_ascii(text) does not exist

这是我的 postgresql 版本:

SELECT version();
PostgreSQL 9.5.2 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.2 20140120 (Red Hat 4.8.2-16), 64-bit

【问题讨论】:

    标签: postgresql unicode sqlalchemy


    【解决方案1】:

    postgresql 中没有 utf8_to_ascii(text) 函数(如错误消息所述;))。而是定义了这个名称的转换(更多关于转换:https://www.postgresql.org/docs/current/static/sql-createconversion.html):https://www.postgresql.org/docs/current/static/functions-string.html#CONVERSION-NAMES

    要利用现有的转换,请使用convert(string bytea, src_encoding name, dest_encoding name)

    尝试使用以下约束定义:

    CheckConstraint("encode(convert(name::bytea, 'UTF8'::name, 'SQL_ASCII'::name), 'escape') = name", name='prevent_non_ascii')
    

    【讨论】:

    • 谢谢!但这会导致以下错误:(ProgrammingError) function convert(text, unknown, unknown) does not exist HINT: No function matches the given name and argument types. You might need to add explicit type casts.
    • 现在它说(ProgrammingError) function convert(text, name, name) does not exist HINT: No function matches the given name and argument types. You might need to add explicit type casts. 我也在这个网站上找到了utf6_to_ascii:postgresql.org/docs/current/static/functions-string.html
    • 再次更新 ;),嗯……我在那儿看不到 utf6_to_ascii
    猜你喜欢
    • 1970-01-01
    • 2014-04-04
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 2012-08-29
    • 2014-04-05
    • 2016-11-20
    • 1970-01-01
    相关资源
    最近更新 更多