Generate SQL build.

@param method
the method
@param methodBuilder
the method builder
@param splittedSql
the splitted sql
@param countQuery
is true, the query manage the count query for paged result
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);
	}
487414
private void buildNewInstanceMethodForBuilder( MethodSpec.Builder newInstanceMethodBuilder ) {
        newInstanceMethodBuilder.addStatement( "return new $T(builderDeserializer.deserializeInline(reader, ctx, params, null, null, null, bufferedProperties).build(), bufferedProperties)",
                parameterizedName( Instance.class, beanInfo.getType() ) );
    }
281832
public static void generateSQL(final SQLiteModelMethod method, MethodSpec.Builder methodBuilder) {
		JQLChecker jqlChecker = JQLChecker.getInstance();

		methodBuilder.addCode("\n// generate sql\n");
		String sql = jqlChecker.replace(method, method.jql, new JQLReplacerListenerImpl(method) {
			@Override
			public String onColumnNameToUpdate(String columnName) {
				// only entity's columns
				return currentEntity.findPropertyByName(columnName).columnName;
			}

			@Override
			public String onColumnName(String columnName) {
				return currentSchema.findColumnNameByPropertyName(method, columnName);
			}

			@Override
			public String onBindParameter(String bindParameterName, boolean inStatement) {
				return "?";
			}

		});

		if (method.jql.dynamicReplace.containsKey(JQLDynamicStatementType.DYNAMIC_WHERE)) {
			methodBuilder.addStatement("String _sql=String.format($S, $L)",
					sql.replace(method.jql.dynamicReplace.get(JQLDynamicStatementType.DYNAMIC_WHERE), "%s"),
					"StringUtils.ifNotEmptyAppend(_sqlDynamicWhere,\" AND \")");
		} else {
			methodBuilder.addStatement("String _sql=$S", sql);
		}
	}
1053602
@Override
	public final ResultSet executeQuery() throws SQLException {
		Split split = prepare();
		try {
			return new SimonResultSet(stmt.executeQuery(), this, prefix, split.getStopwatch().getName());
		} finally {
			finish(split);
		}
	}
927159
private void loadSQLAnnotationStatmentOptions(ControlBeanContext context, Method method) {

        final JdbcControl.SQL methodSQL = (JdbcControl.SQL) context.getMethodPropertySet(method, JdbcControl.SQL.class);

        _batchUpdate = methodSQL.batchUpdate();
        _getGeneratedKeys = methodSQL.getGeneratedKeys();
        _genKeyColumnNames = methodSQL.generatedKeyColumnNames();
        _genKeyColumnIndexes = methodSQL.generatedKeyColumnIndexes();
        _scrollType = methodSQL.scrollableResultSet();
        _fetchDirection = methodSQL.fetchDirection();
        _fetchSize = methodSQL.fetchSize();
        _maxRows = methodSQL.maxRows();
        _maxArray = methodSQL.arrayMaxLength();

        _holdability = methodSQL.resultSetHoldabilityOverride();
    }
529144
public static void generateLog(final SQLiteModelMethod method, MethodSpec.Builder methodBuilder) {
		SQLiteDaoDefinition daoDefinition = method.getParent();

		// log is enabled
		if (daoDefinition.isLogEnabled()) {
			// generate log section - BEGIN
			methodBuilder.addComment("log section BEGIN");
			methodBuilder.beginControlFlow("if (_context.isLogEnabled())");

			methodBuilder.addCode("// log for insert -- BEGIN \n");

			JQLChecker checker = JQLChecker.getInstance();
			final One<Boolean> inWhere = new One<Boolean>(false);

			String sql = checker.replace(method, method.jql, new JQLReplacerListenerImpl(method) {

				@Override
				public String onBindParameter(String bindParameterName, boolean inStatement) {
					if (inWhere.value0) {
						return "?";
					}

					return null;
				}

				@Override
				public void onWhereStatementBegin(Where_stmtContext ctx) {
					super.onWhereStatementBegin(ctx);

					inWhere.value0 = true;
				}

				@Override
				public void onWhereStatementEnd(Where_stmtContext ctx) {
					super.onWhereStatementEnd(ctx);

					inWhere.value0 = false;
				}
			});

			if (method.jql.containsSelectOperation) {
				// log
				// manage log
				methodBuilder.addCode("\n");
				methodBuilder.addStatement("$T.info($S)", Logger.class, sql);
			} else {
				sql = checker.replaceVariableStatements(method, sql, new JQLReplaceVariableStatementListenerImpl() {

					@Override
					public String onColumnNameSet(String statement) {
						return "%s";
					}

					@Override
					public String onColumnValueSet(String statement) {
						return "%s";
					}
				});

				methodBuilder.addStatement("$T _columnNameBuffer=new $T()", StringBuffer.class, StringBuffer.class);
				methodBuilder.addStatement("$T _columnValueBuffer=new $T()", StringBuffer.class, StringBuffer.class);
				methodBuilder.addStatement("String _columnSeparator=$S", "");

				SqlBuilderHelper.forEachColumnInContentValue(methodBuilder, method, "_contentValues.keys()", false, new OnColumnListener() {

					@Override
					public void onColumnCheck(MethodSpec.Builder methodBuilder, String columNameVariable) {
						methodBuilder.addStatement("_columnNameBuffer.append(_columnSeparator+$L)", columNameVariable);
						methodBuilder.addStatement("_columnValueBuffer.append(_columnSeparator+$S+$L)", ":", columNameVariable);
						methodBuilder.addStatement("_columnSeparator=$S", ", ");

					}
				});

				methodBuilder.addStatement("$T.info($S, _columnNameBuffer.toString(), _columnValueBuffer.toString())", Logger.class, sql);
			}
			generateLogForContentValues(method, methodBuilder);

			methodBuilder.addCode("// log for insert -- END \n\n");
			SqlBuilderHelper.generateLogForWhereParameters(method, methodBuilder);

			// generate log section - END
			methodBuilder.endControlFlow();
			methodBuilder.addComment("log section END");
		}
	}
510160
@Override
	public void generateLiveData(TypeSpec.Builder classBuilder, SQLiteModelMethod method) {
		SQLiteDaoDefinition daoDefinition = method.getParent();
		Set<JQLProjection> fieldList = JQLChecker.getInstance().extractProjections(method, method.jql.value, method.getEntity());

		// generate method code
		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.getName().replaceAll(LIVE_DATA_PREFIX, "")).addAnnotation(Override.class).addModifiers(Modifier.PUBLIC);

		methodBuilder.addJavadoc("<h2>Live data</h2>\n");
		methodBuilder.addJavadoc("<p>This method open a connection internally.</p>\n\n");

		generateCommonPart(method, classBuilder, methodBuilder, fieldList, GenerationType.NO_CONTENT, method.liveDataReturnClass, true, false);

		boolean pagedLiveData = method.isPagedLiveData();

		if (pagedLiveData) {
			SelectType.PAGED_RESULT.generate(classBuilder, method);

			String pageResultName = SelectPaginatedResultHelper.getCurrentPagedResultClass();
			SelectPaginatedResultHelper.createPagedResult(method, pageResultName, methodBuilder);
		}

		ClassName dataSourceClazz = BindDataSourceBuilder.generateDataSourceName(daoDefinition.getParent());
		ClassName daoFactoryClazz = TypeUtility.className(BindDaoFactoryBuilder.generateDaoFactoryName(daoDefinition.getParent()));
		ClassName batchClazz = TypeUtility.mergeTypeNameWithSuffix(dataSourceClazz, ".Batch");

		List<Pair<String, TypeName>> methodParameters = method.getParameters();
		StringBuilder buffer = new StringBuilder();
		String separator = "";

		for (Pair<String, TypeName> item : methodParameters) {
			buffer.append(separator + item.value0);
			separator = ", ";
		}

		ClassName handlerClass = KriptonLiveDataManager.getInstance().getLiveDataHandlerClazz();
		if (pagedLiveData) {
			handlerClass = KriptonLiveDataManager.getInstance().getPagedLiveDataHandlerClazz();

			TypeSpec batchBuilder = TypeSpec.anonymousClassBuilder("").addSuperinterface(ParameterizedTypeName.get(batchClazz, method.getReturnClass()))
					.addMethod(
							MethodSpec.methodBuilder("onExecute").addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).addParameter(ParameterSpec.builder(daoFactoryClazz, "daoFactory").build())
									.returns(method.getReturnClass()).addStatement("return paginatedResult.execute(daoFactory)").build())
					.build();

			// return
			TypeSpec.Builder liveDataBuilderBuilder = TypeSpec.anonymousClassBuilder("paginatedResult")
					.addSuperinterface(ParameterizedTypeName.get(handlerClass, method.getReturnClass())).addMethod(MethodSpec.methodBuilder("compute").addAnnotation(Override.class)
							.addModifiers(Modifier.PROTECTED).returns(method.getReturnClass()).addStatement("return $T.getInstance().executeBatch($L)", dataSourceClazz, batchBuilder).build());
			TypeSpec liveDataBuilder = liveDataBuilderBuilder.build();

			methodBuilder.addStatement("final $T builder=$L", ParameterizedTypeName.get(handlerClass, method.getReturnClass()), liveDataBuilder);
		} else {
			TypeSpec batchBuilder = TypeSpec.anonymousClassBuilder("").addSuperinterface(ParameterizedTypeName.get(batchClazz, method.getReturnClass()))
					.addMethod(MethodSpec.methodBuilder("onExecute").addAnnotation(Override.class).addModifiers(Modifier.PUBLIC)
							.addParameter(ParameterSpec.builder(daoFactoryClazz, "daoFactory").build()).returns(method.getReturnClass())
							.addStatement("return daoFactory.get$L().$L($L)", daoDefinition.getName(), method.getName() + LIVE_DATA_PREFIX, buffer.toString()).build())
					.build();

			TypeSpec.Builder liveDataBuilderBuilder = TypeSpec.anonymousClassBuilder("").addSuperinterface(ParameterizedTypeName.get(handlerClass, method.getReturnClass()))
					.addMethod(MethodSpec.methodBuilder("compute").addAnnotation(Override.class).addModifiers(Modifier.PROTECTED).returns(method.getReturnClass())
							.addStatement("return $T.getInstance().executeBatch($L)", dataSourceClazz, batchBuilder).build());
			TypeSpec liveDataBuilder = liveDataBuilderBuilder.build();

			methodBuilder.addStatement("final $T builder=$L", ParameterizedTypeName.get(handlerClass, method.getReturnClass()), liveDataBuilder);
		}

		methodBuilder.addStatement("registryLiveData(builder)");
		methodBuilder.addStatement("return builder.getLiveData()");

		classBuilder.addMethod(methodBuilder.build());
	}
663815
private void checkSQL(MethodDeclaration method, AnnotationProcessorEnvironment env) {

        final JdbcControl.SQL methodSQL = method.getAnnotation(JdbcControl.SQL.class);
        if (methodSQL == null) {
            return;
        }

        //
        // check for empty SQL statement member
        //
        if (methodSQL.statement() == null || methodSQL.statement().length() == 0) {
            env.getMessager().printError(method.getPosition(),
                                         getResourceString("jdbccontrol.empty.statement", method.getSimpleName()));
            return;
        }

        //
        // Make sure maxrows is not set to some negative number other than -1
        //
        int maxRows = methodSQL.maxRows();
        if (maxRows < JdbcControl.MAXROWS_ALL) {
            env.getMessager().printError(method.getPosition(),
                                         getResourceString("jdbccontrol.bad.maxrows", method.getSimpleName(),maxRows));
            return;
        }

        //
        //
        // parse the SQL
        //
        //
        SqlParser _p = new SqlParser();
        SqlStatement _statement;
        try {
            _statement = _p.parse(methodSQL.statement());
        } catch (ControlException ce) {
            env.getMessager().printError(method.getPosition(),  getResourceString("jdbccontrol.bad.parse",
                                                                                  method.getSimpleName(),
                                                                                  ce.toString()));
            return;
        }

        //
        // Check that the any statement element params (delimited by '{' and '}' can be
        // matched to method parameter names. NOTE: This check is only valid on non-compiled files,
        // once compiled to a class file method parameter names are replaced with 'arg0', 'arg1', etc.
        // and cannot be used for this check.
        //
        try {
            ParameterChecker.checkReflectionParameters(_statement, method);
        } catch (ControlException e) {
            env.getMessager().printError(method.getPosition(), e.getMessage());
            return;
        }

        //
        // check for case of generatedKeyColumns being set, when getGeneratedKeys is not set to true
        //
        final boolean getGeneratedKeys = methodSQL.getGeneratedKeys();
        final String[] generatedKeyColumnNames = methodSQL.generatedKeyColumnNames();
        final int[] generatedKeyIndexes = methodSQL.generatedKeyColumnIndexes();
        if (!getGeneratedKeys && (generatedKeyColumnNames.length != 0 || generatedKeyIndexes.length != 0)) {
            env.getMessager().printError(method.getPosition(),
                                         getResourceString("jdbccontrol.genkeys", method.getSimpleName()));
            return;
        }

        //
        // check that both generatedKeyColumnNames and generatedKeyColumnIndexes are not set
        //
        if (generatedKeyColumnNames.length > 0 && generatedKeyIndexes.length > 0) {
            env.getMessager().printError(method.getPosition(),
                                         getResourceString("jdbccontrol.genkeycolumns", method.getSimpleName()));

            return;
        }

        //
        // batch update methods must return int[]
        //
        final boolean batchUpdate = methodSQL.batchUpdate();
        final TypeMirror returnType = method.getReturnType();
        if (batchUpdate) {
            if (returnType instanceof ArrayType) {
                final TypeMirror aType = ((ArrayType) returnType).getComponentType();
                if (aType instanceof PrimitiveType == false
                        || ((PrimitiveType) aType).getKind() != PrimitiveType.Kind.INT) {
                    env.getMessager().printError(method.getPosition(),
                                                 getResourceString("jdbccontrol.batchupdate", method.getSimpleName()));
                    return;
                }
            } else if (returnType instanceof VoidType == false) {
                env.getMessager().printError(method.getPosition(),
                                             getResourceString("jdbccontrol.batchupdate", method.getSimpleName()));
                return;
            }

        }

        //
        // iterator type check match
        //
        if (returnType instanceof InterfaceType) {
            String iName = ((InterfaceType) returnType).getDeclaration().getQualifiedName();
            if ("java.util.Iterator".equals(iName)) {
                String iteratorClassName = null;
                try {
                    // this should always except
                    methodSQL.iteratorElementType();
                } catch (MirroredTypeException mte) {
                    iteratorClassName = mte.getQualifiedName();
                }

                if ("org.apache.beehive.controls.system.jdbc.JdbcControl.UndefinedIteratorType".equals(iteratorClassName)) {
                    env.getMessager().printError(method.getPosition(),
                                                 getResourceString("jdbccontrol.iterator.returntype",
                                                                   method.getSimpleName()));
                    return;
                }
            }
        }

        //
        // scrollable result set check
        //
        final JdbcControl.ScrollType scrollable = methodSQL.scrollableResultSet();
        switch (scrollable) {
            case SCROLL_INSENSITIVE:
            case SCROLL_SENSITIVE:
            case SCROLL_INSENSITIVE_UPDATABLE:
            case SCROLL_SENSITIVE_UPDATABLE:
            case FORWARD_ONLY_UPDATABLE:
                String typeName = null;
                if (returnType instanceof DeclaredType) {
                    typeName = ((DeclaredType) returnType).getDeclaration().getQualifiedName();
                }

                if (typeName == null || !"java.sql.ResultSet".equals(typeName)) {
                    env.getMessager().printError(method.getPosition(),
                                                 getResourceString("jdbccontrol.scrollresultset",
                                                                   method.getSimpleName()));
                    return;
                }
            case FORWARD_ONLY:
            default:
                break;
        }

        return;
    }
866473
private function addIntResultMethod(QueryBuilderResult $query, $methodName)
    {
        $intResultMethod = function () use ($query) {
            $sth = $this->pdo->prepare($query->getSql());
            $sth->execute(func_get_args());
            return $sth->rowCount();
        };

        $this->methods[$methodName] = \Closure::bind($intResultMethod, $this, get_class());
    }
643993
@Override
    public SqlQueryResult build(String query) throws IOException, ParserNotFoundException {
        Operation result = (Operation) super.parse(query);

        // sql
        StringBuffer sql = new StringBuffer(result.getOperate());
        sql.delete(sql.length() - 2, sql.length());
        sql.delete(0, 2);

        return new SqlQueryResult(query, sql.toString(), (List<Object>) result.getValue());
    }
323590
@Override
    public <E> DynamicType.Builder<E> processMethod(final DynamicType.Builder<E> builder, final Method method, final Annotation annotation)
    {
        String methodName = method.getName();
        if (ReflectionUtility.isGetMethod(method))
            return createInterceptor(builder, method);
        else if (ReflectionUtility.isSetMethod(method))
            return createInterceptor(builder, method);
        else if (methodName.startsWith("addAll"))
            return createInterceptor(builder, method);
        else if (methodName.startsWith("add"))
            return createInterceptor(builder, method);
        else
            throw new WindupException("Only get*, set*, add*, and addAll* method names are supported for @"
                        + SetInProperties.class.getSimpleName() + ", found at: " + method.getName());
    }
156527
private String extractSQLForJavaDoc(final SQLiteModelMethod method) {
		final One<Boolean> usedInWhere = new One<>(false);
		String sqlForJavaDoc = JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) {

			@Override
			public String onColumnNameToUpdate(String columnName) {
				return currentEntity.findPropertyByName(columnName).columnName;
			}

			@Override
			public String onColumnName(String columnName) {
				return currentEntity.findPropertyByName(columnName).columnName;
			}

			@Override
			public String onBindParameter(String bindParameterName, boolean inStatement) {
				if (!usedInWhere.value0) {
					if (bindParameterName.contains(".")) {
						String[] a = bindParameterName.split("\\.");

						if (a.length == 2) {
							bindParameterName = a[1];
						}
					}

					return ":" + bindParameterName;
				} else {
					return null;
				}
			}

			@Override
			public void onWhereStatementBegin(Where_stmtContext ctx) {
				usedInWhere.value0 = true;
			}

			@Override
			public void onWhereStatementEnd(Where_stmtContext ctx) {
				usedInWhere.value0 = false;
			};

		});
		return sqlForJavaDoc;
	}
559007
public static void generate(TypeSpec.Builder classBuilder, SQLiteModelMethod method) {
		InsertType insertResultType = detectInsertType(method);

		// if true, field must be associate to ben attributes
		TypeName returnType = method.getReturnClass();

		AssertKripton.failWithInvalidMethodSignException(insertResultType == null, method);

		// generate method code
		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.getName()).addAnnotation(Override.class)
				.addModifiers(Modifier.PUBLIC);

		ParameterSpec parameterSpec;
		for (Pair<String, TypeName> item : method.getParameters()) {
			parameterSpec = ParameterSpec.builder(item.value1, item.value0).build();
			methodBuilder.addParameter(parameterSpec);
		}
		methodBuilder.returns(returnType);

		// fail if we use jql to INSERT_BEAN with operation of INSERT-FOR-SELECT
		// AssertKripton.failWithInvalidMethodSignException(insertResultType ==
		// InsertType.INSERT_BEAN && method.jql.containsSelectOperation, method,
		// "INSERT-FROM-SELECT SQL can not be used with method sign");

		// generate inner code
		methodBuilder.addComment("Specialized Insert - $L - BEGIN", insertResultType.getClass().getSimpleName());
		insertResultType.generate(classBuilder, methodBuilder, method, returnType);
		methodBuilder.addComment("Specialized Insert - $L - END", insertResultType.getClass().getSimpleName());

		MethodSpec methodSpec = methodBuilder.build();
		classBuilder.addMethod(methodSpec);

		if (method.contentProviderEntryPathEnabled) {
			// we need to generate insert for content provider to
			generateInsertForContentProvider(classBuilder, method, insertResultType);
		}

	}
907645
static QueryMeta buildCountSql(ActiveRecord activeRecord) {
        QueryMeta     queryMeta = new QueryMeta();
        StringBuilder sqlBuf    = new StringBuilder("SELECT COUNT(*) FROM " + activeRecord.getTableName());
        int[]         pos       = {1};
        List<Object>  list      = parseWhere(activeRecord, pos, sqlBuf);

        List<Object> temp = andWhere(activeRecord, pos, sqlBuf);
        if (null != temp) {
            list.addAll(temp);
        }

        String   sql  = sqlFilter(sqlBuf.toString());
        Object[] args = list.toArray();
        queryMeta.setSql(sql);
        queryMeta.setParams(args);
        return queryMeta;
    }
1138203
@Override
	public int countByCommerceShippingMethodId(long commerceShippingMethodId) {
		FinderPath finderPath = FINDER_PATH_COUNT_BY_COMMERCESHIPPINGMETHODID;

		Object[] finderArgs = new Object[] { commerceShippingMethodId };

		Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);

		if (count == null) {
			StringBundler query = new StringBundler(2);

			query.append(_SQL_COUNT_COMMERCESHIPPINGFIXEDOPTION_WHERE);

			query.append(_FINDER_COLUMN_COMMERCESHIPPINGMETHODID_COMMERCESHIPPINGMETHODID_2);

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(commerceShippingMethodId);

				count = (Long)q.uniqueResult();

				finderCache.putResult(finderPath, finderArgs, count);
			}
			catch (Exception e) {
				finderCache.removeResult(finderPath, finderArgs);

				throw processException(e);
			}
			finally {
				closeSession(session);
			}
		}

		return count.intValue();
	}
800178
private MethodDeclaration generateToBuilderMethod(String builderClassName, String builderImplClassName, EclipseNode type, TypeParameter[] typeParams, ASTNode source) {
		int pS = source.sourceStart, pE = source.sourceEnd;
		long p = (long) pS << 32 | pE;
		
		MethodDeclaration out = new MethodDeclaration(((CompilationUnitDeclaration) type.top().get()).compilationResult);
		out.selector = TO_BUILDER_METHOD_NAME;
		out.modifiers = ClassFileConstants.AccPublic;
		out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
		
		TypeReference[] wildcards = new TypeReference[] {new Wildcard(Wildcard.UNBOUND), new Wildcard(Wildcard.UNBOUND) };
		out.returnType = new ParameterizedSingleTypeReference(builderClassName.toCharArray(), mergeToTypeReferences(typeParams, wildcards), 0, p);
		
		AllocationExpression newClass = new AllocationExpression();
		newClass.type = namePlusTypeParamsToTypeReference(builderImplClassName.toCharArray(), typeParams, p);
		MessageSend invokeFillMethod = new MessageSend();
		invokeFillMethod.receiver = newClass;
		invokeFillMethod.selector = FILL_VALUES_METHOD_NAME;
		invokeFillMethod.arguments = new Expression[] {new ThisReference(0, 0)};
		out.statements = new Statement[] {new ReturnStatement(invokeFillMethod, pS, pE)};
		
		out.traverse(new SetGeneratedByVisitor(source), ((TypeDeclaration) type.get()).scope);
		return out;
	}
463807
private function _sqlFromMethod($method)
    {
        if(!preg_match('/^(findBy|oneBy)(.*?)$/', $method, $m))
            throw new \BadMethodCallException("Unable to parse $method");

        // split on AND or OR and case boundries
        $sql = strtolower(preg_replace('/(?<=[a-z0-9\b])(Or|And)(?=[A-Z])/',' $1 ',$m[2]));

        // add parameter binds
        return preg_replace_callback('/\b([\w-]+)\b/', function($m) {
            return ($m[0] != 'or' && $m[0] != 'and') ? "`{$m[0]}`=?" : $m[0];
        }, $sql);
    }