Top Description Fields Constructors Methods
org.apache.derby.vti

public Class ForeignTableVTI

extends ForwardingVTI
implements RestrictedVTI
Class Inheritance
All Implemented Interfaces
org.apache.derby.vti.RestrictedVTI
Imports
java.io.InputStream, .Reader, java.math.BigDecimal, java.sql.Blob, .Clob, .Connection, .Date, .DatabaseMetaData, .DriverManager, .PreparedStatement, .ResultSet, .ResultSetMetaData, .SQLException, .Time, .Timestamp, .Types, java.util.Calendar, .HashMap, .Map, org.apache.derby.shared.common.util.ArrayUtil, org.apache.derby.iapi.util.IdUtil

This class contains a table function which can be used to bulk-import data from a foreign database. Because the table function is a RestrictedVTI, it can also be used to periodically and efficiently integrate data streams from a foreign database.

If you need to siphon data out of the foreign database on an ongoing basis, you can restrict the data you SELECT. Note that the local views are backed by RestrictedVTIs. That means that the actual query sent to the foreign database will only involve the columns you SELECT. In addition, the query will include the WHERE clause, provided that it is simple enough (see the javadoc for RestrictedVTI):

The following script shows how to use this table function:

-- create a foreign database with a table in it
connect 'jdbc:derby:memory:db;create=true;user=test_dbo;password=test_dbopassword';

call syscs_util.syscs_create_user( 'test_dbo', 'test_dbopassword' );

create table employee
(
    firstName   varchar( 50 ),
    lastName    varchar( 50 ),
    employeeID  int primary key
);

insert into employee values ( 'Billy', 'Goatgruff', 1 );
insert into employee values ( 'Mary', 'Hadalittlelamb', 2 );

connect 'jdbc:derby:memory:db;shutdown=true';

-- now create the database where we will do our work
connect 'jdbc:derby:memory:db1;create=true';

-- register a table function with the shape of the foreign table
create function employeeFunction
(
    schemaName  varchar( 32672 ),
    tableName   varchar( 32672 ),
    connectionURL        varchar( 32672 )
)
returns table
(
    firstName   varchar( 50 ),
    lastName    varchar( 50 ),
    employeeID  int    
)
language java parameter style derby_jdbc_result_set no sql
external name 'org.apache.derby.vti.ForeignTableVTI.readForeignTable'
;

-- create a convenience view to factor out the function parameters
create view foreignEmployee
as select firstName, lastName, employeeID
from table
(
    employeeFunction
    (
        'TEST_DBO',
        'EMPLOYEE',
        'jdbc:derby:memory:db;user=test_dbo;password=test_dbopassword'
    )
) s;

-- now select from the view as though it were a local table
select * from foreignEmployee;
select lastName from foreignEmployee where employeeID = 2;

Field Summary

Modifier and TypeField and Description
private String[]
private int[]
private static HashMap<String, Connection>
private String
private Connection
private PreparedStatement
private String
private String
private Restriction

Constructor Summary

AccessConstructor and Description
public
ForeignTableVTI(String
Name of the foreign schema
foreignSchemaName
,
String
Name of the foreign table
foreignTableName
,
Connection
Connection to the foreign database
foreignConnection
)

Construct from the foreign schema and table name and a foreign connection.

protected
ForeignTableVTI(String foreignSchemaName, String foreignTableName, String connectionURL)

Method Summary

Modifier and TypeMethod and Description
public void
close()

Overrides org.apache.derby.vti.ForwardingVTI.close.

Implements java.sql.ResultSet.close.

Releases this ResultSet object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed.

public static int

Returns:

the number of open connections to foreign databases
countConnections
()

This function is useful for verifying that the connection to the foreign database was dropped when the foreignViews tool was unloaded.

private static String
public static void
dropConnection(String
URL for connecting to foreign database via DriverManager.getConnection()
connectionURL
)

Remove the cached connection to the foreign database.

private static Connection
getForeignConnection(String connectionURL, Connection foreignConnection)

public void
initScan(String[]
Names of the columns to be fetched
columnNames
,
Restriction
Where clause fragment used to filter rows
restriction
)

Implements org.apache.derby.vti.RestrictedVTI.initScan.

Initialize a scan of a ResultSet.

public boolean
isClosed()

Overrides org.apache.derby.vti.ForwardingVTI.isClosed.

Implements java.sql.ResultSet.isClosed.

Retrieves whether this ResultSet object has been closed.

private String
makeQuery()

Build the query which will be sent to the foreign database.

protected int
mapColumnNumber(int
Number of column in this VTI
derbyNumber
)

Overrides org.apache.derby.vti.ForwardingVTI.mapColumnNumber.

Map a 1-based Derby column number to a 1-based column number in the foreign query.

public boolean
next()

Overrides org.apache.derby.vti.ForwardingVTI.next.

Implements java.sql.ResultSet.next.

Moves the cursor forward one row from its current position.

private static PreparedStatement
public static ForeignTableVTI

Returns:

a VTI which reads the foreign table
readForeignTable
(String
Case-sensitive name of foreign schema
foreignSchemaName
,
String
Case-sensitive name of foreign table
foreignTableName
,
String
URL for connecting to foreign database via DriverManager.getConnection()
connectionURL
)

Table function to read a table in a foreign database.

Inherited from org.apache.derby.vti.ForwardingVTI:
getAsciiStreamgetBigDecimalgetBigDecimalgetBinaryStreamgetBlobgetBooleangetBytegetBytesgetCharacterStreamgetClobgetDategetDategetDoublegetFloatgetIntgetLonggetMetaDatagetObjectgetShortgetStringgetTimegetTimegetTimestampgetTimestampgetWrappedResultSetwasNullwrapResultSet

Field Detail

_columnNamesback to summary
private String[] _columnNames
_columnNumberMapback to summary
private int[] _columnNumberMap
_connectionsback to summary
private static HashMap<String, Connection> _connections
_connectionURLback to summary
private String _connectionURL
_foreignConnectionback to summary
private Connection _foreignConnection
_foreignPreparedStatementback to summary
private PreparedStatement _foreignPreparedStatement
_foreignSchemaNameback to summary
private String _foreignSchemaName
_foreignTableNameback to summary
private String _foreignTableName
_restrictionback to summary
private Restriction _restriction

Constructor Detail

ForeignTableVTIback to summary
public ForeignTableVTI(String foreignSchemaName, String foreignTableName, Connection foreignConnection)

Construct from the foreign schema and table name and a foreign connection.

Parameters
foreignSchemaName:String

Name of the foreign schema

foreignTableName:String

Name of the foreign table

foreignConnection:Connection

Connection to the foreign database

ForeignTableVTIback to summary
protected ForeignTableVTI(String foreignSchemaName, String foreignTableName, String connectionURL)

Method Detail

closeback to summary
public void close() throws SQLException

Overrides org.apache.derby.vti.ForwardingVTI.close.

Implements java.sql.ResultSet.close.

Doc from java.sql.ResultSet.close.

Releases this ResultSet object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed.

The closing of a ResultSet object does not close the Blob, Clob or NClob objects created by the ResultSet. Blob, Clob or NClob objects remain valid for at least the duration of the transaction in which they are created, unless their free method is invoked.

When a ResultSet is closed, any ResultSetMetaData instances that were created by calling the getMetaData method remain accessible.

Note

A ResultSet object is automatically closed by the Statement object that generated it when that Statement object is closed, re-executed, or is used to retrieve the next result from a sequence of multiple results.

Calling the method close on a ResultSet object that is already closed is a no-op.

Exceptions
SQLException:
if a database access error occurs
countConnectionsback to summary
public static int countConnections()

This function is useful for verifying that the connection to the foreign database was dropped when the foreignViews tool was unloaded.

Returns:int

the number of open connections to foreign databases

delimitedIDback to summary
private static String delimitedID(String text)
dropConnectionback to summary
public static void dropConnection(String connectionURL)

Remove the cached connection to the foreign database. This method is called by ForeignDBViews.unloadTool().

Parameters
connectionURL:String

URL for connecting to foreign database via DriverManager.getConnection()

getForeignConnectionback to summary
private static Connection getForeignConnection(String connectionURL, Connection foreignConnection) throws SQLException
initScanback to summary
public void initScan(String[] columnNames, Restriction restriction) throws SQLException

Implements org.apache.derby.vti.RestrictedVTI.initScan.

Doc from org.apache.derby.vti.RestrictedVTI.initScan.

Initialize a scan of a ResultSet. This method is called once before the scan begins. It is called before any ResultSet method is called. This method performs two tasks:

  • Column names - Tells the ResultSet which columns need to be fetched.
  • Limits - Gives the ResultSet simple bounds to apply in order to limit which rows are returned. Note that the ResultSet does not have to enforce all of these bounds. Derby will redundantly enforce these limits on all rows returned by the ResultSet. That is, filtering not performed inside the ResultSet will still happen outside the ResultSet.

The columnNames argument is an array of columns which need to be fetched. This is an array of the column names declared in the Table Function's CREATE FUNCTION statement. Column names which were double-quoted in the CREATE FUNCTION statement appear case-sensitive in this array. Column names which were not double-quoted appear upper-cased. Derby asks the Table Function to fetch all columns mentioned in the query. This includes columns mentioned in the SELECT list as well as columns mentioned in the WHERE clause. Note that a column could be mentioned in the WHERE clause in a complex expression which could not be passed to the Table Function via the restriction argument.

The array has one slot for each column declared in the CREATE FUNCTION statement. Slot 0 corresponds to the first column declared in the CREATE FUNCTION statement and so on. If a column does not need to be fetched, then the corresponding slot is null. If a column needs to be fetched, then the corresponding slot holds the column's name.

Note that even though the array may have gaps, it is expected that columns in the ResultSet will occur at the positions declared in the CREATE FUNCTION statement. Consider the following declaration:

 create function foreignEmployeeTable()
 returns table
 (
     id        int,
     birthDay  date,
     firstName varchar( 100 ),
     lastName  varchar( 100 )
 )
...

and the following query:

select lastName from table( foreignEmployeeTable() ) s

In this example, the array passed to this method will have 4 slots. Slots 0, 1, and 2 will be null and slot 3 will hold the String "LASTNAME". Last names will be retrieved from the ResultSet by calls to getString( 4 )--remember that JDBC column ids are 1-based.

The restriction argument is a simple expression which should be evaluated inside the Table Function in order to eliminate rows. The expression is a binary tree built out of ANDs, ORs, and column qualifiers. The column qualifiers are simple comparisons between constant values and columns in the Table Function. The Table Function only returns rows which satisfy the expression. The restriction is redundantly enforced by Derby on the rows returned by the ResultSet--this means that restriction gives the Table Function a hint about how to optimize its performance but the Table Function is not required to enforce the entire restriction.

Parameters
columnNames:String[]

Names of the columns to be fetched

restriction:Restriction

Where clause fragment used to filter rows

Exceptions
SQLException:
on error
isClosedback to summary
public boolean isClosed()

Overrides org.apache.derby.vti.ForwardingVTI.isClosed.

Implements java.sql.ResultSet.isClosed.

Doc from java.sql.ResultSet.isClosed.

Retrieves whether this ResultSet object has been closed. A ResultSet is closed if the method close has been called on it, or if it is automatically closed.

Returns:boolean

true if this ResultSet object is closed; false if it is still open

makeQueryback to summary
private String makeQuery()

Build the query which will be sent to the foreign database.

mapColumnNumberback to summary
protected int mapColumnNumber(int derbyNumber)

Overrides org.apache.derby.vti.ForwardingVTI.mapColumnNumber.

Map a 1-based Derby column number to a 1-based column number in the foreign query.

Parameters
derbyNumber:int

Doc from org.apache.derby.vti.ForwardingVTI.mapColumnNumber.

Number of column in this VTI

Returns:int

Doc from org.apache.derby.vti.ForwardingVTI.mapColumnNumber.

the corresponding number of the column in the wrapped ResultSet

Annotations
@Override
nextback to summary
public boolean next() throws SQLException

Overrides org.apache.derby.vti.ForwardingVTI.next.

Implements java.sql.ResultSet.next.

Doc from java.sql.ResultSet.next.

Moves the cursor forward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown. If the result set type is TYPE_FORWARD_ONLY, it is vendor specified whether their JDBC driver implementation will return false or throw an SQLException on a subsequent call to next.

If an input stream is open for the current row, a call to the method next will implicitly close it. A ResultSet object's warning chain is cleared when a new row is read.

Returns:boolean

true if the new current row is valid; false if there are no more rows

Exceptions
SQLException:
if a database access error occurs or this method is called on a closed result set
prepareStatementback to summary
private static PreparedStatement prepareStatement(Connection conn, String text) throws SQLException
readForeignTableback to summary
public static ForeignTableVTI readForeignTable(String foreignSchemaName, String foreignTableName, String connectionURL)

Table function to read a table in a foreign database.

Parameters
foreignSchemaName:String

Case-sensitive name of foreign schema

foreignTableName:String

Case-sensitive name of foreign table

connectionURL:String

URL for connecting to foreign database via DriverManager.getConnection()

Returns:ForeignTableVTI

a VTI which reads the foreign table