Generate sql statement for data defined in {@code dataSourceToUse} and for table
in {@code tableToWrite}

@param dataSourceToUse
source to use for string generation
@param tableToWrite
table to use to store data
@return generated sql string
773515
private String generateSQLStatementForDataInTable(
			Map<String, Set<Integer>> dataSourceToUse, String tableToWrite)
	{
		StringBuffer output = new StringBuffer();
		for (Entry<String, Set<Integer>> e : dataSourceToUse.entrySet()) {

			String curTemplateName = e.getKey();

			Set<Integer> curPageIds = e.getValue();

			//FIXME Problem - we do reuse existing ids here, but we treat template names from the pages and from revisions separately - resulting in
			if (!curTemplateName.isEmpty() && !curPageIds.isEmpty()) {
				//if template name does not have an id in the tplname-id map
				String id = "LAST_INSERT_ID()";
				if (!tplNameToTplId.containsKey(curTemplateName)) {
					output.append("INSERT INTO "
							+ GeneratorConstants.TABLE_TPLID_TPLNAME
							+ " (templateName) VALUES ('" + curTemplateName
							+ "');");
					output.append("\r\n");
				}
				else {
					//if template name has an id in the tplname-id map
					id = tplNameToTplId.get(curTemplateName).toString();
				}

				StringBuilder curValues = new StringBuilder();
				for (Integer pId : curPageIds) {
					if (curValues.length() > 0) {
						curValues.append(",");
					}
					curValues.append("(" + id + ", ");
					curValues.append(pId);
					curValues.append(")");
				}
				output.append("REPLACE INTO " + tableToWrite + " VALUES "
						+ curValues + ";");
				output.append("\r\n");

			}
		}

		return output.toString();
	}
1106856
public static String execQueryAllRows(@NotNull final SQLInputs sqlInputs) throws Exception {
        ConnectionService connectionService = new ConnectionService();
        try (final Connection connection = connectionService.setUpConnection(sqlInputs)) {
            connection.setReadOnly(true);

            Statement statement = connection.createStatement(sqlInputs.getResultSetType(), sqlInputs.getResultSetConcurrency());

            statement.setQueryTimeout(sqlInputs.getTimeout());
            final ResultSet resultSet = statement.executeQuery(sqlInputs.getSqlCommand());

            final String resultSetToDelimitedColsAndRows = Format.resultSetToDelimitedColsAndRows(resultSet, sqlInputs.isNetcool(), sqlInputs.getColDelimiter(), sqlInputs.getRowDelimiter());
            if (resultSet != null) {
                resultSet.close();
            }
            return resultSetToDelimitedColsAndRows;
        }
    }
187306
protected PreparedStatement getPreparedStatement(final SqlContext sqlContext) throws SQLException {
		PreparedStatement stmt = ((LocalTransactionManager) transactionManager).getPreparedStatement(sqlContext);
		// プロパティ設定
		applyProperties(stmt);
		return stmt;
	}
399153
public static DataSource initializeTxSimple(DataSource dataSource) {
      TxTransactionManager txManager = new TxTransactionManager(dataSource);
      return initializeTxCustom(txManager.getTxDataSource(), txManager, txManager);
   }
454668
public ConnectedCrud<T, K> to(DataSource dataSource) throws SQLException {
        Connection connection = dataSource.getConnection();
        try {
            return new ConnectedCrud<T, K>(new DataSourceTransactionTemplate(dataSource), to(connection));
        } finally {
            connection.close();
        }
    }
259781
public static void prepareDataSource(DataSource ds) throws SQLException {
    Connection con = null;
    String sql;
    try {
      con = ds.getConnection();
      con.setAutoCommit(false);

      DatabaseMetaData meta = con.getMetaData();
      ResultSet rs = meta.getTables(null, null, null, new String[]{"TABLE"});
      int tableNameColumn = rs.findColumn("TABLE_NAME");
      int count = 0;
      while (rs.next()) {
        String tableName = rs.getString(tableNameColumn);
        if (tableName.equalsIgnoreCase("CachedClasses")) {
          count++;
        }
      }

      if (count == 0) {
        String blobType = DbUtil.getTypeName(Types.BLOB, con);
        String nameType = DbUtil.getTypeName(Types.VARCHAR, 1024, con);
        String md5Type = DbUtil.getTypeName(Types.BINARY, 16, con);

        sql =  "CREATE TABLE CachedClasses ( \n" +
            "  Name " + nameType + " NOT NULL, \n" +
            "  MD5 " + md5Type + " NOT NULL, \n" +
            "  Definition " + blobType + " NOT NULL, \n" +
            "  PRIMARY KEY (Name, MD5) \n" +
            ")";
        DbUtil.update(ds, sql);
        con.commit();
      }

      con.setAutoCommit(true);
    } catch (SQLException e) {
      DbUtil.rollback(con);
      throw e;
    } finally {
      DbUtil.close(con);
    }
  }
506681
@Override
	public SqlContext createSqlContext() {
		SqlContextImpl sqlContext = new SqlContextImpl();
		Map<String, Parameter> paramMap = new ConcurrentHashMap<>(getConstParameterMap());

		// 自動バインド用パラメータ生成クラスが指定されている場合は、そこで生成されたパラメータをパラメータマップに追加する
		if (autoBindParameterCreators != null && !autoBindParameterCreators.isEmpty()) {
			for (AutoBindParameterCreator creator : getAutoBindParameterCreators()) {
				Map<String, Parameter> bindMap = creator.getBindParameterMap();
				if (bindMap != null && !bindMap.isEmpty()) {
					paramMap.putAll(bindMap);
				}
			}
		}

		sqlContext.setConstParameterMap(paramMap);
		sqlContext.setSqlFilterManager(getSqlFilterManager());
		sqlContext.setParameterMapperManager(new BindParameterMapperManager(parameterMapperManager));
		sqlContext.setQueryAutoParameterBinder(queryAutoParameterBinder);
		sqlContext.setUpdateAutoParameterBinder(updateAutoParameterBinder);

		return sqlContext;
	}
532617
protected void generateSql(DaoDesc daoDesc, SqlDesc sqlDesc) {
    File sqlFile =
        FileUtil.createSqlDir(
            sqlConfig.getDestDir(), daoDesc.getQualifiedName(), sqlDesc.getFileName());
    GenerationContext context =
        new GenerationContext(
            sqlDesc, sqlFile, sqlDesc.getTemplateName(), "UTF-8", sqlConfig.isOverwrite());
    generator.generate(context);
  }
219863
@SneakyThrows
    public static XADataSource build(final DatabaseType databaseType, final DataSource dataSource) {
        XADataSource result = createXADataSource(databaseType);
        Properties xaProperties = XAPropertiesFactory.createXAProperties(databaseType).build(SWAPPER.swap(dataSource));
        PropertyUtils.setProperties(result, xaProperties);
        return result;
    }
1238811
@Override
  public final synchronized DataSource lazyGetDataSource() throws Exception {
    String beanName = getDataSourceName();
    HikariDataSource dataSource =
      (HikariDataSource) getBeansMap().get(beanName);
    if (dataSource == null) {
      dataSource = new HikariDataSource();
      dataSource.setJdbcUrl(getDatabaseName());
      dataSource.setDriverClassName("org.sqlite.JDBC");
      getBeansMap().put(beanName, dataSource);
      lazyGetLogger().info(null, FactoryAppBeansSqlite.class, beanName
        + " has been created.");
    }
    return dataSource;
  }
703155
protected SQLiteDatabaseSchema createDataSource(Element databaseSchema) {
		if (databaseSchema.getKind() != ElementKind.INTERFACE) {
			String msg = String.format("Class %s: only interfaces can be annotated with @%s annotation",
					databaseSchema.getSimpleName().toString(), BindDataSource.class.getSimpleName());
			throw (new InvalidKindForAnnotationException(msg));
		}

		if (!databaseSchema.getSimpleName().toString().endsWith(BindDataSourceBuilder.SUFFIX)) {
			String msg = String.format(
					"Interface %s marked with @%s annotation must have a typeName with suffix \""
							+ BindDataSourceBuilder.SUFFIX + "\" to be used with @BindDataSource",
					databaseSchema.getSimpleName().toString(), BindDataSource.class.getSimpleName());
			throw (new InvalidNameException(msg));
		}

		// go ahead to dataSource analysis
		// ASSERT: daoElement and beanElement is element for dao and bean
		// associated
		String schemaFileName = AnnotationUtility.extractAsString(databaseSchema, BindDataSource.class,
				AnnotationAttributeType.FILENAME);
		int schemaVersion = AnnotationUtility.extractAsInt(databaseSchema, BindDataSource.class,
				AnnotationAttributeType.VERSION);
		boolean generateLog = AnnotationUtility.extractAsBoolean(databaseSchema, BindDataSource.class,
				AnnotationAttributeType.GENERATE_LOG);
		boolean generateSchema = AnnotationUtility.extractAsBoolean(databaseSchema, BindDataSource.class,
				AnnotationAttributeType.GENERATE_SCHEMA);
		boolean generateAsyncTask = AnnotationUtility.extractAsBoolean(databaseSchema, BindDataSource.class,
				AnnotationAttributeType.GENERATE_ASYNC_TASK);
		boolean generateCursorWrapper = AnnotationUtility.extractAsBoolean(databaseSchema, BindDataSource.class,
				AnnotationAttributeType.GENERATE_CURSOR_WRAPPER);
		boolean generateRx = AnnotationUtility.extractAsBoolean(databaseSchema, BindDataSource.class,
				AnnotationAttributeType.GENERATE_RX);

		// get all dao used within SQLDatabaseSchema annotation
		List<String> daoIntoDataSource = AnnotationUtility.extractAsClassNameArray(elementUtils, databaseSchema,
				BindDataSource.class, AnnotationAttributeType.DAO_SET);

		String configCursorFactory = ReferredClasses.NO_CURSOR_FACTORY_CLASS_NAME;
		String configDatabaseErrorHandler = ReferredClasses.NO_DATABASE_ERROR_HANDLER_CLASS_NAME;
		String configDatabaseLifecycleHandler = ReferredClasses.NO_DATABASE_LIFECYCLE_HANDLER_CLASS_NAME;
		boolean configInMemory = false;
		boolean configLogEnabled = true;
		String configPopulatorClass = NoPopulator.class.getName();

		// manage for annotated data-source options
		BindDataSourceOptions dataSourceOptionsAnnotation = databaseSchema.getAnnotation(BindDataSourceOptions.class);
		if (dataSourceOptionsAnnotation != null) {
			configInMemory = AnnotationUtility.extractAsBoolean(databaseSchema, BindDataSourceOptions.class,
					AnnotationAttributeType.IN_MEMORY);
			configLogEnabled = AnnotationUtility.extractAsBoolean(databaseSchema, BindDataSourceOptions.class,
					AnnotationAttributeType.LOG_ENABLED);
			configPopulatorClass = AnnotationUtility.extractAsClassName(databaseSchema, BindDataSourceOptions.class,
					AnnotationAttributeType.POPULATOR);
			configCursorFactory = AnnotationUtility.extractAsClassName(databaseSchema, BindDataSourceOptions.class,
					AnnotationAttributeType.CURSOR_FACTORY);
			configDatabaseLifecycleHandler = AnnotationUtility.extractAsClassName(databaseSchema,
					BindDataSourceOptions.class, AnnotationAttributeType.DATABASE_LIFECYCLE_HANDLER);
		}

		SQLiteDatabaseSchema schema = new SQLiteDatabaseSchema((TypeElement) databaseSchema, schemaFileName,
				schemaVersion, generateSchema, generateLog, generateAsyncTask, generateCursorWrapper, generateRx,
				daoIntoDataSource, configCursorFactory, configDatabaseErrorHandler, configDatabaseLifecycleHandler,
				configInMemory, configLogEnabled, configPopulatorClass);

		// manage for content provider generation
		BindContentProvider contentProviderAnnotation = databaseSchema.getAnnotation(BindContentProvider.class);
		if (contentProviderAnnotation != null) {
			schema.generateContentProvider = true;
			schema.contentProvider = new SQLiteModelContentProvider();
			schema.contentProvider.authority = contentProviderAnnotation.authority();
		} else {
			schema.generateContentProvider = false;
		}

		return schema;

	}
311889
public static PreparedStatement createTrackPointsTable(Connection connection, String trackPointsTableName,boolean isH2) throws SQLException {
        try (Statement stmt = connection.createStatement()) {
            StringBuilder sb = new StringBuilder("CREATE TABLE ");
            sb.append(trackPointsTableName).append(" (");
            if(isH2){
                sb.append("the_geom POINT CHECK ST_SRID(THE_GEOM) = 4326,");
            }
            else{
                sb.append("the_geom GEOMETRY(POINT, 4326),");
            }
            sb.append(" id INT,");
            sb.append(GPXTags.LAT.toLowerCase()).append(" FLOAT8,");
            sb.append(GPXTags.LON.toLowerCase()).append(" FLOAT8,");
            sb.append(GPXTags.ELE.toLowerCase()).append(" FLOAT8,");
            sb.append(GPXTags.TIME.toLowerCase()).append(" TEXT,");
            sb.append(GPXTags.MAGVAR.toLowerCase()).append(" FLOAT8,");
            sb.append(GPXTags.GEOIDHEIGHT.toLowerCase()).append(" FLOAT8,");
            sb.append(GPXTags.NAME.toLowerCase()).append(" TEXT,");
            sb.append(GPXTags.CMT.toLowerCase()).append(" TEXT,");
            sb.append("description").append(" TEXT,");
            sb.append(GPXTags.SRC.toLowerCase()).append(" TEXT,");
            sb.append(GPXTags.HREF.toLowerCase()).append(" TEXT,");
            sb.append(GPXTags.HREFTITLE.toLowerCase()).append(" TEXT,");
            sb.append(GPXTags.SYM.toLowerCase()).append(" TEXT,");
            sb.append(GPXTags.TYPE.toLowerCase()).append(" TEXT,");
            sb.append(GPXTags.FIX.toLowerCase()).append(" TEXT,");
            sb.append(GPXTags.SAT.toLowerCase()).append(" INT,");
            sb.append(GPXTags.HDOP.toLowerCase()).append(" FLOAT8,");
            sb.append(GPXTags.VDOP.toLowerCase()).append(" FLOAT8,");
            sb.append(GPXTags.PDOP.toLowerCase()).append(" FLOAT8,");
            sb.append(GPXTags.AGEOFDGPSDATA.toLowerCase()).append(" FLOAT8,");
            sb.append(GPXTags.DGPSID.toLowerCase()).append(" INT,");
            sb.append(GPXTags.EXTENSIONS.toLowerCase()).append(" BOOLEAN,");
            sb.append("track_segment_id").append(" INT);");
            stmt.execute(sb.toString());
        }
        //We return the preparedstatement of the waypoints table
        StringBuilder insert = new StringBuilder("INSERT INTO ").append(trackPointsTableName).append(" VALUES ( ?");
        for (int i = 1; i < GpxMetadata.RTEPTFIELDCOUNT; i++) {
            insert.append(",?");
        }
        insert.append(");");
        return connection.prepareStatement(insert.toString());
    }
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();
   }
1156441
public String toSQL(final MasterSlaveRule masterSlaveRule, final ShardingDataSourceMetaData shardingDataSourceMetaData) {
        StringBuilder result = new StringBuilder();
        for (Object each : segments) {
            if (each instanceof SchemaPlaceholder) {
                result.append(shardingDataSourceMetaData.getActualDataSourceMetaData(masterSlaveRule.getMasterDataSourceName()).getSchemaName());
            } else {
                result.append(each);
            }
        }
        return result.toString();
    }
161906
public static SqlContext getSqlContext(BeanDescFactory beanDescFactory, Object param) {
        SqlContext context = new SqlContextImpl();

        if (param != null) {
            BeanDesc beanDesc = beanDescFactory.getBeanDesc(param);
            for (int i = 0; i < beanDesc.getPropertyDescSize(); i++) {
                PropertyDesc pd = beanDesc.getPropertyDesc(i);
                context.addArg(pd.getPropertyName(), pd.getValue(param), pd
                        .getPropertyType());
            }
        }

        return context;
    }
1357648
@Override
    public void sql(BindingSQLContext<JsonArray> ctx) {
        // Depending on how you generate your SQL, you may need to explicitly distinguish
        // between jOOQ generating bind variables or inlined literals. If so, use this check:
        // ctx.render().paramType() == INLINED
        RenderContext context = ctx.render().visit(DSL.val(ctx.convert(converter()).value()));
        if (SQLDialect.POSTGRES.equals(ctx.configuration().dialect().family()))
        {
            context.sql("::json");
        }
    }
1182464
public String buildAllDataSql()
    {
        String sql="select * from ${tablename} ";
        String tablename= ModelHelper.getTableName(this.getClass());
        sql= StringUtil.replace(sql,"${tablename}",tablename);
        return sql;
    }