All files / lib QueryParser.js

100% Statements 82/82
86.84% Branches 33/38
100% Functions 13/13
100% Lines 82/82
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 2486x 6x                                   6x   6x               6x                   6x           6x 6x                   1310x     1310x 319x     991x 1514x   991x                     200x                   222x 222x               222x 222x 222x 222x     222x     222x 1110x     222x                   20x     20x 60x 39x       20x                     189x 189x   189x 189x   189x     198x     198x 79x 119x 5x   114x       198x     198x 198x 198x 198x 198x 198x 198x       198x 8x   8x 8x 8x           198x 12x   12x 12x 12x           198x   20x         198x 214x 214x   214x       198x 198x 198x 198x 198x                   198x 188x 176x   176x 171x 171x         198x     189x 189x 189x   189x       6x  
const XRegExp = require('xregexp');
const Helpers = require('./Helpers');
 
// --------------------------------------------------------------------------
 
/**
 * Internal object for parsing query fragments
 *
 * @private
 * @param {Driver} driver - The driver object for the database in use
 */
class QueryParser {
	/**
	 * @constructor
	 *
	 * @param {Driver} driver - The driver object for the database in use
	 * @return {void}
	 */
	constructor (driver) {
		this.driver = driver;
 
		const matchPatterns = {
			function: /([a-z0-9_]+\((.*)\))/i,
			operator: /!=?|=|\+|&&?|~|\|\|?|\^|\/|<>|>=?|<=?|-|%|OR|AND|NOT|XOR/ig,
			literal: /([0-9]+)|'(.*?)'|true|false/ig
		};
 
		// Full pattern for identifiers
		// Making sure that literals and functions aren't matched
		matchPatterns.identifier = XRegExp(
			`(
				(?!
					${matchPatterns['function'].source}|
					${matchPatterns.literal.source}
				)
				([a-z_-]+[0-9]*\\.?)
			)+`, 'igx');
 
		// Full pattern for determining ordering of the pieces
		matchPatterns.joinCombined = XRegExp(
			`${matchPatterns['function'].source}+|	# functions
			${matchPatterns.literal.source}+|	# literal values
			${matchPatterns.identifier.source}	# identifiers
			|(${matchPatterns.operator.source})+`, 'igx');
 
		this.matchPatterns = matchPatterns;
		this.identifierBlacklist = ['true', 'false', 'null'];
	}
 
	/**
	 * Filter matched patterns
	 *
	 * @param {Array} array - Set of possible matches
	 * @return {Array|null} - Filtered set of possible matches
	 */
	filterMatches (array) {
		const output = [];
 
		// Return non-array matches
		if (Helpers.isNull(array)) {
			return null;
		}
 
		array.forEach(item => {
			output.push(item);
		});
		return output;
	}
 
	/**
	 * Check if the string contains an operator, and if so, return the operator(s).
	 * If there are no matches, return null
	 *
	 * @param {String} string - the string to check
	 * @return {Array|null} - List of operators
	 */
	hasOperator (string) {
		return this.filterMatches(string.match(this.matchPatterns.operator));
	}
 
	/**
	 * Tokenize the sql into parts for additional processing
	 *
	 * @param {String} sql - Join sql to parse
	 * @return {Object} - Join condition components
	 */
	parseJoin (sql) {
		const matches = {};
		const output = {
			functions: [],
			identifiers: [],
			operators: [],
			literals: []
		};
 
		// Get clause components
		matches.functions = sql.match(new RegExp(this.matchPatterns['function'].source, 'ig'));
		matches.identifiers = sql.match(this.matchPatterns.identifier);
		matches.operators = sql.match(this.matchPatterns.operator);
		matches.literals = sql.match(this.matchPatterns.literal);
 
		// Get everything at once for ordering
		matches.combined = sql.match(this.matchPatterns.joinCombined);
 
		// Flatten the matches to increase relevance
		Object.keys(matches).forEach(key => {
			output[key] = this.filterMatches(matches[key]);
		});
 
		return output;
	}
 
	/**
	 * Return the output of the parsing of the join condition
	 *
	 * @param {String} condition - The join condition to evaluate
	 * @return {String} - The parsed/escaped join condition
	 */
	compileJoin (condition) {
		const parts = this.parseJoin(condition);
 
		// Quote the identifiers
		parts.combined.forEach((part, i) => {
			if (parts.identifiers.indexOf(part) !== -1 && !Helpers.isNumber(part)) {
				parts.combined[i] = this.driver.quoteIdentifiers(part);
			}
		});
 
		return parts.combined.join(' ');
	}
 
	/**
	 * Parse a where clause to separate functions from values
	 *
	 * @param {Driver} driver - The current db driver
	 * @param {State} state - Query Builder state object
	 * @return {String} - The parsed/escaped where condition
	 */
	parseWhere (driver, state) {
		const whereMap = state.whereMap;
		let	whereValues = state.rawWhereValues;
 
		const outputMap = [];
		const outputValues = [];
 
		Object.keys(whereMap).forEach(key => {
			// Combine fields, operators, functions and values into a full clause
			// to have a common starting flow
			let fullClause = '';
 
			// Add an explicit = sign where one is inferred
			if (!this.hasOperator(key)) {
				fullClause = `${key} = ${whereMap[key]}`;
			} else if (whereMap[key] === key) {
				fullClause = key;
			} else {
				fullClause = `${key} ${whereMap[key]}`;
			}
 
			// Separate the clause into separate pieces
			const parts = this.parseJoin(fullClause);
 
			// Filter explicit literals from lists of matches
			Eif (whereValues.indexOf(whereMap[key]) !== -1) {
				const value = whereMap[key];
				const identIndex = parts.identifiers.indexOf(value);
				const litIndex = (Helpers.isArray(parts.literals)) ? parts.literals.indexOf(value) : -1;
				const combIndex = parts.combined.indexOf(value);
				const funcIndex = (Helpers.isArray(parts.functions)) ? parts.functions.indexOf(value) : -1;
				let inOutputArray = outputValues.includes(value);
 
				// Remove the identifier in question,
				// and add to the output values array
				if (identIndex !== -1) {
					parts.identifiers.splice(identIndex, 1);
 
					Eif (!inOutputArray) {
						outputValues.push(value);
						inOutputArray = true;
					}
				}
 
				// Remove the value from the literals list
				// so it is not added twice
				if (litIndex !== -1) {
					parts.literals.splice(litIndex, 1);
 
					Eif (!inOutputArray) {
						outputValues.push(value);
						inOutputArray = true;
					}
				}
 
				// Remove the value from the combined list
				// and replace it with a placeholder
				if (combIndex !== -1 && funcIndex === -1) {
					// Make sure to skip functions when replacing values
					parts.combined[combIndex] = '?';
				}
			}
 
			// Filter false positive identifiers
			parts.identifiers = parts.identifiers.filter(item => {
				const isInCombinedMatches = parts.combined.indexOf(item) !== -1;
				const isNotInBlackList = this.identifierBlacklist.indexOf(item.toLowerCase()) === -1;
 
				return isInCombinedMatches && isNotInBlackList;
			}, this);
 
			// Quote identifiers
			Eif (Helpers.isArray(parts.identifiers)) {
				parts.identifiers.forEach(ident => {
					const index = parts.combined.indexOf(ident);
					Eif (index !== -1) {
						parts.combined[index] = driver.quoteIdentifiers(ident);
					}
				});
			}
 
			// Replace each literal with a placeholder in the map
			// and add the literal to the values,
			// This should only apply to literal values that are not
			// explicitly mapped to values, but have to be parsed from
			// a where condition,
			if (Helpers.isArray(parts.literals)) {
				parts.literals.forEach(lit => {
					const litIndex = parts.combined.indexOf(lit);
 
					if (litIndex !== -1) {
						parts.combined[litIndex] = '?';
						outputValues.push(lit);
					}
				});
			}
 
			outputMap.push(parts.combined.join(' '));
		});
 
		state.rawWhereValues = [];
		state.whereValues = state.whereValues.concat(outputValues);
		state.whereMap = outputMap;
 
		return state;
	}
}
 
module.exports = QueryParser;