TypedParameterSqlParser.java

/*
 * Copyright 2022 Proto Utils Authors
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
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>
 * <p>
 * Specify the parser by setting the {@code @UseSqlParser(TypedParameterSqlParser.class)} annotation:
 * <pre>{@code
 * {@literal@}UseSqlParser(TypedParameterSqlParser.class)
 * public interface MyDao {}
 * }</pre>
 */
public class TypedParameterSqlParser implements SqlParser {
    private final JdbiCache<String, ParsedSql> parsedSqlCache;

    /**
     * Create a new typed parameter SQL parser.
     */
    public TypedParameterSqlParser() {
        parsedSqlCache = DefaultJdbiCacheBuilder
                .builder()
                .maxSize(1000)
                .buildWithLoader(this::parseInternal);
    }

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

    /** {@inheritDoc} */
    @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 inName = false;
        for (int i = 0; i < sql.length(); i++) {
            var ch = sql.charAt(i);
            if (inName) {
                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);
                        inName = false;
                    } else {
                        throw new IllegalArgumentException("Invalid name: ':" + str + "'");
                    }
                }
            } else if (ch == ':') {
                builder.append(buffer.toString());
                buffer = new StringBuilder();
                inName = true;
            } else if (ch == '?') {
                builder.append(buffer.toString());
                buffer = new StringBuilder();
                builder.appendPositionalParameter();
            } else {
                buffer.append(ch);
            }
        }

        if (buffer.length() > 0) {
            if (inName) {
                var str = buffer.toString();
                if (VALID_NAME.matcher(str).matches()) {
                    builder.appendNamedParameter(str);
                } else {
                    throw new IllegalArgumentException("Invalid name: ':" + str + "'");
                }
            } 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]+)?$");
}