TypedParameterSqlParser.java

package net.morimekta.proto.jdbi.v3.util;

import org.jdbi.v3.core.cache.JdbiCache;
import org.jdbi.v3.core.cache.internal.DefaultJdbiCacheBuilder;
import org.jdbi.v3.core.statement.ParsedSql;
import org.jdbi.v3.core.statement.SqlParser;
import org.jdbi.v3.core.statement.StatementContext;

import java.util.regex.Pattern;

/**
 * Parse SQL arguments with ':' prefix, dotted separation between field names, and '|'
 * before the designated type. Can be put in combination with {@link MessageNamedArgumentFinder}
 * to designate the argument types in the SQL itself, where the argument finder will convert
 * the value (best effort) to the correct SQL type. Note that there must be no spaces around
 * the pipe ('|') for the type.
 * <p>
 * <b>Examples:</b>
 * <ul>
 *     <li><code>?</code> Standard positional argument.</li>
 *     <li><code>?|type</code>
 *         Positional argument with 'type' SQL type, this variant will only
 *         work with the message itself in the {@link MessageNamedArgumentFinder}.
 *     </li>
 *     <li><code>:name</code> Standard named (and positional) argument.</li>
 *     <li><code>:name|type</code> Named argument with 'type' SQL type.</li>
 *     <li><code>:name.field</code> Named argument with subfield.</li>
 *     <li><code>:name.field|type</code> Named argument with subfield and 'type' SQL type.</li>
 * </ul>
 */
public class TypedParameterSqlParser implements SqlParser {
    private final JdbiCache<String, ParsedSql> parsedSqlCache;

    public TypedParameterSqlParser() {
        parsedSqlCache = DefaultJdbiCacheBuilder
                .builder()
                .maxSize(1000)
                .buildWithLoader(this::parseInternal);
    }

    @Override
    public ParsedSql parse(String sql, StatementContext ctx) {
        return parsedSqlCache.get(sql);
    }

    @Override
    public String nameParameter(String rawName, StatementContext ctx) {
        return rawName;
    }

    private ParsedSql parseInternal(String sql) {
        ParsedSql.Builder builder = ParsedSql.builder();
        StringBuilder     buffer  = new StringBuilder();

        var var = false;
        for (int i = 0; i < sql.length(); i++) {
            var ch = sql.charAt(i);
            if (var) {
                if (VALID_NAME_CHARS.matcher(String.valueOf(ch)).matches()) {
                    buffer.append(ch);
                } else {
                    var str = buffer.toString();
                    if (VALID_NAME.matcher(str).matches()) {
                        builder.appendNamedParameter(str);
                        buffer = new StringBuilder();
                        buffer.append(ch);
                        var = false;
                    } else {
                        throw new IllegalArgumentException("Invalid name: " + str);
                    }
                }
            } else if (ch == ':') {
                var = true;
                if (buffer.length() > 0) {
                    builder.append(buffer.toString());
                    buffer = new StringBuilder();
                }
            } else if (ch == '?') {
                if (buffer.length() > 0) {
                    builder.append(buffer.toString());
                    buffer = new StringBuilder();
                }
                builder.appendPositionalParameter();
            } else {
                buffer.append(ch);
            }
        }

        if (buffer.length() > 0) {
            if (var) {
                builder.appendNamedParameter(buffer.toString());
            } else {
                builder.append(buffer.toString());
            }
        }

        return builder.build();
    }

    private static final Pattern VALID_NAME_CHARS = Pattern.compile("[a-zA-Z0-9_.|]");
    private static final Pattern VALID_NAME       = Pattern.compile(
            "([a-zA-Z][a-zA-Z0-9_]*)(\\.[a-zA-Z][a-zA-Z0-9_]*)*(\\|[a-zA-Z]+)?");
}