Java Code Examples for java.sql.Connection#setSchema()

The following examples show how to use java.sql.Connection#setSchema() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: calcite-avatica   File: JdbcMeta.java    License: Apache License 2.0 6 votes vote down vote up
protected void apply(Connection conn, ConnectionProperties connProps)
    throws SQLException {
  if (connProps.isAutoCommit() != null) {
    conn.setAutoCommit(connProps.isAutoCommit());
  }
  if (connProps.isReadOnly() != null) {
    conn.setReadOnly(connProps.isReadOnly());
  }
  if (connProps.getTransactionIsolation() != null) {
    conn.setTransactionIsolation(connProps.getTransactionIsolation());
  }
  if (connProps.getCatalog() != null) {
    conn.setCatalog(connProps.getCatalog());
  }
  if (connProps.getSchema() != null) {
    conn.setSchema(connProps.getSchema());
  }
}
 
Example 2
/**
 * Determine whether there are currently thread-bound credentials,
 * using them if available, falling back to the statically specified
 * username and password (i.e. values of the bean properties) otherwise.
 * <p>Delegates to {@link #doGetConnection(String, String)} with the
 * determined credentials as parameters.
 * @see #doGetConnection
 */
@Override
public Connection getConnection() throws SQLException {
	JdbcUserCredentials threadCredentials = this.threadBoundCredentials.get();
	Connection con = (threadCredentials != null ?
			doGetConnection(threadCredentials.username, threadCredentials.password) :
			doGetConnection(this.username, this.password));

	if (this.catalog != null) {
		con.setCatalog(this.catalog);
	}
	if (this.schema != null) {
		con.setSchema(this.schema);
	}
	return con;
}
 
Example 3
/**
 * Determine whether there are currently thread-bound credentials,
 * using them if available, falling back to the statically specified
 * username and password (i.e. values of the bean properties) otherwise.
 * <p>Delegates to {@link #doGetConnection(String, String)} with the
 * determined credentials as parameters.
 * @see #doGetConnection
 */
@Override
public Connection getConnection() throws SQLException {
	JdbcUserCredentials threadCredentials = this.threadBoundCredentials.get();
	Connection con = (threadCredentials != null ?
			doGetConnection(threadCredentials.username, threadCredentials.password) :
			doGetConnection(this.username, this.password));

	if (this.catalog != null) {
		con.setCatalog(this.catalog);
	}
	if (this.schema != null) {
		con.setSchema(this.schema);
	}
	return con;
}
 
Example 4
/**
 * Determine whether there are currently thread-bound credentials,
 * using them if available, falling back to the statically specified
 * username and password (i.e. values of the bean properties) else.
 * <p>Delegates to {@link #doGetConnection(String, String)} with the
 * determined credentials as parameters.
 */
@Override
@UsesJava7
public Connection getConnection() throws SQLException {
	JdbcUserCredentials threadCredentials = this.threadBoundCredentials.get();
	Connection con = (threadCredentials != null ?
			doGetConnection(threadCredentials.username, threadCredentials.password) :
			doGetConnection(this.username, this.password));

	if (this.catalog != null) {
		con.setCatalog(this.catalog);
	}
	if (this.schema != null) {
		con.setSchema(this.schema);
	}
	return con;
}
 
Example 5
/**
 * Build properties for the Driver, including the given username and password (if any),
 * and obtain a corresponding Connection.
 * @param username the name of the user
 * @param password the password to use
 * @return the obtained Connection
 * @throws SQLException in case of failure
 * @see java.sql.Driver#connect(String, java.util.Properties)
 */
@UsesJava7
protected Connection getConnectionFromDriver(String username, String password) throws SQLException {
	Properties mergedProps = new Properties();
	Properties connProps = getConnectionProperties();
	if (connProps != null) {
		mergedProps.putAll(connProps);
	}
	if (username != null) {
		mergedProps.setProperty("user", username);
	}
	if (password != null) {
		mergedProps.setProperty("password", password);
	}

	Connection con = getConnectionFromDriver(mergedProps);
	if (this.catalog != null) {
		con.setCatalog(this.catalog);
	}
	if (this.schema != null) {
		con.setSchema(this.schema);
	}
	return con;
}
 
Example 6
Source Project: calcite   File: CalciteAssert.java    License: Apache License 2.0 5 votes vote down vote up
public Connection apply(Connection connection) throws SQLException {
  if (schema != null) {
    CalciteConnection con = connection.unwrap(CalciteConnection.class);
    SchemaPlus rootSchema = con.getRootSchema();
    rootSchema.add(name, schema);
  }
  connection.setSchema(name);
  return connection;
}
 
Example 7
Source Project: presto   File: QueryRewriter.java    License: Apache License 2.0 5 votes vote down vote up
private void trySetConnectionProperties(Query query, Connection connection)
        throws SQLException
{
    // Required for jdbc drivers that do not implement all/some of these functions (eg. impala jdbc driver)
    // For these drivers, set the database default values in the query database
    try {
        connection.setClientInfo("ApplicationName", "verifier-rewrite");
        connection.setCatalog(catalogOverride.orElse(query.getCatalog()));
        connection.setSchema(schemaOverride.orElse(query.getSchema()));
    }
    catch (SQLClientInfoException ignored) {
        // Do nothing
    }
}
 
Example 8
/**
 * Called before execution of every test method in class.
 *
 * @throws Exception If failed.
 */
@Before
public void before() throws Exception {
    TestSQLFunctions.init();

    Connection conn = GridTestUtils.connect(grid(0), null);

    conn.setSchema('"' + GridAbstractTest.DEFAULT_CACHE_NAME + '"');

    stmt = conn.createStatement();
}
 
Example 9
@Before
public void createTables() throws Exception {
    triggerDAO.dropAllTriggers(SCHEMA, "T");
    Connection conn = new TestConnection(DriverManager.getConnection(connectionString, new Properties()));
    conn.setSchema(SCHEMA.toUpperCase());
    methodWatcher.setConnection(conn);
}
 
Example 10
Source Project: quarkus   File: PoolInterceptorsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onConnectionAcquire(Connection connection) {
    try {
        connection.setSchema("INTERCEPTOR");
    } catch (SQLException e) {
        Assertions.fail(e);
    }
}
 
Example 11
Source Project: quarkus   File: PoolInterceptorsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onConnectionAcquire(Connection connection) {
    try {
        connection.setSchema("LOW");
    } catch (SQLException e) {
        Assertions.fail(e);
    }
}
 
Example 12
Source Project: quarkus   File: PoolInterceptorsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onConnectionAcquire(Connection connection) {
    try {
        Assertions.assertEquals("LOW", connection.getSchema());
        connection.setSchema("PRIORITY");
    } catch (SQLException e) {
        Assertions.fail(e);
    }
}
 
Example 13
@Override
public Connection getConnection() throws SQLException {
    Connection conn = super.getConnection();
    conn.setSchema(tenantId);
    LOG.debugv("Set tenant {0} for connection: {1}", tenantId, conn);
    return conn;
}
 
Example 14
@Test(groups = {"unit", "server"})
public void testConnect() {
    CassandraDriver driver = new CassandraDriver();

    try {
        CassandraConfiguration config = CassandraConfiguration.DEFAULT;
        Properties props = new Properties();
        props.setProperty(KEY_USERNAME, config.getUserName());
        props.setProperty(KEY_PASSWORD, config.getPassword());

        Connection conn = driver.connect(config.getConnectionUrl(), props);
        assertTrue(conn instanceof BaseCassandraConnection);
        assertTrue(conn.getClass().getName()
                .endsWith("datastax.CassandraConnection"));

        conn.setSchema("system");
        ResultSet rs = conn.createStatement().executeQuery(
                "select * from peers limit 5");
        while (rs.next()) {
            Logger.debug("{}\n=====", rs.getRow());
            for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
                Object obj = rs.getObject(i);
                Logger.debug("[{}]=[{}]", rs.getMetaData().getColumnName(i),
                        obj == null ? "null" : obj.getClass() + "@" + obj.hashCode());
            }
        }
        rs.close();
        conn.close();
    } catch (Exception e) {
        e.printStackTrace();
        fail("Exception happened during test: " + e.getMessage());
    }
}
 
Example 15
Source Project: snowflake-jdbc   File: ConnectionIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@ConditionalIgnore(condition = RunningOnGithubAction.class)
public void testConnectionGetAndSetDBAndSchema() throws SQLException
{
  Connection con = getConnection();

  final String database = System.getenv("SNOWFLAKE_TEST_DATABASE").toUpperCase();
  final String schema = System.getenv("SNOWFLAKE_TEST_SCHEMA").toUpperCase();

  assertEquals(database, con.getCatalog());
  assertEquals(schema, con.getSchema());

  final String SECOND_DATABASE = "SECOND_DATABASE";
  final String SECOND_SCHEMA = "SECOND_SCHEMA";
  Statement statement = con.createStatement();
  statement.execute(String.format("create or replace database %s", SECOND_DATABASE));
  statement.execute(String.format("create or replace schema %s", SECOND_SCHEMA));
  statement.execute(String.format("use database %s", database));

  // TODO: use the other database and schema
  con.setCatalog(SECOND_DATABASE);
  assertEquals(SECOND_DATABASE, con.getCatalog());
  assertEquals("PUBLIC", con.getSchema());

  con.setSchema(SECOND_SCHEMA);
  assertEquals(SECOND_SCHEMA, con.getSchema());

  statement.execute(String.format("use database %s", database));
  statement.execute(String.format("use schema %s", schema));

  assertEquals(database, con.getCatalog());
  assertEquals(schema, con.getSchema());

  statement.execute(String.format("drop database if exists %s", SECOND_DATABASE));
  con.close();
}
 
Example 16
Source Project: ignite   File: JdbcStreamingSelfTest.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * @param allowOverwrite Allow overwriting of existing keys.
 * @param flushTimeout Stream flush timeout.
 * @return Connection to use for the test.
 * @throws Exception if failed.
 */
protected Connection createStreamedConnection(boolean allowOverwrite, long flushTimeout) throws Exception {
    Properties props = new Properties();

    props.setProperty(IgniteJdbcDriver.PROP_STREAMING, "true");
    props.setProperty(IgniteJdbcDriver.PROP_STREAMING_FLUSH_FREQ, String.valueOf(flushTimeout));

    if (allowOverwrite)
        props.setProperty(IgniteJdbcDriver.PROP_STREAMING_ALLOW_OVERWRITE, "true");

    Connection res = DriverManager.getConnection(STREAMING_URL, props);

    res.setSchema(QueryUtils.DFLT_SCHEMA);

    return res;
}
 
Example 17
/**
 * Trying to cancel fetch query in situation that there's no worker for cancel query,
 * cause server thread pool is full. No exceptions expected.
 * In order to guarantee correct concurrent processing of query itself and it's cancellation request
 * thress latches and some other stuff is used.
 * For more details see <code>TestSQLFunctions#awaitLatchCancelled()</code>,
 * <code>TestSQLFunctions#awaitQuerySuspensionLatch()</code>
 * and <code>JdbcThinStatementCancelSelfTest#cancel(java.sql.Statement)</code>.
 *
 * @throws Exception If failed.
 */
@Test
public void testCancelFetchAgainstFullServerThreadPool() throws Exception {
    stmt.setFetchSize(1);

    ResultSet rs = stmt.executeQuery("SELECT * from Integer");

    rs.next();

    List<Statement> statements = Collections.synchronizedList(new ArrayList<>());
    List<Connection> connections = Collections.synchronizedList(new ArrayList<>());

    // Prepares connections and statemens in order to use them for filling thread pool with pseuso-infine quries.
    for (int i = 0; i < SERVER_THREAD_POOL_SIZE; i++) {
        Connection yaConn = DriverManager.getConnection(URL);

        yaConn.setSchema('"' + DEFAULT_CACHE_NAME + '"');

        connections.add(yaConn);

        Statement yaStmt = yaConn.createStatement();

        statements.add(yaStmt);
    }

    try {
        // Completely fills server thread pool.
        IgniteInternalFuture<Long> fillPoolRes = fillServerThreadPool(statements,
            SERVER_THREAD_POOL_SIZE - 1);

        IgniteInternalFuture fetchRes = GridTestUtils.runAsync(() -> {
            GridTestUtils.assertThrows(log, () -> {
                rs.next();

                return null;
            }, SQLException.class, "The query was cancelled while executing.");
        });

        stmt.cancel();

        // Ensures that there were no exceptions within async data fetching process.
        fetchRes.get(CHECK_RESULT_TIMEOUT);

        // Releases queries in thread pool.
        TestSQLFunctions.suspendQryLatch.countDown();

        // Ensure that there were no exceptions within async thread pool filling process.
        fillPoolRes.get(CHECK_RESULT_TIMEOUT);
    }
    finally {
        for (Statement statement : statements)
            statement.close();

        for (Connection connection : connections)
            connection.close();
    }
}
 
Example 18
@Override
protected Connection getConnection(@Nonnull @NonNull final String schema) throws SQLException {
    final Connection connection = this.dataSource.getConnection();
    connection.setSchema(connection.getCatalog());
    return connection;
}
 
Example 19
protected Connection getConnection(@Nonnull @NonNull final String schema) throws SQLException {
    final Connection connection = this.dataSource.getConnection();
    connection.setSchema(schema);
    return connection;
}
 
Example 20
Source Project: calcite   File: CalciteAssert.java    License: Apache License 2.0 4 votes vote down vote up
public Connection apply(Connection connection) throws SQLException {
  connection.setSchema(name);
  return connection;
}