SELECT SQL生成

@param metadata エンティティメタ情報
@param type エイティティタイプ
@param sqlConfig SQLコンフィグ
@param addCondition 条件を追加するかどうか。追加する場合<code>true</code>
@return SELECT SQL
167502
protected String buildSelectSQL(final TableMetadata metadata, final Class<? extends Object> type,
			final SqlConfig sqlConfig, final boolean addCondition) {
		final List<? extends TableMetadata.Column> columns = metadata.getColumns();

		final StringBuilder sql = new StringBuilder(
				buildSelectClause(metadata, type, sqlConfig.getSqlAgentFactory().getSqlIdKeyName()));

		if (addCondition) {
			sql.append("/*BEGIN*/").append(System.lineSeparator());
			sql.append("WHERE").append(System.lineSeparator());

			for (final TableMetadata.Column col : columns) {
				final String camelColName = col.getCamelColumnName();
				final StringBuilder parts = new StringBuilder().append("\t").append("AND ")
						.append(col.getColumnIdentifier())
						.append(" = ").append("/*").append(camelColName).append("*/''").append(System.lineSeparator());
				wrapIfComment(sql, parts, col);
			}
			sql.append("/*END*/").append(System.lineSeparator());

			boolean firstFlag = true;
			final List<? extends TableMetadata.Column> keys = metadata.getKeyColumns();
			if (!keys.isEmpty()) {
				sql.append("ORDER BY").append(System.lineSeparator());
				firstFlag = true;
				for (final TableMetadata.Column col : keys) {
					sql.append("\t");
					if (firstFlag) {
						sql.append("  ");
						firstFlag = false;
					} else {
						sql.append(", ");
					}
					sql.append(col.getColumnIdentifier()).append(System.lineSeparator());
				}
			}
		}

		return sql.toString();
	}
1312296
public <T> String tableCreateStatement(Type<T> type, TableCreationMode mode) {
        String tableName = type.getName();

        QueryBuilder qb = createQueryBuilder();
        qb.keyword(CREATE);
        if (type.getTableCreateAttributes() != null) {
            for (String attribute : type.getTableCreateAttributes()) {
                qb.append(attribute, true);
            }
        }
        qb.keyword(TABLE);
        if (mode == TableCreationMode.CREATE_NOT_EXISTS) {
            qb.keyword(IF, NOT, EXISTS);
        }
        qb.tableName(tableName);
        qb.openParenthesis();

        int index = 0;
        // columns to define first
        Predicate<Attribute> filter = new Predicate<Attribute>() {
            @Override
            public boolean test(Attribute value) {
                if (value.isVersion() &&
                    !platform.versionColumnDefinition().createColumn()) {
                    return false;
                }
                if (platform.supportsInlineForeignKeyReference()) {
                    return !value.isForeignKey() && !value.isAssociation();
                } else {
                    return value.isForeignKey() || !value.isAssociation();
                }
            }
        };

        Set<Attribute<T, ?>> attributes = type.getAttributes();
        for (Attribute attribute : attributes) {
            if (filter.test(attribute)) {
                if (index > 0) {
                    qb.comma();
                }
                createColumn(qb, attribute);
                index++;
            }
        }
        // foreign keys
        for (Attribute attribute : attributes) {
            if (attribute.isForeignKey()) {
                if (index > 0) {
                    qb.comma();
                }
                createForeignKeyColumn(qb, attribute, true, false);
                index++;
            }
        }
        // composite primary key
        if(type.getKeyAttributes().size() > 1) {
            if (index > 0) {
                qb.comma();
            }
            qb.keyword(PRIMARY, KEY);
            qb.openParenthesis();
            qb.commaSeparated(type.getKeyAttributes(),
                    new QueryBuilder.Appender<Attribute<T, ?>>() {
                @Override
                public void append(QueryBuilder qb, Attribute<T, ?> value) {
                    qb.attribute(value);
                }
            });
            qb.closeParenthesis();
        }
        qb.closeParenthesis();
        return qb.toString();
    }
266215
@Override
    public void create(SchemaMigrationMetadata metadata) {
        session.execute(
                insertInto(METADATA_TABLE)
                        .ifNotExists()
                        .value(ID_COL, metadata.getId())
                        .value(INDEX_COL, metadata.getIndex())
                        .value(TOKEN_COL, metadata.getToken())
                        .value(STATUS_COL, metadata.getStatus().name())
                        .value(FINGERPRINT_COL, metadata.getFingerprint()));
    }
1314518
public static DataSource createDataSource(String source, String type, String... configs){
		String config = StringUtils.join(configs, " ");
		return createDataSource(source, type, config);
	}
43535
public void append2SQLSelect(final SQLSelect _sqlSelect)
    {
        if (iWhere != null) {
            final SQLWhere sqlWhere = _sqlSelect.getWhere();
            for (final IWhereTerm<?> term : iWhere.getTerms()) {
                if (term instanceof IWhereElementTerm) {
                    final IWhereElement element = ((IWhereElementTerm) term).getElement();
                    if (element.getAttribute() != null)
                    {
                        final String attrName = element.getAttribute();
                        for (final Type type : types) {
                            final Attribute attr = type.getAttribute(attrName);
                            if (attr != null) {
                                addAttr(_sqlSelect, sqlWhere, attr, term, element);
                                break;
                            }
                        }
                    } else if (element.getSelect() != null) {
                        final IWhereSelect select = element.getSelect();
                        for (final ISelectElement ele : select.getElements()) {
                            if (ele instanceof IBaseSelectElement) {
                                switch (((IBaseSelectElement) ele).getElement()) {
                                    case STATUS:
                                        for (final Type type : types) {
                                            final Attribute attr = type.getStatusAttribute();
                                            if (attr != null) {
                                                addAttr(_sqlSelect, sqlWhere, attr, term, element);
                                                break;
                                            }
                                        }
                                        break;
                                    default:
                                        break;
                                }
                            } else if (ele instanceof IAttributeSelectElement) {
                                final String attrName = ((IAttributeSelectElement) ele).getName();
                                for (final Type type : types) {
                                    addAttr(_sqlSelect, sqlWhere, type.getAttribute(attrName), term, element);
                                }
                            }
                        }
                    }
                }
            }
        }
        if (iOrder != null) {
            final SQLOrder sqlOrder = _sqlSelect.getOrder();
            for (final IOrderElement element: iOrder.getElements()) {
                for (final Type type : types) {
                    final Attribute attr = type.getAttribute(element.getKey());
                    if (attr != null) {
                        final SQLTable table = attr.getTable();
                        final String tableName = table.getSqlTable();
                        final TableIdx tableidx = _sqlSelect.getIndexer().getTableIdx(tableName);
                        sqlOrder.addElement(tableidx.getIdx(), attr.getSqlColNames(), element.isDesc());
                        break;
                    }
                }
            }
        }
    }
185063
public static RDBMetadata createMetadata(Connection conn,
											 TypeFactory typeFactory,
											 JdbcTypeMapper jdbcTypeMapper) throws SQLException  {

		final DatabaseMetaData md = conn.getMetaData();
		String productName = md.getDatabaseProductName();
		if (printouts) {
			System.out.println("=================================\nDBMetadataExtractor REPORT: " + productName);
			System.out.println("storesLowerCaseIdentifiers: " + md.storesLowerCaseIdentifiers());
			System.out.println("storesUpperCaseIdentifiers: " + md.storesUpperCaseIdentifiers());
			System.out.println("storesMixedCaseIdentifiers: " + md.storesMixedCaseIdentifiers());
			System.out.println("supportsMixedCaseIdentifiers: " + md.supportsMixedCaseIdentifiers());
			System.out.println("storesLowerCaseQuotedIdentifiers: " + md.storesLowerCaseQuotedIdentifiers());
			System.out.println("storesUpperCaseQuotedIdentifiers: " + md.storesUpperCaseQuotedIdentifiers());
			System.out.println("storesMixedCaseQuotedIdentifiers: " + md.storesMixedCaseQuotedIdentifiers());
			System.out.println("supportsMixedCaseQuotedIdentifiers: " + md.supportsMixedCaseQuotedIdentifiers());
			System.out.println("getIdentifierQuoteString: " + md.getIdentifierQuoteString());
		}

		QuotedIDFactory idfac;
		//  MySQL
		if (productName.contains("MySQL"))  {
			//System.out.println("getIdentifierQuoteString: " + md.getIdentifierQuoteString());
			idfac = new QuotedIDFactoryMySQL(md.storesMixedCaseIdentifiers(), "`");
		}
		else if (md.storesMixedCaseIdentifiers()) {
			// treat Exareme as a case-sensitive DB engine (like MS SQL Server)
			// "SQL Server" = MS SQL Server
			idfac = new QuotedIDFactoryIdentity("\"");
		}
		else {
			if (md.storesLowerCaseIdentifiers())
				// PostgreSQL treats unquoted identifiers as lower-case
				idfac = new QuotedIDFactoryLowerCase("\"");
			else if (md.storesUpperCaseIdentifiers())
				// Oracle, DB2, H2, HSQL
				idfac = new QuotedIDFactoryStandardSQL("\"");
			else {
				log.warn("Unknown combination of identifier handling rules: " + md.getDatabaseProductName());
				log.warn("storesLowerCaseIdentifiers: " + md.storesLowerCaseIdentifiers());
				log.warn("storesUpperCaseIdentifiers: " + md.storesUpperCaseIdentifiers());
				log.warn("storesMixedCaseIdentifiers: " + md.storesMixedCaseIdentifiers());
				log.warn("supportsMixedCaseIdentifiers: " + md.supportsMixedCaseIdentifiers());
				log.warn("storesLowerCaseQuotedIdentifiers: " + md.storesLowerCaseQuotedIdentifiers());
				log.warn("storesUpperCaseQuotedIdentifiers: " + md.storesUpperCaseQuotedIdentifiers());
				log.warn("storesMixedCaseQuotedIdentifiers: " + md.storesMixedCaseQuotedIdentifiers());
				log.warn("supportsMixedCaseQuotedIdentifiers: " + md.supportsMixedCaseQuotedIdentifiers());
				log.warn("getIdentifierQuoteString: " + md.getIdentifierQuoteString());

				idfac = new QuotedIDFactoryStandardSQL("\"");
			}
		}

		RDBMetadata metadata = new RDBMetadata(md.getDriverName(), md.getDriverVersion(),
							productName, md.getDatabaseProductVersion(), idfac, jdbcTypeMapper, typeFactory);

		return metadata;
	}
76319
def _select_sql(self, **kwargs):
        
        return 'SELECT {distinct}{modifier}{select}'.format(
              distinct='DISTINCT ' if self._distinct else '',
              modifier='{} '.format(' '.join(self._modifiers)) if self._modifiers else '',
              select=','.join(term.get_sql(with_alias=True, subquery=True, **kwargs)
                              for term in self._selects),
        )
1187857
public SQLUnit toSQL(final TableUnit tableUnit, final Map<String, String> logicAndActualTableMap, final ShardingRule shardingRule, final ShardingDataSourceMetaData shardingDataSourceMetaData) {
        StringBuilder result = new StringBuilder();
        List<Object> insertParameters = new LinkedList<>();
        for (Object each : segments) {
            if (!(each instanceof ShardingPlaceholder)) {
                result.append(each);
                continue;
            }
            String logicTableName = ((ShardingPlaceholder) each).getLogicTableName();
            String actualTableName = logicAndActualTableMap.get(logicTableName);
            if (each instanceof TablePlaceholder) {
                appendTablePlaceholder((TablePlaceholder) each, actualTableName, result);
            } else if (each instanceof SchemaPlaceholder) {
                appendSchemaPlaceholder(shardingRule, shardingDataSourceMetaData, actualTableName, result);
            } else if (each instanceof IndexPlaceholder) {
                appendIndexPlaceholder((IndexPlaceholder) each, actualTableName, result);
            } else if (each instanceof InsertValuesPlaceholder) {
                appendInsertValuesPlaceholder(tableUnit, (InsertValuesPlaceholder) each, insertParameters, result);
            } else {
                result.append(each);
            }
        }
        return insertParameters.isEmpty() ? new SQLUnit(result.toString(), new ArrayList<>(parameters)) : new SQLUnit(result.toString(), insertParameters);
    }
839056
public SqlInfo buildBetweenSql(String fieldText, Object startValue, Object endValue) {
        /* 根据开始文本和结束文本判断执行是大于、小于还是区间的查询sql和参数的生成 */
        if (startValue != null && endValue == null) {
            join.append(prefix).append(fieldText).append(ZealotConst.GTE_SUFFIX);
            params.add(startValue);
        } else if (startValue == null && endValue != null) {
            join.append(prefix).append(fieldText).append(ZealotConst.LTE_SUFFIX);
            params.add(endValue);
        } else {
            join.append(prefix).append(fieldText).append(ZealotConst.BT_AND_SUFFIX);
            params.add(startValue);
            params.add(endValue);
        }

        return sqlInfo.setJoin(join).setParams(params);
    }
217479
private Number getIdColumnData(ResultSet resultSet, ResultSetMetaData metaData, int columnIndex)
			throws SQLException {
		int typeVal = metaData.getColumnType(columnIndex);
		switch (typeVal) {
			case Types.BIGINT:
			case Types.DECIMAL:
			case Types.NUMERIC:
				return (Number) resultSet.getLong(columnIndex);
			case Types.INTEGER:
				return (Number) resultSet.getInt(columnIndex);
			default:
				String columnName = metaData.getColumnName(columnIndex);
				throw new SQLException(
						"Unexpected ID column type " + TypeValMapper.getSqlTypeForTypeVal(typeVal) + " (typeVal "
								+ typeVal + ") in column " + columnName + "(#" + columnIndex + ") is not a number");
		}
	}
1281463
private String buildSelectSQL(boolean addOrderBy) {
        SQLParams sqlParams = SQLParams.builder()
                .modelClass(this.modelClass)
                .selectColumns(this.selectColumns)
                .tableName(this.tableName)
                .pkName(this.primaryKeyColumn)
                .conditionSQL(this.conditionSQL)
                .excludedColumns(this.excludedColumns)
                .isSQLLimit(isSQLLimit)
                .build();

        ifThen(addOrderBy, () -> sqlParams.setOrderBy(this.orderBySQL.toString()));

        return Anima.of().dialect().select(sqlParams);
    }
1282634
public static OptimizeEngine newInstance(final ShardingRule shardingRule, final SQLStatement sqlStatement, final List<Object> parameters, final GeneratedKey generatedKey) {
        if (sqlStatement instanceof InsertStatement) {
            return new InsertOptimizeEngine(shardingRule, (InsertStatement) sqlStatement, parameters, generatedKey);
        }
        if (sqlStatement instanceof SelectStatement || sqlStatement instanceof DMLStatement) {
            return new QueryOptimizeEngine(sqlStatement.getRouteConditions().getOrCondition(), parameters);
        }
        // TODO do with DDL and DAL
        return new QueryOptimizeEngine(sqlStatement.getRouteConditions().getOrCondition(), parameters);
    }
329221
private StringBuilder appendPostTypes(final EnumSet<Post.Type> types, final StringBuilder sql) {
      int typesCount = types != null ? types.size() : 0;
      switch(typesCount) {
         case 0:
            break;
         case 1:
            sql.append(" AND post_type=").append(String.format("'%s'", types.iterator().next().toString()));
            break;
         default:
            sql.append(" AND post_type IN (");
            sql.append(inJoiner.join(types.stream().map(t -> String.format("'%s'", t.toString())).collect(Collectors.toSet())));
            sql.append(")");
            break;
      }

      return sql;
   }
633476
public WhereCondition WHERE(WhereCondition whereCondition) {
        checkTokenOrderIsCorrect(ESqlToken.WHERE);
        mSgSQL.append("(");
        mSgSQL.append(whereCondition.toWhereConditionPart());
        mSgSQL.append(")");
        return WhereCondition.this;
    }
1132041
public static <T> List<T> buildSQLResult(SQLRestResponse result,Class<T> type){
		if(result == null || result.getRows() == null || result.getRows().size() == 0)
			return null;
		if(result.getRows() != null && result.getRows().size() > 0) {
			List<Object[]> rows = result.getRows();
			List<T> datas = new ArrayList<T>(rows.size());
			ColumnMeta[] metas = result.getColumns();
			if (Map.class.isAssignableFrom(type)) {
				Map<String,Object> data = null;
				for(int i = 0; i < rows.size(); i ++) {
					Object[] row = rows.get(i);
					data = new HashMap<String,Object>(metas.length);
					for (int j = 0; j < metas.length; j++) {
						data.put(metas[j].getName(),row[j]);
					}
					datas.add((T)data);
				}

			} else {
				DateFormat defaultDateFormat = SerialUtil.getDateFormateMeta().toDateFormat();
				T valueObject = null;
				for(int i = 0; i < rows.size(); i ++) {
					Object[] row = rows.get(i);
					valueObject = buildObject(type,  metas,  row,defaultDateFormat);
					datas.add(valueObject);
				}
			}
			return datas;
		}
		else {
			return null;
		}

	}
844249
public SqlBuilder where(final Collection<Condition> cons) {
    conditions.addAll(cons);
    return params(Conditions.getParamMap(cons));
  }
1124077
function (type) {
            var sql = [("" + type).toUpperCase()];
            try {
                this._static[sql + "_CLAUSE_METHODS"].forEach(function (m) {
                    if (m.match("With")) {
                        this[m](sql);
                    } else {
                        var sqlRet = this[m]();
                        if (sqlRet) {
                            sql.push(sqlRet);
                        }
                    }
                }, this);
            } catch (e) {
                throw e;
            }
            return sql.join("");
        }