Generate SQL fragment made of list.
190356
protected function sqlList($buffer_id, $decorations)
	{
		$first = true;

		if (isset($this->buffers[$buffer_id])) {
			if ($decorations & (self::INDENT | self::SUB_INDENT)) {
				if ($decorations & (self::BRACKETS | self::SUB_INDENT)) {
					echo $this->sub_indent;
				} else {
					echo $this->indent;
				}
			} else if ($decorations & (self::LABEL | self::BRACKETS)) {
				echo ' ';
			}
			if ($decorations & self::LABEL) {
				echo $buffer_id;
			}
			if ($decorations & self::BRACKETS) {
				echo '(';
			}
			foreach ($this->buffers[$buffer_id] as $buf) {
				if ($decorations & self::NO_SEPARATOR) {
					if ($first) {
						$first = false;
					} else {
						echo "\n", $this->sub_indent;
					}
				} else if ($decorations & self::BRACKETS) {
					if ($first) {
						$first = false;
					} else {
						echo ", ";
					}
				} else {
					if ($first) {
						$first = false;
						echo ' ';
					} else {
						echo ",\n", $this->sub_indent;
					}
				}
				$this->sqlBuffer($buf);
			}
			if ($decorations & self::BRACKETS) {
				echo ')';
			}
			if ($decorations & self::COMMA) {
				echo ",";
			}
			if ($decorations & self::EOL) {
				echo "\n";
			}
		}
	}
175669
def compile(self):
        
        # Can't tell if this is a hack or not. Revisit later
        self.context.set_query(self)

        # If any subqueries, translate them and add to beginning of query as
        # part of the WITH section
        with_frag = self.format_subqueries()

        # SELECT
        select_frag = self.format_select_set()

        # FROM, JOIN, UNION
        from_frag = self.format_table_set()

        # WHERE
        where_frag = self.format_where()

        # GROUP BY and HAVING
        groupby_frag = self.format_group_by()

        # ORDER BY
        order_frag = self.format_order_by()

        # LIMIT
        limit_frag = self.format_limit()

        # Glue together the query fragments and return
        query = '\n'.join(
            filter(
                None,
                [
                    with_frag,
                    select_frag,
                    from_frag,
                    where_frag,
                    groupby_frag,
                    order_frag,
                    limit_frag,
                ],
            )
        )
        return query
349254
def generate_table_from(data):
    ""
    table = Texttable(max_width=120)
    table.add_row(["view", "method", "status", "count", "minimum", "maximum", "mean", "stdev", "queries", "querytime"]) 
    table.set_cols_align(["l", "l", "l", "r", "r", "r", "r", "r", "r", "r"])

    for item in sorted(data):
        mean = round(sum(data[item]['times'])/data[item]['count'], 3)

        mean_sql = round(sum(data[item]['sql'])/data[item]['count'], 3)
        mean_sqltime = round(sum(data[item]['sqltime'])/data[item]['count'], 3)
        
        sdsq = sum([(i - mean) ** 2 for i in data[item]['times']])
        try:
            stdev = '%.2f' % ((sdsq / (len(data[item]['times']) - 1)) ** .5)
        except ZeroDivisionError:
            stdev = '0.00'

        minimum = "%.2f" % min(data[item]['times'])
        maximum = "%.2f" % max(data[item]['times'])
        table.add_row([data[item]['view'], data[item]['method'], data[item]['status'], data[item]['count'], minimum, maximum, '%.3f' % mean, stdev, mean_sql, mean_sqltime])

    return table.draw()
391727
private String generatePageSQLStatement(boolean tableExists,
			Map<String, Set<Integer>> dataSourceToUse)
	{
		StringBuffer output = new StringBuffer();

		// Statement creates table for Template Id -> Page Id
		output.append("CREATE TABLE IF NOT EXISTS "
				+ GeneratorConstants.TABLE_TPLID_PAGEID
				+ " ("
				+ "templateId INTEGER UNSIGNED NOT NULL,"
				+ "pageId INTEGER UNSIGNED NOT NULL, UNIQUE(templateId, pageId));\r\n");

		// Statement for data into templateId -> pageId
		output.append(this.generateSQLStatementForDataInTable(dataSourceToUse,
				GeneratorConstants.TABLE_TPLID_PAGEID));

		if (!tableExists) {
			// Create index statement if table does not exists
			output.append("CREATE INDEX pageIdx ON "
					+ GeneratorConstants.TABLE_TPLID_PAGEID
					+ "(pageId);");
			output.append("\r\n");
		}

		return output.toString();

	}
806738
function listToFragment(list) {
  var fragment = document.createDocumentFragment();
  for (var i = 0, l = list.length; i < l; i++) {
    // Use toFragment since this may be an array of text, a jQuery object of `<template>`s, etc.
    fragment.appendChild(toFragment(list[i]));
    if (l === list.length + 1) {
      // adjust for NodeLists which are live, they shrink as we pull nodes out of the DOM
      i--;
      l--;
    }
  }
  return fragment;
}
568687
def build_joins(self):
        
        join_parts = []

        # get the sql for each join object
        for join_item in self.joins:
            join_parts.append(join_item.get_sql())

        # if there are any joins, combine them
        if len(join_parts):
            combined_joins = ' '.join(join_parts)
            return '{0} '.format(combined_joins)
        return ''
207470
def from_list(cls, database, key, data, clear=False):
        
        lst = cls(database, key)
        if clear:
            lst.clear()
        lst.extend(data)
        return lst
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);
	}
17225
public static void generateSQLForInsertDynamic(final SQLiteModelMethod method, MethodSpec.Builder methodBuilder) {
		methodBuilder.addComment("generate SQL for insert");
		JQLChecker checker = JQLChecker.getInstance();

		// replace the table name, other pieces will be removed
		String sql = checker.replace(method, method.jql, new JQLReplacerListenerImpl(method) {

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

		final One<Integer> counter = new One<Integer>(0);
		sql = checker.replaceVariableStatements(method, sql, new JQLReplaceVariableStatementListenerImpl() {

			@Override
			public String onColumnNameSet(String statement) {
				counter.value0++;
				return "%s";
			}

			@Override
			public String onColumnValueSet(String statement) {
				counter.value0++;
				return "%s";
			}

		});

		if (counter.value0 == 2) {
			methodBuilder.addStatement("String _sql=String.format($S, _contentValues.keyList(), _contentValues.keyValueList())", sql);
		} else {
			methodBuilder.addStatement("String _sql=String.format($S, _contentValues.keyList())", sql);
		}
	}
933759
public List<Map<String, Object>> selectList(String sql) {
        String msId = msUtils.select(sql);
        return sqlSession.selectList(msId);
    }
640814
public Collection<SQLSegment> extract(final SQLAST ast) {
        Collection<SQLSegment> result = new LinkedList<>();
        Preconditions.checkState(ast.getSQLStatementRule().isPresent());
        Map<ParserRuleContext, Integer> parameterMarkerIndexes = getParameterMarkerIndexes(ast.getParserRuleContext());
        for (SQLSegmentExtractor each : ast.getSQLStatementRule().get().getExtractors()) {
            if (each instanceof OptionalSQLSegmentExtractor) {
                Optional<? extends SQLSegment> sqlSegment = ((OptionalSQLSegmentExtractor) each).extract(ast.getParserRuleContext(), parameterMarkerIndexes);
                if (sqlSegment.isPresent()) {
                    result.add(sqlSegment.get());
                }
            } else if (each instanceof CollectionSQLSegmentExtractor) {
                result.addAll(((CollectionSQLSegmentExtractor) each).extract(ast.getParserRuleContext(), parameterMarkerIndexes));
            }
        }
        return result;
    }
949656
def _from_sql(self, soql):
        """"""
        # pylint:disable=too-many-branches,too-many-nested-blocks
        assert not self.soql, "Don't use _from_sql method directly"
        self.soql = soql
        soql, self.subqueries = split_subquery(soql)
        match_parse = re.match(r'SELECT (.*) FROM (\w+)\b(.*)$', soql, re.I)
        if not match_parse:
            raise ProgrammingError('Invalid SQL: %s' % self.soql)
        fields_sql, self.root_table, self.extra_soql = match_parse.groups()
        fields = [x.strip() for x in fields_sql.split(',')]
        self.is_aggregation = bool(pattern_groupby.search(self.extra_soql) or
                                   pattern_aggregation.search(fields[0]))
        self.is_plain_count = fields[0].upper() == 'COUNT()'
        consumed_subqueries = 0
        expr_alias_counter = 0
        #
        if not self.is_plain_count:
            for field in fields:
                if self.is_aggregation:
                    match = re.search(r'\b\w+$', field)
                    if match:
                        alias = match.group()
                        assert alias not in RESERVED_WORDS, "invalid alias name"
                        if match.start() > 0 and field[match.start() - 1] == ' ':
                            field = field[match.start() - 1]
                    else:
                        alias = 'expr{}'.format(expr_alias_counter)
                        expr_alias_counter += 1
                    assert '&' not in field, "Subquery not expected as field in aggregation query"
                elif '&' in field:
                    assert field == '(&)'  # verify that the subquery was in parentheses
                    subquery = QQuery(self.subqueries[consumed_subqueries][0])
                    consumed_subqueries += 1
                    self.has_child_rel_field = True
                    field = subquery
                    # TODO more child relationships to the same table
                    alias = subquery.root_table
                else:
                    alias = field
                    if '.' in alias:
                        if alias.split('.', 1)[0].lower() == self.root_table.lower():
                            alias = alias.split('.', 1)[1]
                        if '.' in alias:
                            # prepare paths for possible empty outer joins
                            subroots = self.subroots
                            root_crumbs = alias.lower().split('.')[:-1]
                            for scrumb in root_crumbs:
                                subroots.setdefault(scrumb, {})
                                subroots = subroots[scrumb]
                self.aliases.append(alias)
                self.fields.append(field)
1088787
def to_sql
      sql = ["select"]
      select_values << "*" if select_values.empty?

      sql << select_values.uniq.join(", ")

      sql << "from #{build_series_name}"

      sql << "where #{where_values.join(' and ')}" unless where_values.empty?

      unless group_values.empty? && time_value.nil?
        group_fields = (time_value.nil? ? [] : ['time(' + @values[:time] + ')']) + group_values
        group_fields.uniq!
        sql << "group by #{group_fields.join(', ')}"
      end

      sql << "fill(#{fill_value})" unless fill_value.nil?

      sql << "order by #{order_values.uniq.join(',')}" unless order_values.empty?

      sql << "limit #{limit_value}" unless limit_value.nil?
      sql << "offset #{offset_value}" unless offset_value.nil?
      sql << "slimit #{slimit_value}" unless slimit_value.nil?
      sql << "soffset #{soffset_value}" unless soffset_value.nil?
      sql.join " "
    end
794798
@Override
   public Sql[] generateSql(final InsertStatement statement, final Database database,
         final SqlGeneratorChain sqlGeneratorChain) {
      for (final Entry<String, Object> entry : statement.getColumnValues().entrySet()) {
         entry.setValue(handleColumnValue(entry.getValue(), database));
      }
      return super.generateSql(statement, database, sqlGeneratorChain);
   }
1306935
public List<Object[]> select(Sql sql) throws SQLException {
		
		long start =  System.currentTimeMillis();
		
		if (sql.validate() == false) {
			return null;
		}
		
		List<Object[]> dataList = null;
		
		if (sql.isSelect()) {
			
			ResultSet rs = null;
			PreparedStatement stmt = null;

			try {
				stmt = this.createStatment(conn, sql);
				rs = stmt.executeQuery();
				
				dataList = getResultSet(rs);

			} catch (SQLException e) {
				throw e;
			} finally {
				try {
					if (rs != null && rs.isClosed() == false) {
						rs.close();
					}
					if (stmt != null && stmt.isClosed() == false) {
						stmt.close();
					}
				} catch (SQLException e) {
					throw e;
				}
			}
		}
		
		logger.debug(String.format("Execute %s used %d ms", sql.getSql(), System.currentTimeMillis() - start));
		
		return dataList;
	}
714250
public Sql listSeparator(/*@Untainted*/ String sql) {
    if (listFirstItem.peek()) {
      listFirstItem.pop();
      listFirstItem.push(false);
      return this;
    } else {
      return append(sql);
    }
  }
615975
def _generate_sql(self, keys, changed_keys):
        
        for key in reversed(keys):
            app_label, sql_name = key
            new_item = self.to_sql_graph.nodes[key]
            sql_deps = [n.key for n in self.to_sql_graph.node_map[key].parents]
            reverse_sql = new_item.reverse_sql

            if key in changed_keys:
                operation_cls = AlterSQL
                kwargs = {}
                # in case of replace mode, AlterSQL will hold sql, reverse_sql and
                # state_reverse_sql, the latter one will be used for building state forward
                # instead of reverse_sql.
                if new_item.replace:
                    kwargs['state_reverse_sql'] = reverse_sql
                    reverse_sql = self.from_sql_graph.nodes[key].sql
            else:
                operation_cls = CreateSQL
                kwargs = {'dependencies': list(sql_deps)}

            operation = operation_cls(
                sql_name, new_item.sql, reverse_sql=reverse_sql, **kwargs)
            sql_deps.append(key)
            self.add_sql_operation(app_label, sql_name, operation, sql_deps)