使用 jooq 创建查询字符串时如何转义单引号?

How to escape single quotes while creating a query string with jooq?

我正在尝试通过以下方式创建一个 jooq 查询字符串

DSL.using(SQLDialect.MYSQL)
            .select(
                    ImmutableList.of(DSL.field("Name"))
            .from(DSL.table("Account"))
            .where(DSL.field("Name").eq("Yaswanth's Company"))).toString()

生成的查询字符串将单引号转义为另一个单引号,这是转义单引号的默认 mySQL 方式。

"select Name from Account where Name = 'Yaswanth''s Company'"

但是在为 salesforce 形成查询字符串时,我需要使用反斜杠对单引号进行转义。 (称为 SOQL)。

我需要这样的查询字符串

"select Name from Account where Name = 'Yaswanth\'s Company'"

我查看了 jooq 库代码,这是在 DefaultBinding 中硬编码的 class

private final String escape(Object val, Context<?> context) {
    String result = val.toString();

    if (needsBackslashEscaping(context.configuration()))
        result = result.replace("\", "\\");

    return result.replace("'", "''");
}

有没有办法让我通过 DSL.using(*, *) 可以传递的配置或设置来覆盖此默认行为?

大多数 SQL 数据库遵循 SQL 标准,将单引号加倍以进行转义,但是使此功能可配置当然是有意义的。我们可能会使用 #5873.

为 jOOQ 3.10 执行此操作

与此同时,最适合您的解决方法是为所有字符串类型编写您自己的 data type binding 并在生成 SQL 字符串时覆盖 DefaultBinding 行为。大致是这样的:

代码生成配置

使用<forcedTypes/>

<forcedType>
    <userType>java.lang.String</userType>
    <binding>com.example.AlternativeEscapingStringBinding</binding>
    <!-- add other vendor-specific string type names here -->
    <types>(?i:N?(VAR)?CHAR|TEXT|N?CLOB)</types>
</forcedType>

数据类型绑定

public class AlternativeEscapingStringBinding implements Binding<String, String> {
    ...

    @Override
    public void sql(BindingSQLContext<String> ctx) throws SQLException {
        if (ctx.paramType() == ParamType.INLINED) 
            if (ctx.value() == null)
                ctx.render().sql('null');
            else
                ctx.render()
                   .sql('\'')
                   .sql(ctx.value().replace("'", "\'"))
                   .sql('\'');
        else
            ctx.render().sql('?');
    }
}

如果您没有使用代码生成器

您仍然可以手动将自己的数据类型绑定应用到您的字段:

DSL.field("Name", SQLDataType.VARCHAR
                             .asConvertedDataType(new AlternativeEscapingStringBinding()));

你每次都必须记住这一点...