com.github.chengyuxing.sql.support.SqlParser Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of rabbit-sql Show documentation
Show all versions of rabbit-sql Show documentation
Light wrapper of JDBC, support ddl, dml, query, plsql/procedure/function, transaction and manage sql
file.
package com.github.chengyuxing.sql.support;
import com.github.chengyuxing.common.tuple.Pair;
import com.github.chengyuxing.sql.utils.SqlGenerator;
import java.util.List;
import java.util.Map;
/**
* Support parse named parameter sql
* Named parameter prefix symbol depends on implementation of {@link #sqlGenerator()}.
* Named parameter format e.g if named parameter prefix is '{@code :}' :
*
* - {@code :name} (jdbc standard named parameter format, it will parsed to '{@code ?}').
*
* String template ({@code ${...}} will not be prepared) variable format:
*
* - {@code ${var}}: if boxed basic type array ({@link String String[]}, {@link Integer Integer[]}, ...) or ({@link java.util.Set Set}, {@link List List}, ...) detected, just expand and replace;
* - {@code ${!var}}: starts with '{@code !}', if boxed basic type array ({@link String String[]}, {@link Integer Integer[]}, ...) or ({@link java.util.Set Set}, {@link List List}, ...) detected, expand and wrap safe single quotes, then replace.
*
* Notice: in postgresql, some symbol operator such as ({@code ?}, {@code ?|}, {@code ?&}, {@code @?}) should be write double '{@code ?}' ({@code ??}, {@code ??|}, {@code ??&}, {@code @??}) to avoid prepare sql error or use function to replace.
* e.g. postgresql sql statement:
*
*
* select t.id || 'number' || 'name:cyx','{"name": "user"}'::jsonb
* from test.user t
* where id = :id::integer
* and id > :idc
* and name = text :username
* and '["a","b","c"]'::jsonb ??& array ['a', 'b']
* ${cnd}
*
*
* @see SqlGenerator
*/
public abstract class SqlParser {
/**
* Do some prepare work for parse source sql.
*
* @param sql sql
* @param args args
* @return parsed sql and args
*/
protected abstract Pair> parseSql(String sql, Map args);
/**
* Sql translator for support prepare sql.
*
* @return Sql translator.
*/
protected abstract SqlGenerator sqlGenerator();
/**
* Convert named parameter sql to prepared sql.
*
* @param sql named parameter sql
* @param args args
* @return GeneratedSqlMetaData
*/
protected SqlGenerator.GeneratedSqlMetaData prepare(String sql, Map args) {
// try to generate full named parameter sql.
Pair> result = parseSql(sql, args);
String parsedSql = result.getItem1();
Map parsedArgs = result.getItem2();
// convert named parameter sql to prepared sql.
return sqlGenerator().generatePreparedSql(parsedSql, parsedArgs);
}
}