java/sql-dk/src/info/globalcode/sql/dk/SQLCommandNamed.java
author František Kučera <franta-hg@frantovo.cz>
Thu, 26 Dec 2013 11:58:14 +0100
branchv_0
changeset 68 574cd7fbb5b2
parent 61 deba1f6600f8
child 78 d98f33d91553
permissions -rw-r--r--
SQLType enum wrapper for java.sql.Types
     1 /**
     2  * SQL-DK
     3  * Copyright © 2013 František Kučera (frantovo.cz)
     4  *
     5  * This program is free software: you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License as published by
     7  * the Free Software Foundation, either version 3 of the License, or
     8  * (at your option) any later version.
     9  *
    10  * This program is distributed in the hope that it will be useful,
    11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  * GNU General Public License for more details.
    14  *
    15  * You should have received a copy of the GNU General Public License
    16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
    17  */
    18 package info.globalcode.sql.dk;
    19 
    20 import static info.globalcode.sql.dk.Functions.notNull;
    21 import static info.globalcode.sql.dk.Functions.findByName;
    22 import java.sql.Connection;
    23 import java.sql.PreparedStatement;
    24 import java.sql.SQLException;
    25 import java.util.ArrayList;
    26 import java.util.List;
    27 import java.util.logging.Level;
    28 import java.util.logging.Logger;
    29 import java.util.regex.Matcher;
    30 import java.util.regex.Pattern;
    31 import java.util.regex.PatternSyntaxException;
    32 
    33 /**
    34  *
    35  * @author Ing. František Kučera (frantovo.cz)
    36  */
    37 public class SQLCommandNamed extends SQLCommand {
    38 
    39 	private static final Logger log = Logger.getLogger(SQLCommandNamed.class.getName());
    40 	private String namePrefix;
    41 	private String nameSuffix;
    42 	private List<NamedParameter> parameters;
    43 	private List<NamedParameter> parametersUsed = new ArrayList<>();
    44 	private StringBuilder updatedQuery;
    45 	private Pattern pattern;
    46 
    47 	public SQLCommandNamed(String query, List<NamedParameter> parameters, String namePrefix, String nameSuffix) {
    48 		super(query);
    49 		this.updatedQuery = new StringBuilder(query.length());
    50 		this.parameters = parameters;
    51 		this.namePrefix = namePrefix;
    52 		this.nameSuffix = nameSuffix;
    53 	}
    54 
    55 	@Override
    56 	public PreparedStatement prepareStatement(Connection c) throws SQLException {
    57 		try {
    58 			buildPattern();
    59 			placeParametersAndUpdateQuery();
    60 			logPossiblyMissingParameters();
    61 		} catch (PatternSyntaxException e) {
    62 			throw new SQLException("Name prefix „" + namePrefix + "“ or suffix „" + nameSuffix + "“ contain a wrong regular expression. " + e.getLocalizedMessage(), e);
    63 		}
    64 		return c.prepareStatement(updatedQuery.toString());
    65 	}
    66 
    67 	@Override
    68 	public void parametrize(PreparedStatement ps) throws SQLException {
    69 		int i = 1;
    70 		for (Parameter p : notNull(parametersUsed)) {
    71 			ps.setObject(i++, p.getValue(), p.getType().getCode());
    72 		}
    73 	}
    74 
    75 	/**
    76 	 * Builds a regexp pattern that matches all parameter names (with prefix/suffix) and which has
    77 	 * one group: parameter name (without prefix/suffix)
    78 	 */
    79 	private void buildPattern() {
    80 		StringBuilder patternString = new StringBuilder();
    81 
    82 		patternString.append(namePrefix);
    83 		patternString.append("(?<paramName>");
    84 		for (int i = 0; i < parameters.size(); i++) {
    85 			patternString.append(Pattern.quote(parameters.get(i).getName()));
    86 			if (i < parameters.size() - 1) {
    87 				patternString.append("|");
    88 			}
    89 		}
    90 		patternString.append(")");
    91 		patternString.append(nameSuffix);
    92 
    93 		pattern = Pattern.compile(patternString.toString());
    94 	}
    95 
    96 	private void placeParametersAndUpdateQuery() throws SQLException {
    97 		final String originalQuery = getQuery();
    98 		Matcher m = pattern.matcher(originalQuery);
    99 
   100 		int lastPosition = 0;
   101 		while (m.find(lastPosition)) {
   102 			String name = m.group("paramName");
   103 
   104 			updatedQuery.append(originalQuery.substring(lastPosition, m.start()));
   105 			updatedQuery.append("?");
   106 
   107 			parametersUsed.add(findByName(parameters, name));
   108 
   109 			lastPosition = m.end();
   110 		}
   111 		updatedQuery.append(originalQuery.substring(lastPosition, originalQuery.length()));
   112 
   113 		for (NamedParameter definedParameter : parameters) {
   114 			if (findByName(parametersUsed, definedParameter.getName()) == null) {
   115 				/**
   116 				 * User can have predefined set of parameters and use them with different SQL
   117 				 * queries that use only subset of these parameters → just warning, not exception.
   118 				 */
   119 				log.log(Level.WARNING, "Parameter „{0}“ is defined but not used in the query: „{1}“", new Object[]{definedParameter.getName(), originalQuery});
   120 			}
   121 		}
   122 	}
   123 
   124 	private void logPossiblyMissingParameters() {
   125 		Pattern p = Pattern.compile(namePrefix + "(?<paramName>.*?)" + nameSuffix);
   126 		Matcher m = p.matcher(updatedQuery);
   127 		int lastPosition = 0;
   128 		while (m.find(lastPosition)) {
   129 			/**
   130 			 * We have not parsed and understood the SQL query; the parameter-like looking string
   131 			 * could be inside a literal part of the query → just warning, not exception.
   132 			 */
   133 			log.log(Level.WARNING, "Possibly missing parameter „{0}“ in the query: „{1}“", new Object[]{m.group("paramName"), getQuery()});
   134 			lastPosition = m.end();
   135 		}
   136 	}
   137 
   138 	@Override
   139 	public List<NamedParameter> getParameters() {
   140 		return parameters;
   141 	}
   142 }