{@inheritDoc}

@see jp.co.future.uroborosql.context.SqlContextFactory#createSqlContext()
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;
	}
1189547
private static JQL buildJQLSelect(final SQLiteModelMethod method, final JQL result, final Map<JQLDynamicStatementType, String> dynamicReplace, String preparedJql) {
		final Class<? extends Annotation> annotation = BindSqlSelect.class;
		final SQLiteDaoDefinition dao = method.getParent();

		if (StringUtils.hasText(preparedJql)) {
			result.value = preparedJql;

			// In SELECT SQL only where statement can contains bind parameter
			JQLChecker.getInstance().analyze(method, result, new JqlBaseListener() {

				@Override
				public void enterBind_dynamic_sql(Bind_dynamic_sqlContext ctx) {
					JQLDynamicStatementType dynamicType = JQLDynamicStatementType.valueOf(ctx.bind_parameter_name().getText().toUpperCase());

					int start = ctx.getStart().getStartIndex() - 1;
					int stop = ctx.getStop().getStopIndex() + 1;

					String dynamicWhere = result.value.substring(start, stop);

					dynamicReplace.put(dynamicType, dynamicWhere);
				}
			});

			JQLChecker.getInstance().replaceVariableStatements(method, preparedJql, new JQLReplaceVariableStatementListenerImpl() {

				@Override
				public String onWhere(String statement) {
					result.annotatedWhere = true;
					result.staticWhereConditions = true;
					return null;
				}

				@Override
				public String onOrderBy(String statement) {
					result.annotatedOrderBy = true;
					result.staticOrderBy = true;
					return null;
				}

				@Override
				public String onOffset(String statement) {
					result.annotatedOffset = true;
					return null;
				}

				@Override
				public String onLimit(String statement) {
					result.annotatedLimit = true;
					return null;
				}

				@Override
				public String onHaving(String statement) {
					result.annotatedHaving = true;
					return null;
				}

				@Override
				public String onGroup(String statement) {
					result.annotatedGroupBy = true;
					return null;
				}

			});

			forEachParameter(method, new OnMethodParameterListener() {

				@Override
				public void onMethodParameter(VariableElement methodParam) {
					if (methodParam.getAnnotation(BindSqlDynamicOrderBy.class) != null) {
						String orderDynamicName = methodParam.getSimpleName().toString();

						result.paramOrderBy = orderDynamicName;

						// CONSTRAINT: @BindSqlOrderBy can be used only on
						// String
						// parameter type
						AssertKripton.assertTrueOrInvalidTypeForAnnotationMethodParameterException(TypeUtility.isEquals(TypeUtility.typeName(String.class), TypeUtility.typeName(methodParam)),
								method.getParent().getElement(), method.getElement(), methodParam, BindSqlDynamicOrderBy.class);
					}

				}
			});

		} else {
			// extract some informaction from method and bean
			// use annotation's attribute value and exclude and bean definition
			// to
			// define field list
			final Set<String> fields = extractFieldsFromAnnotation(method, BindSqlSelect.class, true);

			boolean distinct = AnnotationUtility.extractAsBoolean(method.getElement(), annotation, AnnotationAttributeType.DISTINCT);
			String annotatedGroupBy = AnnotationUtility.extractAsString(method.getElement(), annotation, AnnotationAttributeType.GROUP_BY);
			String annotatedHaving = AnnotationUtility.extractAsString(method.getElement(), annotation, AnnotationAttributeType.HAVING);

			StringBuilder builder = new StringBuilder();
			builder.append(SELECT_KEYWORD + " ");

			//
			if (distinct) {
				builder.append(DISTINCT_KEYWORD + " ");
			}

			// recreate fields
			builder.append(forEachFields(fields, new OnFieldListener() {

				@Override
				public String onField(String item) {
					return item;
				}
			}));

			// entity name
			builder.append(" " + FROM_KEYWORD + " " + dao.getEntitySimplyClassName());

			// where
			builder.append(defineWhereStatement(method, result, annotation, dynamicReplace));

			// group by
			if (StringUtils.hasText(annotatedGroupBy)) {
				result.annotatedGroupBy = true;
				builder.append(" " + GROUP_BY_KEYWORD + " " + annotatedGroupBy);
			}

			// having
			if (StringUtils.hasText(annotatedHaving)) {
				result.annotatedHaving = true;
				builder.append(" " + HAVING_KEYWORD + " " + annotatedHaving);
			}

			// order by
			builder.append(defineOrderByStatement(method, result, annotation, dynamicReplace));

			// limit
			builder.append(defineLimitStatement(method, result, annotation, dynamicReplace));

			result.value = builder.toString();

		}

		result.value = JQLChecker.getInstance().replace(method, result.value, new JQLReplacerListenerImpl(method, true) {

			@Override
			public String onBindParameter(String bindParameterName, boolean inStatement) {
				if (inStatement) {
					TypeName typeName = method.findParameterType(method.findParameterNameByAlias(bindParameterName));

					AssertKripton.assertTrueOrInvalidMethodSignException(typeName != null && (TypeUtility.isArray(typeName) || TypeUtility.isCollection(typeName)), method,
							"'in' condition need an array or collection parameter");

					String dynamicSpread = bindParameterName;

					dynamicReplace.put(JQLDynamicStatementType.DYNAMIC_SPREAD, dynamicSpread);
					result.spreadParams.add(dynamicSpread);

					// return
					// "#{"+JQLDynamicStatementType.DYNAMIC_SPREAD+"}";
					return null;
				}

				return null;
			}
		});
		
		if (method.isPagedLiveData()) {
			// if is a paged live data, it must have pagination
			dynamicReplace.put(JQLDynamicStatementType.DYNAMIC_PAGE_OFFSET, "");
			dynamicReplace.put(JQLDynamicStatementType.DYNAMIC_PAGE_SIZE, "");			
		}

		result.operationType = JQLType.SELECT;
		result.dynamicReplace = dynamicReplace;
		return result;
	}
853543
protected <T> CharSequence createSQLJoin(final Function<Class, EntityInfo> func, final boolean update, final Map<Class, String> joinTabalis, final Set<String> haset, final EntityInfo<T> info) {
        if (joinTabalis == null || this.nodes == null) return null;
        StringBuilder sb = null;
        for (FilterNode node : this.nodes) {
            CharSequence cs = node.createSQLJoin(func, update, joinTabalis, haset, info);
            if (cs == null) continue;
            if (sb == null) sb = new StringBuilder();
            sb.append(cs);
        }
        return sb;
    }
482206
private void createIfNotExists(String tableName, String createTableStatement) throws SQLException {
		logger.entering(CLASSNAME, "createIfNotExists", new Object[] {tableName, createTableStatement});

		Connection conn = getConnection();
		DatabaseMetaData dbmd = conn.getMetaData();
		ResultSet rs = dbmd.getTables(null, schema, tableName, null);
		PreparedStatement ps = null;
		if(!rs.next()) {
			logger.log(Level.INFO, tableName + " table does not exists. Trying to create it.");
			ps = conn.prepareStatement(createTableStatement);
			ps.executeUpdate();
		}

		cleanupConnection(conn, rs, ps);
		logger.exiting(CLASSNAME, "createIfNotExists");
	}
1006746
@Override
  public Statement createStatement() throws SQLException
  {
    raiseSQLExceptionIfConnectionIsClosed();
    Statement stmt = createStatement(
        ResultSet.TYPE_FORWARD_ONLY,
        ResultSet.CONCUR_READ_ONLY);
    openStatements.add(stmt);
    return stmt;
  }
1303119
private String createSQLStatement(final OneSelect _parentOnesel)
        throws EFapsException
    {
        final Attribute attr = this.type.getAttribute(this.attrName);

        if (attr == null) {
            LinkFromSelect.LOG.error("Could not find Attribute '{}' in Type '{}'", this.attrName, this.type.getName());
            throw new EFapsException(LinkFromSelect.class, "NoAttribute");
        }

        final SQLSelect select = new SQLSelect()
                .column(0, "ID")
                .column(0, attr.getSqlColNames().get(0))
                .from(this.type.getMainTable().getSqlTable(), 0);

        // on a from  select only one table is the base
        getAllSelects().get(0).append2SQLFrom(select);

        int colIndex = select.getColumns().size() + 1;

        for (final OneSelect oneSel : getAllSelects()) {
            colIndex += oneSel.append2SQLSelect(select, colIndex);
        }
        select.addPart(SQLPart.WHERE)
            .addColumnPart(0, attr.getSqlColNames().get(0))
            .addPart(SQLPart.IN).addPart(SQLPart.PARENTHESIS_OPEN);

        if (_parentOnesel.isMultiple()) {
            boolean first = true;
            final List<?> ids = (List<?>) _parentOnesel.getObject();
            for (final Object id : ids) {
                if (first) {
                    first = false;
                } else {
                    select.addPart(SQLPart.COMMA);
                }
                select.addValuePart(id);
            }
        } else {
            select.addValuePart(_parentOnesel.getObject());
        }
        select.addPart(SQLPart.PARENTHESIS_CLOSE);

        _parentOnesel.setValueSelect(null);

        // in a subquery the type must also be set
        if (this.type.getMainTable().getSqlColType() != null) {
            select.addPart(SQLPart.AND)
                .addColumnPart(0, this.type.getMainTable().getSqlColType())
                .addPart(SQLPart.IN).addPart(SQLPart.PARENTHESIS_OPEN);
            boolean first = true;
            if (this.type.isAbstract()) {
                for (final Type atype : getAllChildTypes(this.type)) {
                    if (first) {
                        first = false;
                    } else {
                        select.addPart(SQLPart.COMMA);
                    }
                    select.addValuePart(atype.getId());
                }
                if (first) {
                    LinkFromSelect.LOG.error("The type is declared abstract but does not have children: {}", this.type);
                }
            } else {
                select.addValuePart(this.type.getId());
            }
            select.addPart(SQLPart.PARENTHESIS_CLOSE);
        }

        for (final OneSelect oneSel : getAllSelects()) {
            oneSel.append2SQLWhere(select);
        }
        return select.getSQL();
    }
86381
String createDeleteAllPreparedSQLStatement() {

        final StringGrabber sgSQL = new StringGrabber();

        // Get the table name
        final DBTable table = mModelClazz.getAnnotation(DBTable.class);
        final String tableName = table.tableName();

        sgSQL.append("DELETE FROM " + tableName);

        return sgSQL.toString();
    }
1057667
private static PreparedStatement createStatementForInsert(final Connection connection,
                                                             final Introspected introspected,
                                                             final FieldColumnInfo[] fcInfos) throws SQLException
   {
      final String sql = createStatementCache.computeIfAbsent(introspected, key -> {
         final String tableName = introspected.getTableName();
         final StringBuilder sqlSB = new StringBuilder("INSERT INTO ").append(tableName).append('(');
         final StringBuilder sqlValues = new StringBuilder(") VALUES (");

         for (final FieldColumnInfo fcInfo : fcInfos) {
            sqlSB.append(fcInfo.getDelimitedColumnName()).append(',');
            sqlValues.append("?,");
         }

         sqlValues.deleteCharAt(sqlValues.length() - 1);
         sqlSB.deleteCharAt(sqlSB.length() - 1).append(sqlValues).append(')');

         return sqlSB.toString();
      });

      if (introspected.hasGeneratedId()) {
         return connection.prepareStatement(sql, introspected.getIdColumnNames());
      }
      else {
         return connection.prepareStatement(sql);
      }
   }
115899
@Override
    public PojoQueryContext createPojoQueryContext(Executor executor) {
        return new DefaultPojoQueryContext(session, statementFactory, maximumCacheSize, executor);
    }
999075
protected String createSQLStatement()
        throws EFapsException
    {

        final SQLSelect select = new SQLSelect()
                        .column(0, "ID")
                        .from(getMainType().getMainTable().getSqlTable(), 0);
        for (final OneSelect oneSel : this.allSelects) {
            oneSel.append2SQLFrom(select);
        }

        int colIndex = select.getColumns().size() + 1;
        // if the main table has a column for the type it is selected also
        if (getMainType().getMainTable().getSqlColType() != null) {
            select.column(0, getMainType().getMainTable().getSqlColType());
            this.typeColumnIndex = colIndex;
            colIndex++;
        }

        for (final OneSelect onesel : this.allSelects) {
            if (onesel.getValueSelect() != null) {
                colIndex += onesel.append2SQLSelect(select, colIndex);
            }
        }

        select.addPart(SQLPart.WHERE).addColumnPart(0, "ID").addPart(SQLPart.IN).addPart(SQLPart.PARENTHESIS_OPEN);

        int i = 0;
        for (final Instance instance : getInstanceList()) {
            if (Context.getDbType().getMaxExpressions() > -1 && i > Context.getDbType().getMaxExpressions()) {
                select.addPart(SQLPart.PARENTHESIS_CLOSE)
                                .addPart(SQLPart.OR)
                                .addColumnPart(0, "ID").addPart(SQLPart.IN).addPart(SQLPart.PARENTHESIS_OPEN);
                i = 0;
            }
            if (i > 0) {
                select.addPart(SQLPart.COMMA);
            }
            select.addValuePart(instance.getId());
            i++;
        }
        select.addPart(SQLPart.PARENTHESIS_CLOSE);

        for (final OneSelect oneSel : this.allSelects) {
            oneSel.append2SQLWhere(select);
        }

        return select.getSQL();
    }
1104936
private void createDBTable(Connection conn) throws SQLException {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "createDBTable", new java.lang.Object[] { conn, this });

        Statement createTableStmt = null;
        PreparedStatement specStatement = null;

        try {
            createTableStmt = conn.createStatement();

            if (_isOracle) {
                String oracleFullTableName = _recoveryTableName + _logIdentifierString + _recoveryTableNameSuffix;
                String oracleTableString = oracleTablePreString + oracleFullTableName + oracleTablePostString;
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "Create Oracle Table using: " + oracleTableString);

                String oracleIndexString = indexPreString + _recoveryIndexName + _logIdentifierString + _recoveryTableNameSuffix +
                                           " ON " + oracleFullTableName + indexPostString;

                if (tc.isDebugEnabled())
                    Tr.debug(tc, "Create Oracle Index using: " + oracleIndexString);
                // Create the Oracle table
                createTableStmt.executeUpdate(oracleTableString);
                // Create index on the new table
                createTableStmt.executeUpdate(oracleIndexString);
            } else {
                String db2FullTableName = _recoveryTableName + _logIdentifierString + _recoveryTableNameSuffix;
                String db2TableString = db2TablePreString + db2FullTableName + db2TablePostString;
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "Create DB2 Table using: " + db2TableString);

                String db2IndexString = indexPreString + _recoveryIndexName + _logIdentifierString + _recoveryTableNameSuffix +
                                        " ON " + db2FullTableName + indexPostString;
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "Create DB2 Index using: " + db2IndexString);
                // Create the DB2 table
                createTableStmt.executeUpdate(db2TableString);
                // Create index on the new table
                createTableStmt.executeUpdate(db2IndexString);
            }

            short serviceId = (short) _recoveryAgent.clientIdentifier();
            String insertString = "INSERT INTO " +
                                  _recoveryTableName + _logIdentifierString + _recoveryTableNameSuffix +
                                  " (SERVER_NAME, SERVICE_ID, RU_ID, RUSECTION_ID, RUSECTION_DATA_INDEX, DATA)" +
                                  " VALUES (?,?,?,?,?,?)";
            if (tc.isDebugEnabled())
                Tr.debug(tc, "Have created the table, insert special HA LOCKING row using - " + insertString);

            specStatement = conn.prepareStatement(insertString);
            specStatement.setString(1, _currentProcessServerName);
            specStatement.setShort(2, serviceId);
            specStatement.setLong(3, -1); // NOTE RU_ID SET TO -1
            specStatement.setLong(4, 1);
            specStatement.setShort(5, (short) 1);
            byte buf[] = new byte[2];
            specStatement.setBytes(6, buf);
            int ret = specStatement.executeUpdate();
            if (tc.isDebugEnabled())
                Tr.debug(tc, "Have inserted HA LOCKING ROW with return: " + ret);

        } finally {
            if (createTableStmt != null && !createTableStmt.isClosed()) {
                createTableStmt.close();
            }
            if (specStatement != null && !specStatement.isClosed()) {
                specStatement.close();
            }
        }

        if (tc.isEntryEnabled())
            Tr.exit(tc, "createDBTable");
    }
204586
private static JQL buildJQLDelete(SQLiteModelMethod method, final JQL result, final Map<JQLDynamicStatementType, String> dynamicReplace, String preparedJql) {
		final SQLiteDaoDefinition dao = method.getParent();

		if (StringUtils.hasText(preparedJql)) {
			// in DELETE SQL only where statement can contains bind parameter
			result.value = preparedJql;

			JQLChecker.getInstance().analyze(method, result, new JqlBaseListener() {

				@Override
				public void enterBind_parameter(Bind_parameterContext ctx) {
					result.bindParameterOnWhereStatementCounter++;
				}

				@Override
				public void enterBind_dynamic_sql(Bind_dynamic_sqlContext ctx) {
					JQLDynamicStatementType dynamicType = JQLDynamicStatementType.valueOf(ctx.bind_parameter_name().getText().toUpperCase());

					int start = ctx.getStart().getStartIndex() - 1;
					int stop = ctx.getStop().getStopIndex() + 1;

					String dynamicWhere = result.value.substring(start, stop);

					dynamicReplace.put(dynamicType, dynamicWhere);
				}
			});

			// where management
			JQLChecker.getInstance().replaceVariableStatements(method, preparedJql, new JQLReplaceVariableStatementListenerImpl() {

				@Override
				public String onWhere(String statement) {
					result.annotatedWhere = true;
					result.staticWhereConditions = true;
					return null;
				}
			});

		} else {
			StringBuilder builder = new StringBuilder();
			builder.append(DELETE_KEYWORD + " " + FROM_KEYWORD);
			// entity name
			builder.append(" " + dao.getEntitySimplyClassName());

			builder.append(defineWhereStatement(method, result, BindSqlDelete.class, dynamicReplace));

			result.value = builder.toString();
		}
		result.operationType = JQLType.DELETE;
		result.dynamicReplace = dynamicReplace;
		return result;
	}
904234
public static void generateSQLForStaticQuery(final SQLiteModelMethod method, MethodSpec.Builder methodBuilder) {
		methodBuilder.addComment("generate static SQL for statement");
		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 onColumnNameToUpdate(String columnName) {
				return onColumnName(columnName);
			}

			@Override
			public String onColumnName(String columnName) {
				SQLProperty tempProperty = method.getEntity().get(columnName);

				AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);

				return tempProperty.columnName;
			}

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

		methodBuilder.addStatement("String _sql=$S", sql);
	}
400654
public void createDB() throws PlatformException
    {
        if (_creationScript == null)
        {
            createCreationScript();
        }

        Project             project    = new Project();
        TorqueDataModelTask modelTask  = new TorqueDataModelTask();
        File                tmpDir     = null;
        File                scriptFile = null;
        
        try
        {
            tmpDir = new File(getWorkDir(), "schemas");
            tmpDir.mkdir();

            scriptFile = new File(tmpDir, CREATION_SCRIPT_NAME);

            writeCompressedText(scriptFile, _creationScript);

            project.setBasedir(tmpDir.getAbsolutePath());

            // we use the ant task 'sql' to perform the creation script
	        SQLExec         sqlTask = new SQLExec();
	        SQLExec.OnError onError = new SQLExec.OnError();
	
	        onError.setValue("continue");
	        sqlTask.setProject(project);
	        sqlTask.setAutocommit(true);
	        sqlTask.setDriver(_jcd.getDriver());
	        sqlTask.setOnerror(onError);
	        sqlTask.setUserid(_jcd.getUserName());
	        sqlTask.setPassword(_jcd.getPassWord() == null ? "" : _jcd.getPassWord());
	        sqlTask.setUrl(getDBCreationUrl());
	        sqlTask.setSrc(scriptFile);
	        sqlTask.execute();

	        deleteDir(tmpDir);
        }
        catch (Exception ex)
        {
            // clean-up
            if ((tmpDir != null) && tmpDir.exists())
            {
                try
                {
                    scriptFile.delete();
                }
                catch (NullPointerException e) 
                {
                    LoggerFactory.getLogger(this.getClass()).error("NPE While deleting scriptFile [" + scriptFile.getName() + "]", e);
                }
            }
            throw new PlatformException(ex);
        }
    }
518769
public DataSource createDataSource(Properties props) throws SQLException {
    props = new SingleUseProperties(props);
    if (props.containsKey(JDBC_INITIAL_POOL_SIZE)
        || props.containsKey(JDBC_MIN_POOL_SIZE)
        || props.containsKey(JDBC_MAX_POOL_SIZE)
        || props.containsKey(JDBC_MAX_IDLE_TIME)
        || props.containsKey(JDBC_MAX_STATEMENTS)) {
      return createPoolingDataSource(props);
    } else {
      return createSimpleDataSource(props);
    }
  }
355249
public SqlSource createSqlSource(MappedStatement ms, String xmlSql) {
        return languageDriver.createSqlSource(ms.getConfiguration(), "<script>\n\t" + xmlSql + "</script>", null);
    }
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();
	}