Compile and return SQLite VM for SQL statement. Only available
in SQLite 2.8.0 and above, otherwise a no-op.

@param sql SQL statement to be compiled
@return a Vm object
482605
public Vm compile( String sql ) throws jsqlite.Exception {
        synchronized (this) {
            Vm vm = new Vm();
            vm_compile(sql, vm);
            return vm;
        }
    }
826131
def sql(self):
        
        clone = self.query.clone()
        sql, params = clone.get_compiler(using=self.db).as_sql()
        return sql % params
478775
def compile_create(self, blueprint, command, connection):
        
        columns = ", ".join(self._get_columns(blueprint))

        sql = "CREATE TABLE %s (%s)" % (self.wrap_table(blueprint), columns)

        sql = self._compile_create_encoding(sql, connection, blueprint)

        if blueprint.engine:
            sql += " ENGINE = %s" % blueprint.engine

        return sql
1251551
private Result executeCompiledStatement(Result cmd) {

        Statement cs = cmd.getStatement();

        if (!cs.isValid()) {
            long csid = cmd.getStatementID();

            cs = database.compiledStatementManager.getStatement(this, csid);

            if (cs == null) {

                // invalid sql has been removed already
                return Result.newErrorResult(Error.error(ErrorCode.X_07502));
            }
        }

        Object[] pvals = cmd.getParameterData();

        return executeCompiledStatement(cs, pvals);
    }
1185511
public Set<String> getTable(String sql) {
		Set<String> tableSet = new HashSet<String>();
		
		try {
			Statement statement = parserManager.parse(new StringReader(sql));
			
			if (statement instanceof Select) {
				tableSet = new SelectParser().parse((Select)statement);
			} else if (statement instanceof Delete) {
				tableSet = new DeleteParser().parse((Delete)statement);
			} else if (statement instanceof Insert) {
				tableSet = new InsertParser().parse((Insert)statement);
			} else if (statement instanceof Update) {
				tableSet = new UpdateParser().parse((Update)statement);
			} else if (statement instanceof CreateTable) {
				tableSet = new CreateTableParser().parse((CreateTable)statement);
			} else if (statement instanceof CreateView) {
				tableSet = new CreateViewParser().parse((CreateView)statement);
			} else if (statement instanceof Alter) {
				tableSet = new AlterParser().parse((Alter)statement);
			} else if (statement instanceof Drop) {
				tableSet = new DropParser().parse((Drop)statement);
			}
		} catch (Exception e) {
			logger.debug(String.format("SQL Parse Exception: exception=%s, sql=%s", e.getMessage(), sql));
		} catch (Error e) {
			logger.debug(String.format("SQL Parse Exception: exception=%s, sql=%s", e.getMessage(), sql));
		}
		
		Set<String> resultSet = new HashSet<String>();
		for (String tableName : tableSet) {
			if (StringUtils.isNotEmpty(tableName)) {
				if (tableName.startsWith("`")) {
					tableName = tableName.substring(1);
				}
				if (tableName.endsWith("`")) {
					tableName = tableName.substring(0, tableName.length() - 1);
				}
				resultSet.add(tableName.toUpperCase());
			}
		}
		
		return resultSet;
	}
721847
public static SqlInfo getSqlInfo(String nameSpace, String zealotId, Object paramObj) {
        if (StringHelper.isBlank(nameSpace) || StringHelper.isBlank(zealotId)) {
            throw new ValidFailException("请输入有效的nameSpace或者zealotId的值!");
        }

        // 获取nameSpace文档中的指定sql的zealotId的节点对应的Node节点，如果是debug模式，则实时获取；否则从缓存中获取.
        Node zealotNode = NormalConfig.getInstance().isDebug() ? XmlNodeHelper.getNodeBySpaceAndId(nameSpace, zealotId)
                : AbstractZealotConfig.getZealots().get(StringHelper.concat(nameSpace, ZealotConst.SP_AT, zealotId));
        if (zealotNode == null) {
            throw new NodeNotFoundException("未找到nameSpace为:" + nameSpace + ",zealotId为:" + zealotId + "的节点!");
        }

        // 生成新的SqlInfo信息并打印出来.
        SqlInfo sqlInfo = buildNewSqlInfo(nameSpace, zealotNode, paramObj);
        SqlInfoPrinter.newInstance().printZealotSqlInfo(sqlInfo, true, nameSpace, zealotId);
        return sqlInfo;
    }
180530
public Sql[] generateSql(CreateSynonymStatement statement, Database database, SqlGeneratorChain chain) {
		StringBuilder sql = new StringBuilder("CREATE ");
		if (statement.isReplace() != null && statement.isReplace()) {
			sql.append("OR REPLACE ");
		}

		if (statement.isPublic() != null && statement.isPublic()) {
			sql.append("PUBLIC ");
		}

		sql.append("SYNONYM ");

		if (statement.getSynonymSchemaName() != null) {
			sql.append(statement.getSynonymSchemaName()).append(".");
		}

		sql.append(statement.getSynonymName());
		sql.append(" FOR ");

		if (statement.getObjectSchemaName() != null) {
			sql.append(statement.getObjectSchemaName()).append(".");
		}

		sql.append(statement.getObjectName());

		return new Sql[] { new UnparsedSql(sql.toString()) };
	}
1330180
public Cursor rawQuery(String sql, String[] makeArgListQueryString) throws SQLException {
    Log.v("SQLiteDatabase rawQuery: " + Thread.currentThread().getId() + " \"" + Thread.currentThread().getName() + "\" " + sql);
    long timeNow = System.currentTimeMillis();
    long delta = 0;
    do {
      try {
        Cursor cursor = sqliteDatabase.rawQuery(sql, makeArgListQueryString);
        Log.v("SQLiteDatabase rawQuery OK: " + Thread.currentThread().getId() + " \"" + Thread.currentThread().getName() + "\" " + sql);
        return cursor;
      } catch (SQLiteException e) {
        if ( isLockedException(e) ) {
          delta = System.currentTimeMillis() - timeNow;
        } else {
          throw SQLDroidConnection.chainException(e);
        }
      }
    } while (delta < timeout);
    throw new SQLException ("Timeout Expired");
  }
326157
public String subQuery(String sql) {
    if (options.maxQuerySizeToLog > 0 && sql.length() > options.maxQuerySizeToLog - 3) {
      return sql.substring(0, options.maxQuerySizeToLog - 3) + "...";
    }
    return sql;
  }
1186059
WrappedStatement compile(String sql) throws SQLException {
    WrappedStatement ws;
    if (! isEnabled(Option.REUSE_STATEMENTS)) {
      ws = new WrappedStatement(connection.prepareStatement(sql), false);
    }
    else {
      if (pool == null) {
        pool = new IdentityHashMap<>();
      }
      String sqlI = sql.intern();
      ws = pool.get(sqlI);
      if (ws == null) {
        ws =  new WrappedStatement(connection.prepareStatement(sql), true);
        pool.put(sqlI, ws);
      }
    }
    return ws;
  }
436714
public TableResult get_table( String sql, int maxrows, String args[] ) throws jsqlite.Exception {
        TableResult ret = new TableResult(maxrows);
        if (!is3()) {
            try {
                exec(sql, ret, args);
            } catch (jsqlite.Exception e) {
                if (maxrows <= 0 || !ret.atmaxrows) {
                    throw e;
                }
            }
        } else {
            synchronized (this) {
                /* only one statement !!! */
                Vm vm = compile(sql, args);
                set_last_error(vm.error_code);
                if (ret.maxrows > 0) {
                    while( ret.nrows < ret.maxrows && vm.step(ret) ) {
                        set_last_error(vm.error_code);
                    }
                } else {
                    while( vm.step(ret) ) {
                        set_last_error(vm.error_code);
                    }
                }
                vm.finalize();
            }
        }
        return ret;
    }
923871
public static ParsedSql parseSqlStatement(final String sql) {
        Assert.notNull(sql, "SQL must not be null");

        Set<String> namedParameters = new HashSet<>();
        String sqlToUse = sql;
        List<ParameterHolder> parameterList = new ArrayList<>();

        char[] statement = sql.toCharArray();
        int namedParameterCount = 0;
        int unnamedParameterCount = 0;
        int totalParameterCount = 0;

        int escapes = 0;
        int i = 0;
        while (i < statement.length) {
            int skipToPosition;
            while (i < statement.length) {
                skipToPosition = skipCommentsAndQuotes(statement, i);
                if (i == skipToPosition) {
                    break;
                } else {
                    i = skipToPosition;
                }
            }
            if (i >= statement.length) {
                break;
            }
            char c = statement[i];
            if (c == ':' || c == '&') {
                int j = i + 1;
                if (j < statement.length && statement[j] == ':' && c == ':') {
                    // Postgres-style "::" casting operator should be skipped
                    i = i + 2;
                    continue;
                }
                String parameter;
                if (j < statement.length && c == ':' && statement[j] == '{') {
                    // :{x} style parameter
                    while (j < statement.length && !('}' == statement[j])) {
                        j++;
                        if (':' == statement[j] || '{' == statement[j]) {
                            throw new CommonRuntimeException("Parameter name contains invalid character '" +
                                    statement[j] + "' at position " + i + " in statement: " + sql);
                        }
                    }
                    if (j >= statement.length) {
                        throw new CommonRuntimeException(
                                "Non-terminated named parameter declaration at position " + i + " in statement: " + sql);
                    }
                    if (j - i > 3) {
                        parameter = sql.substring(i + 2, j);
                        namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter);
                        totalParameterCount = addNamedParameter(parameterList, totalParameterCount, escapes, i, j + 1, parameter);
                    }
                    j++;
                } else {
                    while (j < statement.length && !isParameterSeparator(statement[j])) {
                        j++;
                    }
                    if (j - i > 1) {
                        parameter = sql.substring(i + 1, j);
                        namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter);
                        totalParameterCount = addNamedParameter(parameterList, totalParameterCount, escapes, i, j, parameter);
                    }
                }
                i = j - 1;
            } else {
                if (c == '\\') {
                    int j = i + 1;
                    if (j < statement.length && statement[j] == ':') {
                        // escaped ":" should be skipped
                        sqlToUse = sqlToUse.substring(0, i - escapes) + sqlToUse.substring(i - escapes + 1);
                        escapes++;
                        i = i + 2;
                        continue;
                    }
                }
                if (c == '?') {
                    int j = i + 1;
                    if (j < statement.length && (statement[j] == '?' || statement[j] == '|' || statement[j] == '&')) {
                        // Postgres-style "??", "?|", "?&" operator should be skipped
                        i = i + 2;
                        continue;
                    }
                    unnamedParameterCount++;
                    totalParameterCount++;
                }
            }
            i++;
        }

        ParsedSql parsedSql = new ParsedSql(sqlToUse);
        parsedSql.setParameterList(parameterList);
        parsedSql.setNamedParameterCount(namedParameterCount);
        parsedSql.setUnnamedParameterCount(unnamedParameterCount);
        parsedSql.setTotalParameterCount(totalParameterCount);
        return parsedSql;
    }
561745
protected String generateCreateIndexSql(final CreateSpatialIndexStatement statement,
         final Database database) {
      final StringBuilder sql = new StringBuilder();
      sql.append("CREATE INDEX ");
      final String schemaName = statement.getTableSchemaName();
      final String catalogName = statement.getTableCatalogName();
      final String indexName = statement.getIndexName();
      sql.append(database.escapeIndexName(catalogName, schemaName, indexName));
      sql.append(" ON ");
      final String tableName = statement.getTableName();
      sql.append(database.escapeTableName(catalogName, schemaName, tableName)).append(" (");
      final Iterator<String> iterator = Arrays.asList(statement.getColumns()).iterator();
      final String column = iterator.next();
      sql.append(database.escapeColumnName(catalogName, statement.getTableSchemaName(), tableName,
            column));
      sql.append(") INDEXTYPE IS mdsys.spatial_index");

      // Generate and add the optional parameters.
      final Collection<String> parameters = getParameters(statement);
      if (parameters != null && !parameters.isEmpty()) {
         sql.append(" PARAMETERS ('");
         sql.append(StringUtils.join(parameters, " "));
         sql.append("')");
      }
      return sql.toString();
   }
838175
@Override
    public SqlInfo buildSqlInfo(BuildSource source) {
        Object paramObj = source.getParamObj();
        SqlInfo sqlInfo = source.getSqlInfo();
        Node node = source.getNode();

        // 循环判断所有`when`的值，直到能找到第n个when的时候，如果都为false，则跳出循环走else的逻辑
        // 循环过程中，如果判断到第x个when解析后的值为true时，则解析拼接这第x个then的值到Sql中，并直接返回.
        int i = 0;
        while (true) {
            // 每次循环加1，如果是第一个，则，when/then等添加的后缀为空字符串.
            i++;
            String x = i == 1 ? "" : String.valueOf(i);

            // 获取第i个when属性的文本值，如果其文本内容为空则不再拼接，进入else的分支条件来拼接Sql片段信息.
            String whenText = XmlNodeHelper.getNodeAttrText(node, ZealotConst.ATTR_WHEN + x);
            if (StringHelper.isBlank(whenText)) {
                log.info("case标签中第" + i + "个when属性不存在或者内容为空，进入else的分支条件.");
                break;
            }

            // 如果when属性的解析值为true,则拼接其对应的`then`块的SQL片段.then块的值为解析其字符串模板的值.
            if (ParseHelper.isTrue(whenText, paramObj)) {
                String thenText = XmlNodeHelper.getNodeAttrText(node, ZealotConst.ATTR_THEN + x);
                if (StringHelper.isNotBlank(thenText)) {
                    sqlInfo.getJoin().append(ParseHelper.parseTemplate(thenText, paramObj));
                }
                return sqlInfo;
            }
        }

        // 如果没进入前面任何一个when-then的分支块，则进入else的分支，如果else为空，则直接返回原SqlInfo.
        String elseText = XmlNodeHelper.getNodeAttrText(node, ZealotConst.ATTR_ELSE);
        if (StringHelper.isBlank(elseText)) {
            log.info("case标签中else属性不存在或者内容为空，不拼接任何SQL片段.");
            return sqlInfo;
        }

        sqlInfo.getJoin().append(ParseHelper.parseTemplate(elseText, paramObj));
        return sqlInfo;
    }
258191
protected CallableStatement getCallableStatement(final SqlContext sqlContext) throws SQLException {
		CallableStatement stmt = ((LocalTransactionManager) transactionManager).getCallableStatement(sqlContext);
		// プロパティ設定
		applyProperties(stmt);
		return stmt;
	}
1002695
public static SQLException chainException(android.database.SQLException sqlException) {
        if ( sqlThrowable < 0 || sqlThrowable >= 9 ) {
            try {
                sqlThrowable = 9;
                //return new SQLException (sqlException);
                // creating by reflection is significantly slower, but since Exceptions should be unusual
                // this should not be a performance issue.
                final Constructor<?> c = SQLException.class.getDeclaredConstructor(new Class[] {Throwable.class});
                return (SQLException)c.newInstance(new Object[]{sqlException});
            } catch ( Exception e) {
                sqlThrowable = 1;
            }
        }
        // if the code above worked correctly, then the exception will have been returned.  Otherwise, we need
        // to go through this clause and create a SQLDroidSQLException
        try {
            // avoid a direct reference to the sqldroidSQLException so that app > API level 9 do not need that class.
            final Constructor<?> c = SQLDroidConnection.class.getClassLoader().loadClass("org.sqldroid.SQLDroidSQLException").getDeclaredConstructor(new Class[] {android.database.SQLException.class});
            // SQLDroidSQLException is an instance of (direct subclass of) SQLException, so the cast below is correct although
            // the instance created will always be a SQLDroidSQLException
            return (SQLException)c.newInstance(new Object[]{sqlException});
        } catch (Exception e) {
            return new SQLException ("Unable to Chain SQLException " + sqlException.getMessage());
        }
    }
1068192
public static SQLParser newInstance(final DatabaseType databaseType, final String sql) {
        for (ShardingParseEngine each : NewInstanceServiceLoader.newServiceInstances(ShardingParseEngine.class)) {
            if (DatabaseType.valueOf(each.getDatabaseType()) == databaseType) {
                return each.createSQLParser(sql);
            }
        }
        throw new UnsupportedOperationException(String.format("Cannot support database type '%s'", databaseType));
    }