Get a string containing the SQL statements and any parameters for a given
batch passed to an ad-hoc query. Used for debugging and logging.
6225
public static String adHocSQLFromInvocationForDebug(StoredProcedureInvocation invocation) {
        assert(invocation.getProcName().startsWith("@AdHoc"));
        ParameterSet params = invocation.getParams();
        // the final param is the byte array we need
        byte[] serializedBatchData = (byte[]) params.getParam(params.size() - 1);

        Pair<Object[], AdHocPlannedStatement[]> data = decodeSerializedBatchData(serializedBatchData);
        Object[] userparams = data.getFirst();
        AdHocPlannedStatement[] statements = data.getSecond();

        StringBuilder sb = new StringBuilder();
        if (statements.length == 0) {
            sb.append("ADHOC INVOCATION HAS NO SQL");
        }
        else if (statements.length == 1) {
            sb.append(adHocSQLStringFromPlannedStatement(statements[0], userparams));
        }
        else { // > 1
            sb.append("BEGIN ADHOC_SQL_BATCH {\n");
            for (AdHocPlannedStatement stmt : statements) {
                sb.append(adHocSQLStringFromPlannedStatement(stmt, userparams)).append("\n");
            }
            sb.append("} END ADHOC_SQL_BATCH");
        }

        return sb.toString();
    }
976336
public function debugQuery($sql, $params = array())
    {
        $keys = array();

        # build a regular expression for each parameter
        foreach ($params as $key => &$value)
        {
            if (is_string($key))
            {
                $keys[] = '/:' . $key . '/';
            }
            else
            {
                $keys[] = '/[?]/';
            }
            $value = '[#' . $value . '#]';
        }

        $query = preg_replace($keys, $params, $sql, 1, $count);

        return $query;
    }
1332577
def sql(self, dialect=None, inserts=False, creates=True,
            drops=True, metadata_source=None):
        
        result = [self.ddl(dialect, creates=creates, drops=drops)]
        if inserts:
            for row in self.inserts(dialect):
                result.append(row)
        return '\n'.join(result)
448199
private static List<ArrayParameter> arrayParametersSortedAsc(Map<String, List<Integer>> parameterNamesToIndexes,
                                                                 Map<String, Query.ParameterSetter> parameters,
                                                                 boolean allowArrayParameters) {
        List<ArrayParameters.ArrayParameter> arrayParameters = new ArrayList<>();
        for(Map.Entry<String, Query.ParameterSetter> parameter : parameters.entrySet()) {
            if (parameter.getValue().parameterCount > 1) {
                if (!allowArrayParameters) {
                    throw new Sql2oException("Array parameters are not allowed in batch mode");
                }
                for(int i : parameterNamesToIndexes.get(parameter.getKey())) {
                    arrayParameters.add(new ArrayParameters.ArrayParameter(i, parameter.getValue().parameterCount));
                }
            }
        }
        Collections.sort(arrayParameters);

        return arrayParameters;
    }
739312
public function debugDumpParams()
    {
        $str  = "SQL: [".strlen($this->_statement)."] ".$this->_statement."\n";
        $str .= "Params: ".sizeof($this->_binds)."\n";
        foreach ($this->_binds as $key => $value) {
            $str .= "Key: Name: [".strlen($key)."] $key\n";
            $str .= "name=[".strlen($key)."] \"$key\"\n";
            $str .= "is_param=1\n";
        }
        echo substr($str, 0, strlen($str)-1);
    }
540996
private String getQueryString(Query query) {
        Map<String, Object> hints = query.getHints();
        return hints != null ? (String) hints.get("query") : null;
    }
21385
def get_sql(self, with_default_expression=True):
        '''
        
        '''
        if with_default_expression:
            if self.alias:
                return '%s ALIAS %s' % (self.db_type, self.alias)
            elif self.materialized:
                return '%s MATERIALIZED %s' % (self.db_type, self.materialized)
            else:
                default = self.to_db_string(self.default)
                return '%s DEFAULT %s' % (self.db_type, default)
        else:
            return self.db_type
854801
def query(self, sql, param=None, stream=False, row_tuples=False):
        
        if not self.cursor:  # ALLOW NON-TRANSACTIONAL READS
            Log.error("must perform all queries inside a transaction")
        self._execute_backlog()

        try:
            if param:
                sql = expand_template(sql, quote_param(param))
            sql = self.preamble + outdent(sql)
            self.debug and Log.note("Execute SQL:\n{{sql}}", sql=indent(sql))

            self.cursor.execute(sql)
            if row_tuples:
                if stream:
                    result = self.cursor
                else:
                    result = wrap(list(self.cursor))
            else:
                columns = [utf8_to_unicode(d[0]) for d in coalesce(self.cursor.description, [])]
                if stream:
                    result = (wrap({c: utf8_to_unicode(v) for c, v in zip(columns, row)}) for row in self.cursor)
                else:
                    result = wrap([{c: utf8_to_unicode(v) for c, v in zip(columns, row)} for row in self.cursor])

            return result
        except Exception as e:
            e = Except.wrap(e)
            if "InterfaceError" in e:
                Log.error("Did you close the db connection?", e)
            Log.error("Problem executing SQL:\n{{sql|indent}}", sql=sql, cause=e, stack_depth=1)
1215568
public String getSQL()
    {
        final StringBuilder cmd = new StringBuilder().append(" ")
            .append(Context.getDbType().getSQLPart(SQLPart.SELECT)).append(" ");
        if (distinct) {
            cmd.append(Context.getDbType().getSQLPart(SQLPart.DISTINCT)).append(" ");
        }
        boolean first = true;
        for (final Column column : columns) {
            if (first) {
                first = false;
            } else {
                cmd.append(Context.getDbType().getSQLPart(SQLPart.COMMA));
            }
            column.appendSQL(cmd);
        }
        cmd.append(" ").append(Context.getDbType().getSQLPart(SQLPart.FROM)).append(" ");
        first = true;
        for (final FromTable fromTable : fromTables) {
            fromTable.appendSQL(first, cmd);
            if (first) {
                first = false;
            }
        }
        cmd.append(" ");
        boolean whereAdded = false;
        for (final SQLSelectPart part : parts) {
            part.appendSQL(cmd);
            cmd.append(" ");
            whereAdded = whereAdded || !whereAdded && SQLPart.WHERE.equals(part.sqlpart);
        }

        if (where != null) {
            where.setStarted(whereAdded);
            where.appendSQL(tablePrefix, cmd);
        }

        if (order != null) {
            order.appendSQL(tablePrefix, cmd);
        }
        return cmd.toString();
    }
155193
def _sqlfile_to_statements(sql):
    
    statements = (sqlparse.format(stmt, strip_comments=True).strip() for stmt in sqlparse.split(sql))
    return [stmt for stmt in statements if stmt]
993427
@Override
  public String getSqlWithValues() {
    final StringBuilder sb = new StringBuilder();
    final String statementQuery = getStatementQuery();

    // iterate over the characters in the query replacing the parameter placeholders
    // with the actual values
    int currentParameter = 0;
    for( int pos = 0; pos < statementQuery.length(); pos ++) {
      char character = statementQuery.charAt(pos);
      if( statementQuery.charAt(pos) == '?' && currentParameter <= parameterValues.size()) {
        // replace with parameter value
        Value value = parameterValues.get(currentParameter);
        sb.append(value != null ? value.toString() : new Value().toString());
        currentParameter++;
      } else {
        sb.append(character);
      }
    }

    return sb.toString();
  }
378397
def _split_queries(cls, sql):
        ""

        sql_s = dbt.compat.to_string(sql)
        sql_buf = StringIO(sql_s)
        split_query = snowflake.connector.util_text.split_statements(sql_buf)
        return [part[0] for part in split_query]
641282
public String query(String query) {
        try {
            Connection conn = this.tx().getConnection();
            ObjectNode result = this.mapper.createObjectNode();
            ArrayNode dataNode = this.mapper.createArrayNode();
            ArrayNode metaNode = this.mapper.createArrayNode();
            Statement statement = conn.createStatement();
            if (logger.isDebugEnabled()) {
                logger.debug(query);
            }
            ResultSet rs = statement.executeQuery(query);
            ResultSetMetaData rsmd = rs.getMetaData();
            boolean first = true;
            while (rs.next()) {
                int numColumns = rsmd.getColumnCount();
                ObjectNode obj = this.mapper.createObjectNode();
                for (int i = 1; i < numColumns + 1; i++) {
                    String columnName = rsmd.getColumnLabel(i);
                    int type = rsmd.getColumnType(i);
                    //make sure to obtain array using getArray()
                    //At least in H2, this makes a difference...
                    Object o = type == Types.ARRAY ? rs.getArray(i) : rs.getObject(i);
                    this.sqlDialect.putJsonObject(obj, columnName, type, o);
                    if (first) {
                        this.sqlDialect.putJsonMetaObject(this.mapper, metaNode, columnName, type, o);
                    }
                }
                first = false;
                dataNode.add(obj);
            }
            result.set("data", dataNode);
            result.set("meta", metaNode);
            return result.toString();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            this.tx().rollback();
        }
    }
800057
private Map<Integer, Integer> getColumnPosSqlTypes() {
    try {
      final Map<Integer, Integer> columnPosSqlTypes = Maps.newHashMap();
      ParameterMetaData pMetaData = this.insertPstmtForFixedBatch.getParameterMetaData();
      for (int i = 1; i <= pMetaData.getParameterCount(); i++) {
        columnPosSqlTypes.put(i, pMetaData.getParameterType(i));
      }
      return columnPosSqlTypes;
    } catch (SQLException e) {
      throw new RuntimeException("Cannot retrieve columns types for batch insert", e);
    }
  }
1088643
def get_sql(self):
        
        sql = ''
        if self.limit and self.limit > 0:
            sql += 'LIMIT {0} '.format(self.limit)
        if self.offset and self.offset > 0:
            sql += 'OFFSET {0} '.format(self.offset)
        return sql
576130
static String getSQL(Token[] statement) {

        boolean      wasDelimiter = true;
        StringBuffer sb           = new StringBuffer();

        for (int i = 0; i < statement.length; i++) {
            // when the previous statement is ')', there should be a blank before the non-delimiter statement.
            if (!statement[i].isDelimiter &&
                    (!wasDelimiter
                            || (i > 0 && ")".equals(statement[i - 1].getSQL()))))
            {
                sb.append(' ');
            }

            sb.append(statement[i].getSQL());

            wasDelimiter = statement[i].isDelimiter;
        }

        return sb.toString();
    }
1268671
def psql_string(self, sql):
        
        argv = [
            PostgresFinder.find_root() / 'psql',
            '--quiet',
            '-U', self.user,
            '-h', self.host,
            '-p', self.port,
            '-f', '-',
            self.db_name,
        ]
        popen = subprocess.Popen(argv, stdin=subprocess.PIPE)
        popen.communicate(input=sql.encode('utf-8'))
        if popen.returncode != 0:
            raise subprocess.CalledProcessError(popen.returncode, argv)