DB接続情報を指定してSqlConfigを取得する

@param url JDBC接続URL
@param user JDBC接続ユーザ
@param password JDBC接続パスワード
@param schema JDBCスキーマ名
@param autoCommit 自動コミットするかどうか. 自動コミットの場合<code>true</code>
@param readOnly 参照のみかどうか. 参照のみの場合<code>true</code>
@return SqlConfigオブジェクト
771742
public static SqlConfig getConfig(final String url, final String user, final String password, final String schema,
			final boolean autoCommit, final boolean readOnly) {
		return new DefaultSqlConfig(new JdbcConnectionSupplierImpl(url, user, password, schema, autoCommit, readOnly),
				null);
	}
859031
private static ObjectSchema readSchema(String url, String user, String pass,
            SyntaxToJavaClass syntaxToJavaClass, Set<String> binarySet, Set<String> objectClasses) 
        throws NamingException, ClassNotFoundException {
        
        // Set up environment 
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.PROVIDER_URL, url);
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        if (user != null) {
            env.put(Context.SECURITY_PRINCIPAL, user);
        }
        if (pass != null) {
            env.put(Context.SECURITY_CREDENTIALS, pass);
        }

        DirContext context = new InitialDirContext(env);
        DirContext schemaContext = context.getSchema("");
        SchemaReader reader = new SchemaReader(schemaContext, syntaxToJavaClass, binarySet);
        ObjectSchema schema = reader.getObjectSchema(objectClasses);
        
        if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Schema - %1$s", schema.toString()));
        }
        
        return schema;  
    }
41715
public static DBCleanerTool getWorkspaceDBCleaner(Connection jdbcConn, WorkspaceEntry wsEntry) throws DBCleanException
   {
      SecurityHelper.validateSecurityPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION);

      String dialect = resolveDialect(jdbcConn, wsEntry);
      boolean autoCommit = dialect.startsWith(DialectConstants.DB_DIALECT_SYBASE);
      
      DBCleaningScripts scripts = DBCleaningScriptsFactory.prepareScripts(dialect, wsEntry);

      return new DBCleanerTool(jdbcConn, autoCommit, scripts.getCleaningScripts(), scripts.getCommittingScripts(),
         scripts.getRollbackingScripts());
   }
901266
public static String getSelectSQL(Class<?> clazz, boolean selectOnlyKey, boolean withSQL_CALC_FOUND_ROWS) {
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT ");
		if(withSQL_CALC_FOUND_ROWS) {
			sql.append("SQL_CALC_FOUND_ROWS ");
		}
		
		// 处理join方式clazz
		JoinTable joinTable = DOInfoReader.getJoinTable(clazz);
		if(joinTable != null) {
			Field leftTableField = DOInfoReader.getJoinLeftTable(clazz);
			Field rightTableField = DOInfoReader.getJoinRightTable(clazz);
			
			JoinLeftTable joinLeftTable = leftTableField.getAnnotation(JoinLeftTable.class);
			JoinRightTable joinRightTable = rightTableField.getAnnotation(JoinRightTable.class);
			
	        Table table1 = DOInfoReader.getTable(leftTableField.getType());
	        List<Field> fields1 = DOInfoReader.getColumnsForSelect(leftTableField.getType(), selectOnlyKey);
			
	        Table table2 = DOInfoReader.getTable(rightTableField.getType());
	        List<Field> fields2 = DOInfoReader.getColumnsForSelect(rightTableField.getType(), selectOnlyKey);
	        
	        sql.append(join(fields1, ",", joinLeftTable.alias() + "."));
	        sql.append(",");
	        sql.append(join(fields2, ",", joinRightTable.alias() + "."));
	        sql.append(" FROM ").append(getTableName(table1))
	           .append(" ").append(joinLeftTable.alias()).append(" ");
	        sql.append(joinTable.joinType().getCode()).append(" ");
	        sql.append(getTableName(table2)).append(" ").append(joinRightTable.alias());
	        if(joinTable.on() == null || joinTable.on().trim().isEmpty()) {
	        	throw new OnConditionIsNeedException("join table :" + clazz.getName());
	        }
	        sql.append(" on ").append(joinTable.on().trim());
	        
		} else {
			Table table = DOInfoReader.getTable(clazz);
			List<Field> fields = DOInfoReader.getColumnsForSelect(clazz, selectOnlyKey);
			
			sql.append(join(fields, ","));
			sql.append(" FROM ").append(getTableName(table)).append(" ").append(table.alias());
		}
		
		return sql.toString();
	}
1104689
protected SqlStringFilter createSqlStringFilter(ActionRuntime runtime) {
        final Method actionMethod = runtime.getExecuteMethod();
        return newRomanticTraceableSqlStringFilter(actionMethod, () -> {
            return buildSqlMarkingAdditionalInfo(); // lazy because it may be auto-login later
        });
    }
765691
public void doOpen() throws DBException
    {
        try   {
    // FROM is automatic, since the remote BaseRecord is exactly the same as this one
    // ORDER BY
            KeyArea keyArea = this.getRecord().getKeyArea(-1);  // Current index
            String strKeyArea = null;
            boolean bDirection = DBConstants.ASCENDING;
            if (true)
            {
                strKeyArea = keyArea.getKeyName();
                bDirection = keyArea.getKeyField(DBConstants.MAIN_KEY_FIELD).getKeyOrder();
            }
            m_bDirectionCurrent = bDirection;
    // Open mode
            int iOpenMode = this.getRecord().getOpenMode();
    // SELECT (fields to select)
            String strFields = null;
            if (true) // All selected?
            {
                strFields = this.getRecord().getSQLFields(DBConstants.SQL_SELECT_TYPE, true);
                if (strFields.equals(" *"))
                    strFields = null; // Select all
            }
    // WHERE XYZ >=
            Object objInitialKey = null;
            if (true)
            {
                BaseBuffer buffer = new VectorBuffer(null);
                this.getRecord().handleInitialKey();
                if (keyArea.isModified(DBConstants.START_SELECT_KEY))
                {   // Anything set?
                    keyArea.setupKeyBuffer(buffer, DBConstants.START_SELECT_KEY, false);
                    objInitialKey = buffer.getPhysicalData();
                    buffer.addNextString(Integer.toString(keyArea.lastModified(DBConstants.START_SELECT_KEY, false))); // Largest modified field.
                }
            }
    // WHERE XYZ <=
            Object objEndKey = null;
            if (true)
            {
                BaseBuffer buffer = new VectorBuffer(null);
                this.getRecord().handleEndKey();
                if (keyArea.isModified(DBConstants.END_SELECT_KEY))
                {   // Anything set?
                    keyArea.setupKeyBuffer(buffer, DBConstants.END_SELECT_KEY, false);
                    objEndKey = buffer.getPhysicalData();
                    buffer.addNextString(Integer.toString(keyArea.lastModified(DBConstants.END_SELECT_KEY, false))); // Largest modified field.
                }
            }
    // WHERE XYZ
            byte[] byBehaviorData = null;
            boolean bDirty = false;
            if (this.getRecord().getListener() != null)
            {
                ByteArrayOutputStream baOut = new ByteArrayOutputStream();
                ObjectOutputStream daOut = new ObjectOutputStream(baOut);
                FileListener listener = (FileListener)this.getRecord().getListener();
                while (listener != null)
                {
                    if ((listener.getMasterSlaveFlag() & FileListener.RUN_IN_SLAVE) != 0) // Should exist in a SERVER environment
                        if ((listener.getMasterSlaveFlag() & FileListener.DONT_REPLICATE_TO_SLAVE) == 0) // Yes, replicate to the SERVER environment
                            if (listener.isEnabledListener()) // Yes, only replicate enabled listeners.
                    { // There should be a copy of this on the server
                        bDirty = true;
                        daOut.writeUTF(listener.getClass().getName());
                        listener.initRemoteStub(daOut);
                    }
                    listener = (FileListener)listener.getNextListener();
                }
                daOut.flush();
                if (bDirty)
                    byBehaviorData = baOut.toByteArray();
                daOut.close();
                baOut.close();
            }

            this.checkCacheMode(Boolean.TRUE);      // Make sure the cache is set up correctly for this type of query (typically needed)

            synchronized (this.getSyncObject())
            {   // In case this is called from another task
                m_tableRemote.open(strKeyArea, iOpenMode, bDirection, strFields, objInitialKey, objEndKey, byBehaviorData);
            }
        } catch (Exception ex) {
            throw DatabaseException.toDatabaseException(ex);
        }
    }
61747
public boolean getAutoCommit() throws SQLException {
        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("select @@autocommit");
        rs.next();
        boolean autocommit = rs.getBoolean(1);
        rs.close();
        stmt.close();
        return autocommit;
    }
1322513
public static SqlConfig getConfig(final String dataSourceName, final boolean autoCommit, final boolean readOnly,
			final int transactionIsolation) {
		DataSourceConnectionSupplierImpl connectionSupplier = new DataSourceConnectionSupplierImpl(dataSourceName);
		connectionSupplier.setDefaultAutoCommit(autoCommit);
		connectionSupplier.setDefaultReadOnly(readOnly);
		connectionSupplier.setDefaultTransactionIsolation(transactionIsolation);
		return new DefaultSqlConfig(connectionSupplier, null);
	}
136707
public void checkValueStorage(boolean autoRepair)
   {
      SecurityHelper.validateSecurityPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION);

      Connection connection = null;
      PreparedStatement st = null;
      ResultSet resultSet = null;
      try
      {
         connection = jdbcDataContainer.getConnectionFactory().getJdbcConnection();
         st = connection.prepareStatement(vsInspectionQuery.getStatement());
         resultSet = st.executeQuery();

         if (resultSet.next())
         {
            logDescription("ValueData not found inconsistency");

            do
            {
               String storageDesc = resultSet.getString(DBConstants.COLUMN_VSTORAGE_DESC);

               ValueIOChannel channel = null;
               try
               {
                  channel = getIOChannel(storageDesc);
                  doCheckAndRepairValueData(channel, resultSet, autoRepair);
               }
               catch (IOException e)
               {
                  logExceptionAndSetInconsistency("Unexpected exception during checking.", e);
               }
               catch (SQLException e)
               {
                  logExceptionAndSetInconsistency("Unexpected exception during checking.", e);
               }
               finally
               {
                  if (channel != null)
                  {
                     channel.close();
                  }
               }
            }
            while (resultSet.next());
         }
      }
      catch (SQLException e)
      {
         logExceptionAndSetInconsistency("Unexpected exception during checking.", e);
      }
      catch (RepositoryException e)
      {
         logExceptionAndSetInconsistency("Unexpected exception during checking.", e);
      }
      finally
      {
         JDBCUtils.freeResources(resultSet, st, connection);
      }
   }
516131
public String readOnlyTransaction(long singerId, long albumId) {
    // [START readOnlyTransaction]
    String singerColumn = "FirstName";
    String albumColumn = "AlbumTitle";
    String albumTitle = null;
    // ReadOnlyTransaction should be closed to prevent resource leak.
    try (ReadOnlyTransaction txn = dbClient.readOnlyTransaction()) {
      Struct singerRow =
          txn.readRow("Singers", Key.of(singerId), Collections.singleton(singerColumn));
      Struct albumRow =
          txn.readRow("Albums", Key.of(singerId, albumId), Collections.singleton(albumColumn));
      singerRow.getString(singerColumn);
      albumTitle = albumRow.getString(albumColumn);
    }
    // [END readOnlyTransaction]
    return albumTitle;
  }
577536
static boolean closeQuietlyIfAutoCommit(Connection connection) {
        try {
            if (connection != null && !connection.isClosed() && connection.getAutoCommit()) {
                closeQuietly(connection);
                return true;
            } else
                return false;
        } catch (SQLException e) {
            throw new SQLRuntimeException(e);
        }
    }
575579
public String getCreateUserSQL() {

        StringBuffer sb = new StringBuffer(64);

        sb.append(Tokens.T_CREATE).append(' ');
        sb.append(Tokens.T_USER).append(' ');
        sb.append(getStatementName()).append(' ');
        sb.append(Tokens.T_PASSWORD).append(' ');
        sb.append(StringConverter.toQuotedString(password, '"', true));

        return sb.toString();
    }
744487
private String processSchemaName(String dbProductName, String userName, String schemaName) {
        String result = null;

        if (schemaName != null) {
            result = schemaName.toUpperCase();
        } else {
            if ("DB2".equals(dbProductName) == true || "Apache Derby".equals(dbProductName) == true || "Oracle".equals(dbProductName) == true) {
                if (userName != null) {
                    result = userName.toUpperCase();
                }
            } else if ("PostgreSQL".equals(dbProductName) == true) {
                // for PostgreSQL - if no schema specified - public should be used
                result = "public";
            }
        }

        return result;
    }
46654
private UserAndPassword executeStatementToUser(PreparedStatement preparedStmt) throws Exception {
		if( preparedStmt.execute() ) {
			// There's a ResultSet to be had
			ResultSet rs = preparedStmt.getResultSet();
			ResultSetMetaData rsmd = rs.getMetaData();

			int numColumns = rsmd.getColumnCount();
			if( numColumns != 5 ) {
				throw new Exception("Unexpected number of columns returned");
			}
			
			if( false == rs.next() ) {
				throw new Exception("Result set empty");
			}

			int userId = JdbcUtils.extractIntResult(rs,rsmd,1);
			String email = JdbcUtils.extractStringResult(rs,rsmd,2);
			String displayName = JdbcUtils.extractStringResult(rs,rsmd,3);
			String dbPassword = JdbcUtils.extractStringResult(rs,rsmd,4);
			int groupId = JdbcUtils.extractIntResult(rs,rsmd,5);

			if( true == rs.next() ) {
				throw new Exception("Result set had more than one result");
			}
			
			// Return user
			UserAndPassword user = new UserAndPassword();
			user.setId(userId);
			user.setUser(email);
			user.setDisplayName(displayName);
			user.setPassword(dbPassword);
			if( 0 == groupId ) {
				user.setAnonymous(true);
			} else if( 1 == groupId ) {
				user.setAdmin(true);
			}
			Vector<Integer> groups = new Vector<Integer>();
			groups.add( new Integer(groupId) );
			user.setGroups(groups);
			return user;
			
		} else {
			// indicates an update count or no results - this must be no results
			throw new Exception("Query returned no results");
		}
	}
1295032
public final T execute()
   {
      boolean txOwner = !TransactionElf.hasTransactionManager() || TransactionElf.beginOrJoinTransaction();
      Connection connection = null;
      try {
         connection = ConnectionProxy.wrapConnection(dataSource.getConnection());
         if (txOwner) {
            // disable autoCommit mode as we are going to handle transaction by ourselves
            connection.setAutoCommit(false);
         }
         return (args == null)
            ? execute(connection)
            : execute(connection, args);
      }
      catch (SQLException e) {
         if (e.getNextException() != null) {
            e = e.getNextException();
         }
         if (txOwner) {
            // set the txOwner to false as we no longer own the transaction and we shouldn't try to commit it later
            txOwner = false;
            rollback(connection);
         }
         throw new RuntimeException(e);
      } catch (Throwable e) {
         if (txOwner) {
            txOwner = false;
            rollback(connection);
         }
         throw e;
      }
      finally {
         try {
            if (txOwner) {
               commit(connection);
            }
         }
         finally {
            quietClose(connection);
         }
      }
   }
1334838
@Override
    public void setReadOnly(boolean readOnly) throws SQLException
    {
        checkClosed();
        if (!Boolean.parseBoolean(props.getProperty("enableSetReadOnly","false"))){
            throw SQLError.noSupport();
        }
    }
790105
@Local
    @Override
    public <V> V directQuery(String sql, Function<ResultSet, V> handler) {
        final Connection conn = readPool.poll();
        try {
            if (logger.isLoggable(Level.FINEST)) logger.finest("direct query sql=" + sql);
            conn.setReadOnly(true);
            final Statement statement = conn.createStatement();
            //final PreparedStatement statement = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            final ResultSet set = statement.executeQuery(sql);// ps.executeQuery();
            V rs = handler.apply(set);
            set.close();
            statement.close();
            return rs;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            if (conn != null) readPool.offerConnection(conn);
        }
    }