rewrite SQL.

@param isSingleRouting is rewrite
@return SQL builder
773523
public SQLBuilder rewrite(final boolean isSingleRouting) {
        SQLBuilder result = new SQLBuilder(parameters);
        if (sqlTokens.isEmpty()) {
            return appendOriginalLiterals(result);
        }
        appendInitialLiterals(!isSingleRouting, result);
        appendTokensAndPlaceholders(!isSingleRouting, result);
        reviseParameters();
        return result;
    }
752369
@Override
  public MtasSpanQuery rewrite(IndexReader reader) throws IOException {
    MtasSpanQuery newClause = clause.rewrite(reader);
    if (!newClause.equals(clause)) {
      return new MtasSpanUniquePositionQuery(newClause).rewrite(reader);
    } else {
      return super.rewrite(reader);
    }
  }
1235862
public SqlBuilder select(final String what) {
    if (null == what) {
      this.select = null;
    } else {
      if (Strings.contains(what.toLowerCase(), "select")) {
        this.select = what;
      } else {
        this.select = "select " + what;
      }
    }
    return this;
  }
1219284
protected function sql($sql = null, $replace = false)
    {
        if (null !== $sql) {
            if (!isset($this->oosql_sql[$this->oosql_table]) || $replace) {
                $this->oosql_sql[$this->oosql_table] = $sql;
            } else {

                $this->oosql_sql[$this->oosql_table] .= $sql;
            }
            return;
        }
        return $this->oosql_sql[$this->oosql_table];
    }
805111
public Object querySingleResult(String sql, String[] args, int column) {
		return db.querySingleResult(sql, args, column);
	}
235408
@Override
  public MtasSpanQuery rewrite(IndexReader reader) throws IOException {
    if (items.size() == 1) {
      MtasSpanQuery singleQuery = items.get(0).getQuery();
      if (leftMaximum != 0 || rightMaximum != 0) {
        singleQuery = new MtasExpandSpanQuery(singleQuery, leftMinimum,
            leftMaximum, rightMinimum, rightMaximum);
      }
      return singleQuery.rewrite(reader);
    } else {
      MtasSpanSequenceItem newItem;
      MtasSpanSequenceItem previousNewItem = null;
      ArrayList<MtasSpanSequenceItem> newItems = new ArrayList<>(items.size());
      int newLeftMinimum = leftMinimum;
      int newLeftMaximum = leftMaximum;
      int newRightMinimum = rightMinimum;
      int newRightMaximum = rightMaximum;
      MtasSpanQuery newIgnoreClause = ignoreQuery != null
          ? ignoreQuery.rewrite(reader) : null;
      boolean actuallyRewritten = ignoreQuery != null
          ? !newIgnoreClause.equals(ignoreQuery) : false;
      for (int i = 0; i < items.size(); i++) {
        newItem = items.get(i).rewrite(reader);
        if (newItem.getQuery() instanceof MtasSpanMatchNoneQuery) {
          if (!newItem.isOptional()) {
            return new MtasSpanMatchNoneQuery(field);
          } else {
            actuallyRewritten = true;
          }
        } else {
          actuallyRewritten |= !items.get(i).equals(newItem);
          MtasSpanSequenceItem previousMergedItem = MtasSpanSequenceItem.merge(
              previousNewItem, newItem, ignoreQuery, maximumIgnoreLength);
          if (previousMergedItem != null) {
            newItems.set((newItems.size() - 1), previousMergedItem);
            actuallyRewritten = true;
          } else {
            newItems.add(newItem);
          }
          previousNewItem = newItem;
        }
      }
      // check first and last
      if (ignoreQuery == null) {
        ArrayList<MtasSpanSequenceItem> possibleTrimmedItems = new ArrayList<>(
            newItems.size());
        MtasSpanSequenceItem firstItem = newItems.get(0);
        MtasSpanQuery firstQuery = firstItem.getQuery();
        if (firstQuery instanceof MtasSpanMatchAllQuery) {
          newLeftMaximum++;
          if (!firstItem.isOptional()) {
            newLeftMinimum++;
          }
        } else if (firstQuery instanceof MtasSpanRecurrenceQuery) {
          MtasSpanRecurrenceQuery firstRecurrenceQuery = (MtasSpanRecurrenceQuery) firstQuery;
          if (firstRecurrenceQuery.getQuery() instanceof MtasSpanMatchAllQuery
              && firstRecurrenceQuery.getIgnoreQuery() == null) {
            if (!firstItem.isOptional()) {
              newLeftMinimum += firstRecurrenceQuery.getMinimumRecurrence();
              newLeftMaximum += firstRecurrenceQuery.getMaximumRecurrence();
            } else {
              if (firstRecurrenceQuery.getMinimumRecurrence() == 1
                  || firstRecurrenceQuery
                      .getMinimumRecurrence() <= newLeftMinimum) {
                newLeftMinimum += 0;
                newLeftMaximum += firstRecurrenceQuery.getMaximumRecurrence();
              } else {
                possibleTrimmedItems.add(firstItem);
              }
            }
          } else {
            possibleTrimmedItems.add(firstItem);
          }
        } else {
          possibleTrimmedItems.add(firstItem);
        }
        for (int i = 1; i < (newItems.size() - 1); i++) {
          possibleTrimmedItems.add(newItems.get(i));
        }
        if (newItems.size() > 1) {
          MtasSpanSequenceItem lastItem = newItems.get((newItems.size() - 1));
          MtasSpanQuery lastQuery = lastItem.getQuery();
          if (lastQuery instanceof MtasSpanMatchAllQuery) {
            newRightMaximum++;
            if (!lastItem.isOptional()) {
              newRightMinimum++;
            }
          } else if (lastQuery instanceof MtasSpanRecurrenceQuery) {
            MtasSpanRecurrenceQuery lastRecurrenceQuery = (MtasSpanRecurrenceQuery) lastQuery;
            if (lastRecurrenceQuery.getQuery() instanceof MtasSpanMatchAllQuery
                && lastRecurrenceQuery.getIgnoreQuery() == null) {
              if (!lastItem.isOptional()) {
                newRightMinimum += lastRecurrenceQuery.getMinimumRecurrence();
                newRightMaximum += lastRecurrenceQuery.getMaximumRecurrence();
              } else if (lastRecurrenceQuery.getMinimumRecurrence() == 1
                  || lastRecurrenceQuery
                      .getMinimumRecurrence() <= newRightMinimum) {
                newRightMinimum += 0;
                newRightMaximum += lastRecurrenceQuery.getMaximumRecurrence();
              } else {
                possibleTrimmedItems.add(lastItem);
              }
            } else {
              possibleTrimmedItems.add(lastItem);
            }
          } else {
            possibleTrimmedItems.add(lastItem);
          }
        }
        if (possibleTrimmedItems.size() < newItems.size()) {
          actuallyRewritten = true;
          newItems = possibleTrimmedItems;
        }
      }
      if (!actuallyRewritten) {
        if (leftMaximum != 0 || rightMaximum != 0) {
          newLeftMinimum = leftMinimum;
          newLeftMaximum = leftMaximum;
          newRightMinimum = rightMinimum;
          newRightMaximum = rightMaximum;
          leftMinimum = 0;
          leftMaximum = 0;
          rightMinimum = 0;
          rightMaximum = 0;
          MtasSpanQuery finalQuery = new MtasExpandSpanQuery(this,
              newLeftMinimum, newLeftMaximum, newRightMinimum, newRightMaximum);
          return finalQuery.rewrite(reader);
        } else {
          return super.rewrite(reader);
        }
      } else {
        if (!newItems.isEmpty()) {
          return new MtasSpanSequenceQuery(newItems, newLeftMinimum,
              newLeftMaximum, newRightMinimum, newRightMaximum, newIgnoreClause,
              maximumIgnoreLength).rewrite(reader);
        } else {
          return new MtasSpanMatchNoneQuery(field);
        }
      }
    }
  }
171270
private static void generateSQLBuild(SQLiteModelMethod method, MethodSpec.Builder methodBuilder, SplittedSql splittedSql, boolean countQuery) {
		methodBuilder.addStatement("$T _sqlBuilder=sqlBuilder()", StringBuilder.class);
		methodBuilder.addStatement("_sqlBuilder.append($S)", splittedSql.sqlBasic.trim());

		SqlModifyBuilder.generateInitForDynamicWhereVariables(method, methodBuilder, method.dynamicWhereParameterName, method.dynamicWhereArgsParameterName);

		if (method.jql.isOrderBy()) {
			methodBuilder.addStatement("String _sortOrder=$L", method.jql.paramOrderBy);
		}

		SqlBuilderHelper.generateWhereCondition(methodBuilder, method, false);
		SqlSelectBuilder.generateDynamicPartOfQuery(method, methodBuilder, splittedSql, countQuery);
	}
1152298
public String rewrite() {
        if (sqlTokens.isEmpty()) {
            return originalSQL;
        }
        SQLBuilder result = new SQLBuilder(Collections.emptyList());
        int count = 0;
        for (SQLToken each : sqlTokens) {
            if (0 == count) {
                result.appendLiterals(originalSQL.substring(0, each.getStartIndex()));
            }
            if (each instanceof SchemaToken) {
                appendSchemaPlaceholder(originalSQL, result, (SchemaToken) each, count);
            }
            count++;
        }
        return result.toSQL(masterSlaveRule, metaData.getDataSource());
    }
808692
public static Predicate is(final String sql) {
        return new Predicate() {
            public String toSql() {
                return sql;
            }
            public void init(AbstractSqlCreator creator) {
            }
        };
    }
939268
@Override
  public MtasSpanQuery rewrite(IndexReader reader) throws IOException {
    MtasSpanQuery newBigQuery = bigQuery.rewrite(reader);
    MtasSpanQuery newSmallQuery = smallQuery.rewrite(reader);

    if (newBigQuery == null || newBigQuery instanceof MtasSpanMatchNoneQuery
        || newSmallQuery == null
        || newSmallQuery instanceof MtasSpanMatchNoneQuery) {
      return new MtasSpanMatchNoneQuery(field);
    }

    if (newSmallQuery.getMinimumWidth() != null
        && newBigQuery.getMaximumWidth() != null
        && newSmallQuery.getMinimumWidth() > (newBigQuery.getMaximumWidth()
            + leftBoundaryBigMaximum + rightBoundaryBigMaximum)) {
      return new MtasSpanMatchNoneQuery(field);
    }

    if (autoAdjustBigQuery) {
      if (newBigQuery instanceof MtasSpanRecurrenceQuery) {
        MtasSpanRecurrenceQuery recurrenceQuery = (MtasSpanRecurrenceQuery) newBigQuery;
        if (recurrenceQuery.getIgnoreQuery() == null
            && recurrenceQuery.getQuery() instanceof MtasSpanMatchAllQuery) {
          rightBoundaryBigMaximum += leftBoundaryBigMaximum
              + recurrenceQuery.getMaximumRecurrence();
          rightBoundaryBigMinimum += leftBoundaryBigMinimum
              + recurrenceQuery.getMinimumRecurrence();
          leftBoundaryBigMaximum = 0;
          leftBoundaryBigMinimum = 0;
          newBigQuery = new MtasSpanMatchAllQuery(field);
          // System.out.println("REPLACE WITH " + newBigQuery + " (["
          // + leftBoundaryMinimum + "," + leftBoundaryMaximum + "],["
          // + rightBoundaryMinimum + "," + rightBoundaryMaximum + "])");
          return new MtasSpanWithinQuery(newBigQuery, newSmallQuery,
              leftBoundaryBigMinimum, leftBoundaryBigMaximum,
              rightBoundaryBigMinimum, rightBoundaryBigMaximum,
              autoAdjustBigQuery).rewrite(reader);
        }
      } else if (newBigQuery instanceof MtasSpanMatchAllQuery) {
        if (leftBoundaryBigMaximum > 0) {
          rightBoundaryBigMaximum += leftBoundaryBigMaximum;
          rightBoundaryBigMinimum += leftBoundaryBigMinimum;
          leftBoundaryBigMaximum = 0;
          leftBoundaryBigMinimum = 0;
          // System.out.println("REPLACE WITH " + newBigQuery + " (["
          // + leftBoundaryMinimum + "," + leftBoundaryMaximum + "],["
          // + rightBoundaryMinimum + "," + rightBoundaryMaximum + "])");
          return new MtasSpanWithinQuery(newBigQuery, newSmallQuery,
              leftBoundaryBigMinimum, leftBoundaryBigMaximum,
              rightBoundaryBigMinimum, rightBoundaryBigMaximum,
              autoAdjustBigQuery).rewrite(reader);
        }
      } else if (newBigQuery instanceof MtasSpanSequenceQuery) {
        MtasSpanSequenceQuery sequenceQuery = (MtasSpanSequenceQuery) newBigQuery;
        if (sequenceQuery.getIgnoreQuery() == null) {
          List<MtasSpanSequenceItem> items = sequenceQuery.getItems();
          List<MtasSpanSequenceItem> newItems = new ArrayList<>();
          int newLeftBoundaryMinimum = 0;
          int newLeftBoundaryMaximum = 0;
          int newRightBoundaryMinimum = 0;
          int newRightBoundaryMaximum = 0;
          for (int i = 0; i < items.size(); i++) {
            // first item
            if (i == 0) {
              if (items.get(i).getQuery() instanceof MtasSpanMatchAllQuery) {
                newLeftBoundaryMaximum++;
                if (!items.get(i).isOptional()) {
                  newLeftBoundaryMinimum++;
                }
              } else if (items.get(i)
                  .getQuery() instanceof MtasSpanRecurrenceQuery) {
                MtasSpanRecurrenceQuery msrq = (MtasSpanRecurrenceQuery) items
                    .get(i).getQuery();
                if (msrq.getQuery() instanceof MtasSpanMatchAllQuery) {
                  newLeftBoundaryMaximum += msrq.getMaximumRecurrence();
                  if (!items.get(i).isOptional()) {
                    newLeftBoundaryMinimum += msrq.getMinimumRecurrence();
                  }
                } else {
                  newItems.add(items.get(i));
                }
              } else {
                newItems.add(items.get(i));
              }
              // last item
            } else if (i == (items.size() - 1)) {
              if (items.get(i).getQuery() instanceof MtasSpanMatchAllQuery) {
                newRightBoundaryMaximum++;
                if (!items.get(i).isOptional()) {
                  newRightBoundaryMinimum++;
                }
              } else if (items.get(i)
                  .getQuery() instanceof MtasSpanRecurrenceQuery) {
                MtasSpanRecurrenceQuery msrq = (MtasSpanRecurrenceQuery) items
                    .get(i).getQuery();
                if (msrq.getQuery() instanceof MtasSpanMatchAllQuery) {
                  newRightBoundaryMaximum += msrq.getMaximumRecurrence();
                  if (!items.get(i).isOptional()) {
                    newRightBoundaryMinimum += msrq.getMinimumRecurrence();
                  }
                } else {
                  newItems.add(items.get(i));
                }
              } else {
                newItems.add(items.get(i));
              }
              // other items
            } else {
              newItems.add(items.get(i));
            }
          }
          leftBoundaryBigMaximum += newLeftBoundaryMaximum;
          leftBoundaryBigMinimum += newLeftBoundaryMinimum;
          rightBoundaryBigMaximum += newRightBoundaryMaximum;
          rightBoundaryBigMinimum += newRightBoundaryMinimum;
          if (newItems.isEmpty()) {
            rightBoundaryBigMaximum = Math.max(0,
                rightBoundaryBigMaximum + leftBoundaryBigMaximum - 1);
            rightBoundaryBigMinimum = Math.max(0,
                rightBoundaryBigMinimum + leftBoundaryBigMinimum - 1);
            leftBoundaryBigMaximum = 0;
            leftBoundaryBigMinimum = 0;
            newItems.add(new MtasSpanSequenceItem(
                new MtasSpanMatchAllQuery(field), false));
          }
          if (!items.equals(newItems) || newLeftBoundaryMaximum > 0
              || newRightBoundaryMaximum > 0) {
            newBigQuery = (new MtasSpanSequenceQuery(newItems, null, null))
                .rewrite(reader);
            // System.out.println("REPLACE WITH " + newBigQuery + " (["
            // + leftBoundaryMinimum + "," + leftBoundaryMaximum + "],["
            // + rightBoundaryMinimum + "," + rightBoundaryMaximum + "])");
            return new MtasSpanWithinQuery(newBigQuery, newSmallQuery,
                leftBoundaryBigMinimum, leftBoundaryBigMaximum,
                rightBoundaryBigMinimum, rightBoundaryBigMaximum,
                autoAdjustBigQuery).rewrite(reader);
          }
        }
      }
    }

    if (!newBigQuery.equals(bigQuery) || !newSmallQuery.equals(smallQuery)) {
      return (new MtasSpanWithinQuery(newBigQuery, newSmallQuery,
          leftBoundaryBigMinimum, leftBoundaryBigMaximum,
          rightBoundaryBigMinimum, rightBoundaryBigMaximum, autoAdjustBigQuery))
              .rewrite(reader);
    } else if (newBigQuery.equals(newSmallQuery)) {
      return newBigQuery;
    } else {
      baseQuery = (SpanWithinQuery) baseQuery.rewrite(reader);
      return super.rewrite(reader);
    }
  }
968821
public Object querySingleResult(String sql, String[] args, int column) {
		return querySingleResult(sql, args, column, null);
	}
766234
function having() {
    var havings = this.grouped.having;
    if (!havings) {
      return '';
    }
    var sql = ['having'];
    for (var i = 0, l = havings.length; i < l; i++) {
      var str = '',
          s = havings[i];
      if (i !== 0) {
        str = s.bool + ' ';
      }
      if (s.type === 'havingBasic') {
        sql.push(str + this.formatter.columnize(s.column) + ' ' + this.formatter.operator(s.operator) + ' ' + this.formatter.parameter(s.value));
      } else {
        if (s.type === 'whereWrapped') {
          var val = this.whereWrapped(s);
          if (val) {
            sql.push(val);
          }
        } else {
          sql.push(str + this.formatter.unwrapRaw(s.value));
        }
      }
    }
    return sql.length > 1 ? sql.join(' ') : '';
  }
518303
protected function _renderHaving($sql)
    {
        if ($this->_parts[self::FROM] && $this->_parts[self::HAVING]) {
            $sql .= ' ' . self::SQL_HAVING . ' ' . implode(' ', $this->_parts[self::HAVING]);
        }

        return $sql;
    }
681523
public static String convertJQL2SQL(final SQLiteModelMethod method, final boolean replaceWithQuestion) {
		JQLChecker jqlChecker = JQLChecker.getInstance();
		// convert jql to sql
		String sql = jqlChecker.replace(method, method.jql, new JQLReplacerListenerImpl(method) {

			@Override
			public String onBindParameter(String bindParameterName, boolean inStatement) {
				if (replaceWithQuestion) {
					return "?";
				}
				return SqlAnalyzer.PARAM_PREFIX + bindParameterName + SqlAnalyzer.PARAM_SUFFIX;
			}

			@Override
			public String onColumnName(String columnName) {
				SQLProperty tempProperty = currentEntity.get(columnName);
				AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);

				return tempProperty.columnName;
			}

			@Override
			public String onColumnAlias(String alias) {
				SQLProperty tempProperty = currentEntity.get(alias);
				AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, alias);

				return tempProperty.columnName;
			}

		});
		return sql;
	}
20321
public QueryBuilder<T, ID> queryBuilder() throws SQLException {
		if (statementBuilder instanceof QueryBuilder) {
			return (QueryBuilder<T, ID>) statementBuilder;
		} else {
			throw new SQLException("Cannot cast " + statementBuilder.getType() + " to QueryBuilder");
		}
	}
888315
public Datatype.Builder setHasToBuilderMethod(boolean hasToBuilderMethod) {
    this.hasToBuilderMethod = hasToBuilderMethod;
    _unsetProperties.remove(Property.HAS_TO_BUILDER_METHOD);
    return (Datatype.Builder) this;
  }
499023
public static String toSingleColumnSql(String sql) {
		String tempSql = sql.trim();
		String regex = "(?i)^select(.*?)from";
		Matcher m = Pattern.compile(regex).matcher(tempSql);
		String columnAlias = SqlTemplate.SINGLE_COLUMN_ALIAS;
		if (m.find()) {
			columnAlias = m.group(1).trim().replaceAll("\\(\\s+", "(").replaceAll("\\s+\\)", ")").split("\\s+")[0]+ " AS " + columnAlias;
		}
		return tempSql.replaceFirst(regex, "select " + columnAlias + " from ");
	}