libjtds-java-1.2.5.orig/ 0000755 0001750 0001750 00000000000 11337006722 014377 5 ustar martin martin libjtds-java-1.2.5.orig/build_1.3.xml 0000644 0001750 0001750 00000013335 11316672660 016615 0 ustar martin martin
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
The Overview page is the front page of this API document and provides a list of all packages with a summary for each. This page can also contain an overall description of the set of packages.
Each package has a page that contains a list of its classes and interfaces, with a summary for each. This page can contain four categories:
- Interfaces (italic)
- Classes
- Exceptions
- Errors
Each class, interface, nested class and nested interface has its own separate page. Each of these pages has three sections consisting of a class/interface description, summary tables, and detailed member descriptions:
Each summary entry contains the first sentence from the detailed description for that item. The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer.
- Class inheritance diagram
- Direct Subclasses
- All Known Subinterfaces
- All Known Implementing Classes
- Class/interface declaration
- Class/interface description
- Nested Class Summary
- Field Summary
- Constructor Summary
- Method Summary
- Field Detail
- Constructor Detail
- Method Detail
Each documented package, class and interface has its own Use page. This page describes what packages, classes, methods, constructors and fields use any part of the given class or package. Given a class or interface A, its Use page includes subclasses of A, fields declared as A, methods that return A, and methods and constructors with parameters of type A. You can access this page by first going to the package, class or interface, then clicking on the "Use" link in the navigation bar.
There is a Class Hierarchy page for all packages, plus a hierarchy for each package. Each hierarchy page contains a list of classes and a list of interfaces. The classes are organized by inheritance structure starting withjava.lang.Object. The interfaces do not inherit fromjava.lang.Object.
- When viewing the Overview page, clicking on "Tree" displays the hierarchy for all packages.
- When viewing a particular package, class or interface page, clicking "Tree" displays the hierarchy for only that package.
The Deprecated API page lists all of the API that have been deprecated. A deprecated API is not recommended for use, generally due to improvements, and a replacement API is usually given. Deprecated APIs may be removed in future implementations.
The Index contains an alphabetic list of all classes, interfaces, constructors, methods, and fields.
This help file applies to API documentation generated using the standard doclet.
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Package net.sourceforge.jtds.jdbc |
| Class net.sourceforge.jtds.jdbc.ProtocolException extends java.lang.Exception implements Serializable |
| Package net.sourceforge.jtds.jdbc.cache |
| Class net.sourceforge.jtds.jdbc.cache.SimpleLRUCache extends java.util.HashMap implements Serializable |
| Serialized Fields |
int maxCacheSize
java.util.LinkedList list
| Package net.sourceforge.jtds.jdbcx |
| Class net.sourceforge.jtds.jdbcx.JtdsDataSource extends java.lang.Object implements Serializable |
serialVersionUID: 266240l
| Serialized Fields |
java.lang.String serverName
java.lang.String serverType
java.lang.String portNumber
java.lang.String databaseName
java.lang.String tdsVersion
java.lang.String charset
java.lang.String language
java.lang.String domain
java.lang.String useNTLMV2
java.lang.String instance
java.lang.String lastUpdateCount
java.lang.String sendStringParametersAsUnicode
java.lang.String namedPipe
java.lang.String macAddress
java.lang.String prepareSql
java.lang.String packetSize
java.lang.String tcpNoDelay
java.lang.String user
java.lang.String password
java.lang.String loginTimeout
java.lang.String lobBuffer
java.lang.String maxStatements
java.lang.String appName
java.lang.String progName
java.lang.String wsid
java.lang.String xaEmulation
java.lang.String logFile
java.lang.String socketTimeout
java.lang.String socketKeepAlive
java.lang.String processId
java.lang.String ssl
java.lang.String batchSize
java.lang.String bufferDir
java.lang.String bufferMaxMemory
java.lang.String bufferMinPackets
java.lang.String cacheMetaData
java.lang.String useCursors
java.lang.String useLOBs
java.lang.String bindAddress
java.lang.String useJCIFS
java.lang.String description
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
appName property.
Statement.cancel().
props properties object.
defaultKey and the defaults map to
determine the correct value.
expected property value is set using
a given url.
expected property value is set using
a given url and tdsVersion property.
ConnectionJDBC2.unpackProperties(Properties) is called
with an invalid integer (or long) string set on a property.
batchSize property for SQL Server.
batchSize property for Sybase.
bindAddress property.
tmpDir property.
bufferMaxMemory property.
bufferMinPackets property.
testConcurrentBatching() to execute a batch within a transaction that is
then rolled back. InputStream over the CLOB buffer.
OutputStream for CLOB data.OutputStream object over the BLOB
buffer.
InputStream over the BLOB buffer.InputStream object over the BLOB buffer.
OutputStream for BLOB data.InputStream over the CLOB buffer.Blob instance.
Blob instance initialized with data.
BlobBuffer.
BlobBuffer.
cacheMetaData property.
charset property.
Charsets.properties resource.
CharsetInfo object from a character set
descriptor of the form: charset preceded by a numeric value indicating
whether it's a multibyte character set (>1) or not (1) and a vertical
bar (|), eg "1|Cp1252" or "2|MS936".
Clob instance.
Clob instance.
ConnectionJDBC2 class.net.sourceforge.jtds.jdbc.ConnectionJDBC2.unpackProperties(Properties).ConnectionJDBC3Test.testTimerStopHelper.test().
ResultSet).
TdsCore instance to reuse on new statements.
InputStream
for named pipes.
SharedSocket.cancelPending and
SharedSocket.responseOwner.
TdsCore.cancelPending.
Boolean.TRUE if identifiers are case sensitive (the server
was installed that way).
ParamInfo instance.
Connection object's database and JDBC
resources immediately instead of waiting for them to be automatically
released.
TdsCore connection object and associated streams.
Strings.
choices
field should be set when calling
Driver.getPropertyInfo(String, Properties).
SharedSocket object representing a connection to a named
pipe.
Driver.getPropertyInfo(String, Properties).
SharedSocket.VirtualSocket through reflection when Driver.JDBC3
is true.
ResultSet.
databaseName property.
domain property.
DatabaseMetaData.DatabaseMetaData.java.sql.Timestamp.
java.sql.Time.
java.sql.Date.
DefaultProperties class.Driver class.Driver.getPropertyInfo(String, Properties).Driver.setupConnectProperties(String, java.util.Properties).java.sql.Date.
ENVCHANGE packets on login ack, by executing a DB
vendor/version specific query.
jdbc:jtds:).
byte[] as initial value for empty
Blobs.
String as initial value for empty
Clobs.
TdsCore.getParameters() call
JtdsStatement.execute(java.lang.String)
and {#link #executeUpdate}: basic checks, cleaning up of previous
results, setting up and executing the query and loading the first
results.
ResultSets).
ResultSets).
ColInfo instance with the JDBC type set.
ResultSet object and this statement.
Object[] object to a String.
get() so that it also updates the LRU list.
null if the key specified does not have an associated
statement handle.
InputStream.
BlobBuffer object.
Statement for this connection.
TdsCore or null if
nothing is cached and resets the cache (sets it to null).
CharsetInfo instance asociated with the
specified server charset.
CharsetInfo instance asociated with the
specified collation.
CharsetInfo instance asociated with the
specified LCID.
CharsetInfo instance asociated with the
specified sort order.
CharsetInfo instance used by this connection.
ConnectionJDBC2 object referenced by the
JtdsResultSet.statement instance variable.
ResultSet,
Statement or Connection object.
Connection, overriding the default properties
with the ones provided.
SharedSocket.in field.
InputStream over the server response.
SSPIJNIClient instance.
Class.
RequestStream.maxPrecision.
Collection of obsolete statement handles that may
be released, or null if no statement handles are obsolete.
SharedSocket.out field.
SharedNamedPipe.pipe field.
DefaultProperties.getServerType(int), only it returns the default server
type ("sqlserver") if serverType is 0.
DefaultPropertiesTestLibrary.tester.
InputStream.
String and byte[]
respectively.
instance property.
Statement, by cleaning up all queued and
unprocessed results.
testBigDecimal0007.
#initialize() if the SSPI client is not already inited.
#prepareSSORequest() to prepare the NTLM TYPE-1 message.
#prepareSSOSubmit(byte[], long) to prepare the NTLM TYPE-3
message.
#unInitialize() if the SSPI client is inited.
Support.calculateNamedPipeBufferSize(int, int)
using reflection.
#onlySqlServerTests.
#onlyTds70Tests.
true if the specified procName
is a sp_prepare or sp_prepexec handle; returns false
otherwise.
os.name system property to see if it starts
with "windows".
DataSource, ConnectionPoolDataSource and
XADataSource implementation.JtdsDataSource class.JtdsDataSource.addNonNullProperties(Properties, String, String).JtdsDataSource.JtdsDataSource.getReference().JtdsObjectFactory class.JtdsObjectFactory.getObjectInstance(Object, Name, Context, Hashtable).XAConnection interface.XAConnection object.
Xid interface.language property.
lastUpdateCount property.
InputStream that only returns a limited
number of bytes on read (less than the requested number of bytes).
lobBufferSize property.
logfile property.
loginTimeout property.
SQLWarning.
SQLException.
Exception.
Messages.properties and populate
them into Map objects.
DriverPropertyInfo array from
Driver.getPropertyInfo(String, Properties) and convert it
into a Map using the name property for the keys.
Messages.DEFAULT_RESOURCE resource bundle.
true if updates are made to a copy of the LOB; returns
false if LOB updates are made directly to the database.
macAddress property.
maxStatements property.
null).
Messages.properties.Messages.properties file.Messages.properties.Messages.properties.namedPipe property.
namedPipePath property for SQL Server.
namedPipePath property for Sybase.
SharedNamedPipe class.Types-defined type for an SQL Server specific data type.
NULL and non-NULL values being
NULL.
moveToInsertRow() was called.
packetSize property for TDS 4.2.
packetSize property for TDS 5.0.
packetSize property for TDS 7.0 and TDS 8.0.
sp_cursorfetch fetchtype parameter.
sp_cursorfetch numrows IN parameter (for actual fetches).
sp_cursorfetch numrows OUT parameter (for FETCH_INFO).
sp_cursor optype parameter.
sp_cursor rownum parameter.
sp_cursorfetch rownum IN parameter (for actual fetches).
sp_cursorfetch rownum OUT parameter (for FETCH_INFO).
sp_cursor table parameter.
password property.
portNumber property for SQL Server.
portNumber property for Sybase.
prepareSql property for SQL Server.
prepareSql property for Sybase.
processId property.
progName property.
ParameterMetaData.
PooledConnection interface.PreparedStatementTest.testMultiThread() to
test concurrency.null if no parameters
are expected.
byte[].
JtdsStatement.resultQueue until the end of the
response is reached or a ResultSet is encountered.
put() so that it also updates the LRU list.
RequestStream object.
InputStream over the
server response.TdsInputStream instance.
XAException with an explanatory message derived from the
SQLException and the XA error code set to XAER_RMFAIL.
XAException with an explanatory message and the XA error code set.
len bytes or throws an IOException if
there aren't that many bytes available.
int value from the server response stream.
long value from the server response stream.
String from the server response stream,
creating the String from a translated byte
array.
String from the server response stream, translating
it from a byte array using the specified character set.
short value from the server response stream.
String object from the server response stream.
String from the server response stream, creating
it from a translated byte array.
unsigned long value from the server response stream.
TdsCore.
ResultSet).
JtdsResultSet.currentRow.
TimerThread main loop.
Messages.properties.
Messages.properties.
serverType property for SQL Server.
serverType property for Sybase.
socketKeepAlive property.
sockeTimeout property.
ssl property.
SharedLocalNamedPipe.
SharedNamedPipe.
SharedSocket object specifying host name and
port.
Support class.xp_jtdsxa extended stored procedure on the
server.
OutputStream that can be used to update the
BLOB.
charsetInfo field of ci according to
the value of its collation field.
SharedSocket.in field.
DefaultPropertiesTestLibrary.onlySqlServerTests.
DefaultPropertiesTestLibrary.onlyTds70Tests.
SharedSocket.out field.
SharedNamedPipe.pipe field.
#tester.
Driver.connect(String, java.util.Properties) method.
String from the server response stream.
TdsCore that a batch is starting.
String.
true if getting auto-generated keys is supported after a
statment is executed; returns false otherwise
LIKE
escape clause.
true if Callable statements can return multiple result sets;
returns false if they can only return one result set.
true if the database supports named parameters;
returns false if the database does not support named parameters.
true if savepoints are supported; returns
false otherwise
true if the database supports statement pooling;
returns false otherwise.
EXISTS expressions.
IN statements.
tcpNoDelay property.
tds property for TDS 4.2.
tds property for TDS 5.0.
tds property for TDS 7.0.
tds property for TDS 8.0.
TimerThread instance.
TimerListener.TimerRequest.
getTypeInfo().
TypeInfo class.ResponseStream.
absolute() with very large positive
values positions the cursor after the last row and with very large
negative values positions the cursor before the first row.
absolute(-1) works the same as last().
BigDecimals created from double values (i.e with very
large scales).
InputStream that doesn't fill the
buffer on read().
Blob.
Support.calculateNamedPipeBufferSize(int, int)
sets the buffer size appropriately for TDS 4.2 when the packet
size is set to 0.
Support.calculateNamedPipeBufferSize(int, int)
sets the buffer size appropriately for TDS 5.0 when the packet
size is set to 0.
Support.calculateNamedPipeBufferSize(int, int)
sets the buffer size appropriately for TDS 7.0 when the packet
size is set to 0.
Support.calculateNamedPipeBufferSize(int, int)
sets the buffer size appropriately for TDS 8.0 when the packet
size is set to 0.
CallableStatements with return values work correctly.
Clob manipulation including indexed writes.
sp_cursorfetch with fetch sizes
greater than 1.
Statement.setMaxRows() works on cursor
ResultSets.
ResultSet.previous() works correctly on cursor
ResultSets.
CursorResultSet concurrency.
DataTruncation exception.
ResultSet.deleteRow() on updateable result sets.
ResultSet.TYPE_SCROLL_SENSITIVE+1)
see others' updates.
insertRow() works with no values set.
executeUpdate("SELECT ...")
- testFloat1() -
Method in class net.sourceforge.jtds.test.SAfeTest
- Test for bug [963799] float values change when written to the database
- testFloatValues() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Tests that float (single precision - 32 bit) values are not converted to
double (thus loosing precision).
- testFnEscape() -
Method in class net.sourceforge.jtds.test.SAfeTest
- Test for bug related with [1368058] Calling StoredProcedure with
functions ({fn} escape can't handle special characters, e.g. underscore).
- testFnEscapeNesting() -
Method in class net.sourceforge.jtds.test.SAfeTest
- Test for bug #1116046 {fn } escape can't handle nested functions.
- testForBrowse0014() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testForceCharset1() -
Method in class net.sourceforge.jtds.test.ConnectionJDBC2UnitTest
- Test correct behavior of the
charset property.
- testForceCharset2() -
Method in class net.sourceforge.jtds.test.ConnectionJDBC2UnitTest
- Test correct behavior of the
charset property.
- testGetAsciiStream0018() -
Method in class net.sourceforge.jtds.test.CSUnitTest
-
- testGetBoolean0025() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testGetByName() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test whether retrieval by name returns the first occurence (that's what
the spec requires).
- testGetColumnsMetaData() -
Method in class net.sourceforge.jtds.test.DatabaseMetaDataTest
- Test for bug [1120168] jTDS 101 - TDS data type 0 invalid.
- testGetFloatObject() -
Method in class net.sourceforge.jtds.test.SunTest
- Generic test for SUN bug where Float was promoted to Double
by driver leading to ClassCastExceptions in the tests.
- testGetMetaData() -
Method in class net.sourceforge.jtds.test.SunTest
- Test for SUN bug [ PrepStmt1.getMetaData() ]
Driver loops if select contains commas.
- testGetMultiScrollRs() -
Method in class net.sourceforge.jtds.test.SAfeTest
- Test return of multiple scrollable result sets from one execute.
- testGetObject1() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test BIT data type.
- testGetObject2() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test TINYINT data type.
- testGetObject3() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test SMALLINT data type.
- testGetObject4() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test INT data type.
- testGetObject5() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test BIGINT data type.
- testGetParamMetaData() -
Method in class net.sourceforge.jtds.test.JDBC3Test
- Test for bug [1222205] getParameterMetaData returns not implemented.
- testGetProcedures() -
Method in class net.sourceforge.jtds.test.SunTest
- Test for SUN bug [ dbMeta8.testGetProcedures ]
The wrong column names are returned by getProcedures().
- testGetString() -
Method in class net.sourceforge.jtds.test.TimestampTest
- Test for bug [1235845] getTimestamp() returns illegal value after
getString().
- testGetTableTypesOrder() -
Method in class net.sourceforge.jtds.test.DatabaseMetaDataTest
- Test for bug [974036] Bug in 0.8rc1 DatabaseMetaData method getTableTypes()
- testGetTables() -
Method in class net.sourceforge.jtds.test.DatabaseMetaDataTest
- Test for bug [998765] Exception with Sybase and metaData.getTables()
- testIllegalParameters() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for bug [1111516 ] Illegal Parameters in PreparedStatement.
- testImageText() -
Method in class net.sourceforge.jtds.test.Tds5Test
- Test for bug [1161609] Text or image data truncated on Sybase 12.5
- testInOutParameters() -
Method in class net.sourceforge.jtds.test.CallableStatementTest
- Test for separation of IN and INOUT/OUT parameter values
- testInsertConflict0049() -
Method in class net.sourceforge.jtds.test.CSUnitTest
-
- testInsertRow0012() -
Method in class net.sourceforge.jtds.test.SAfeTest
- Test
ResultSet.insertRow() on updateable result sets.
- testInsertRowVisible() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test that inserted rows are visible in a scroll sensitive
ResultSet and that they show up at the end.
- testIntOptions() -
Method in class net.sourceforge.jtds.test.DatabaseMetaDataJDBC3Test
- Test meta data function that return integer values.
- testIntOptions() -
Method in class net.sourceforge.jtds.test.DatabaseMetaDataTest
- Test meta data function that return integer values.
- testIsWindowsOS_Linux() -
Method in class net.sourceforge.jtds.test.SupportUnitTest
-
- testIsWindowsOS_MacOSX() -
Method in class net.sourceforge.jtds.test.SupportUnitTest
-
- testIsWindowsOS_Windows() -
Method in class net.sourceforge.jtds.test.SupportUnitTest
-
- testIsWindowsOS_Windows_XP() -
Method in class net.sourceforge.jtds.test.SupportUnitTest
-
- testIsWindowsOS_windows() -
Method in class net.sourceforge.jtds.test.SupportUnitTest
-
- testLMv2() -
Method in class net.sourceforge.jtds.test.NtlmAuthTest
-
- testLMv2CapturedData() -
Method in class net.sourceforge.jtds.test.NtlmAuthTest
-
- testLargeBatch() -
Method in class net.sourceforge.jtds.test.BatchTest
- Test large batch behavior.
- testLargeBlob1() -
Method in class net.sourceforge.jtds.test.LargeLOBTest
- Test for bug [945507] closing statement after selecting a large IMAGE - Exception
- testLocalTran() -
Method in class net.sourceforge.jtds.test.XaTest
- Demonstrate interleaving local transactions and distributed
transactions.
- testLongData() -
Method in class net.sourceforge.jtds.test.Tds5Test
- Test varchar and varbinary fields longer than 255 bytes.
- testLongStatement() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for bug [1022968] Long SQL expression error.
- testLongToVarchar0008() -
Method in class net.sourceforge.jtds.test.SAfeTest
- Test writing
long values to VARCHAR fields.
- testManyParametersStatement() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for bug [1047330] prep statement with more than 2100 params fails.
- testMaxFieldSize() -
Method in class net.sourceforge.jtds.test.SAfeTest
- Test
Statement.setMaxFieldSize().
- testMaxRows() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for bug [1010660] 0.9-rc1 setMaxRows causes unlimited temp stored
procedures.
- testMaxRows() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Check whether
Statement.setMaxRows() works okay, bug
[1812686].
- testMaxRows0003() -
Method in class net.sourceforge.jtds.test.CSUnitTest
-
- testMetaData() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for bad truncation in prepared statements on metadata retrieval
(patch [1076383] ResultSetMetaData for more complex statements for SQL
Server).
- testMetaData() -
Method in class net.sourceforge.jtds.test.Tds8Test
-
- testMetaData0046() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testMetaDataClearsResultSet() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for bug [1050660] PreparedStatement.getMetaData() clears resultset.
- testMissingParameter0016() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testMissingWhitespace() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for bug [ 1059916 ] whitespace needed in preparedStatement.
- testMoneyHandling0019() -
Method in class net.sourceforge.jtds.test.CSUnitTest
-
- testMoreThan255Columns() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test if COL_INFO packets are processed correctly for
ResultSets with over 255 columns.
- testMultiByteCharTruncation() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for bug [2814376] varchar-type is truncated in non-unicode
environment.
- testMultiThread() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test
Connection concurrency by running
PreparedStatements and rollbacks at the same time to see
whether handles are not lost in the process.
- testMultipleResults() -
Method in class net.sourceforge.jtds.test.JDBC3Test
- Test return of multiple open result sets from one execute.
- testMultipleResults0015() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testNTLMv2() -
Method in class net.sourceforge.jtds.test.NtlmAuthTest
-
- testNTLMv2CapturedData() -
Method in class net.sourceforge.jtds.test.NtlmAuthTest
-
- testNamedParameters0001() -
Method in class net.sourceforge.jtds.test.CallableStatementJDBC3Test
- Test named parameters.
- testNegativeOverflow() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test for bug [2860742], getByte() causes overflow error for negative
values.
- testNegativeScale() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
-
- testNestedEscapes() -
Method in class net.sourceforge.jtds.test.SunTest
- Test nested escapes
- testNestedStatements0022() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testNestedStatements0026() -
Method in class net.sourceforge.jtds.test.TimestampTest
- SAfe Tests whether cursor-based statements still work ok when
nested.
- testNoCount() -
Method in class net.sourceforge.jtds.test.BatchTest
- The first statement in this batch does not return an update count.
- testNoHost() -
Method in class net.sourceforge.jtds.test.JtdsDataSourceUnitTest.Test_JtdsDataSource_getConnection
- Test connecting without specifying a host.
- testNoKeys() -
Method in class net.sourceforge.jtds.test.GenKeyTest
- Test empty result set returned when no keys available.
- testNoPrepare() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test that statements which cannot be prepared are remembered.
- testNoProperties() -
Method in class net.sourceforge.jtds.test.JtdsObjectFactoryUnitTest
- Tests that the factory can correctly rebuild a DataSource with no
properties set (i.e. all values should be null and no NPE should be
thrown).
- testNoUser() -
Method in class net.sourceforge.jtds.test.JtdsDataSourceUnitTest.Test_JtdsDataSource_getConnection
- Test connecting without specifying a user.
- testNonRpcProc1() -
Method in class net.sourceforge.jtds.test.CallableStatementTest
- Test that procedure calls with both literal parameters and parameterr
markers are executed correctly (bug [1078927] Callable statement fails).
- testNonRpcProc2() -
Method in class net.sourceforge.jtds.test.CallableStatementTest
- Test that procedure calls with both literal parameters and parameterr
markers are executed correctly (bug [1078927] Callable statement fails).
- testNormal() -
Method in class net.sourceforge.jtds.test.JtdsDataSourceUnitTest.Test_JtdsDataSource_getConnection
- Test connecting with the settings in connection.properties.
- testNullBoolean() -
Method in class net.sourceforge.jtds.test.Tds8Test
- Test for bug [1042272] jTDS doesn't allow null value into Boolean.
- testNullImage() -
Method in class net.sourceforge.jtds.test.SanityTest
-
- testNullLengthStrings0001() -
Method in class net.sourceforge.jtds.test.SAfeTest
- Test whether NULL values, 0-length strings and single space strings
are treated right.
- testNullOutputParameters() -
Method in class net.sourceforge.jtds.test.SAfeTest
- Test that
null output parameters are handled correctly.
- testNullText() -
Method in class net.sourceforge.jtds.test.SanityTest
-
- testNullUniText() -
Method in class net.sourceforge.jtds.test.Tds5Test
-
- testNumericOverflow() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test for bug [1855125], numeric overflow not reported by jTDS.
- testNvarcharNormalized() -
Method in class net.sourceforge.jtds.test.DatabaseMetaDataTypeInfoTest
-
- testOldDates0016() -
Method in class net.sourceforge.jtds.test.SAfeTest
- Test that dates prior to 06/15/1940 0:00:00 are stored and retrieved
correctly.
- testOptimisticUpdates() -
Method in class net.sourceforge.jtds.test.ClientSideCursorTest
- Test optimistic updates throw exception if row is changed on disk.
- testOrderedByDatatype() -
Method in class net.sourceforge.jtds.test.DatabaseMetaDataTypeInfoTest
- Check types ordered by data type.
- testOrderedByTypeMapping() -
Method in class net.sourceforge.jtds.test.DatabaseMetaDataTypeInfoTest
- Check that types with the same JDBC data type are ordered by closest
match to the standard JDBC type.
- testOutOfMemory() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test the behavior of the ResultSet/Statement/Connection when the JVM
runs out of memory (hopefully) in the middle of a packet.
- testOutOfOrderClose0013() -
Method in class net.sourceforge.jtds.test.SAfeTest
- Test how an "out-of-order" close behaves (e.g close the
Connection first, then the Statement anf
finally the ResultSet).
- testOuterJoinParameters() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for bug [1071397] Error in prepared statement (parameters in outer
join escapes are not recognized).
- testOutputParams() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testParams() -
Method in class net.sourceforge.jtds.test.GenKeyTest
-
- testPessimisticConcurrency() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test pessimistic concurrency for SQL Server (for Sybase optimistic
concurrency will always be used).
- testPlainResultSetPosition0004() -
Method in class net.sourceforge.jtds.test.SAfeTest
- Check that the
isBeforeFirst, isAfterLast,
isFirst and isLast methods work for
forward-only, read-only result sets (bug [1039876] MS SQL
JtdsResultSet.isAfterLast() always returns false).
- testPositionedUpdate() -
Method in class net.sourceforge.jtds.test.ClientSideCursorTest
- Test support for JDBC 1 style positioned updates with named cursors.
- testPrepStmtBatch() -
Method in class net.sourceforge.jtds.test.BatchTest
- Test batched prepared statements.
- testPrepStmtBatchDupKey() -
Method in class net.sourceforge.jtds.test.BatchTest
- Test for bug [1371295] SQL Server continues after duplicate key error.
- testPrepStmtError() -
Method in class net.sourceforge.jtds.test.SunTest
- Test for bug [ 1012301 ] 0.9-rc1: Prepared statement execution error.
- testPrepStmtNoParams() -
Method in class net.sourceforge.jtds.test.BatchTest
- Test for PreparedStatement batch with no parameters.
- testPrepStmtVariableParams() -
Method in class net.sourceforge.jtds.test.BatchTest
- Test for PreparedStatement batch with variable parameter types.
- testPrepareFailWarning() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for bug [1180777] collation-related execption on update.
- testPrepareModes() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test that preparedstatement logic copes with commit modes and
database changes.
- testPrepareSQL0() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for bug [1623668] Lost apostrophes in statement parameter values(prepareSQL=0)
- testPreparedAndCallableCursors0014() -
Method in class net.sourceforge.jtds.test.SAfeTest
- Test cursor-based
ResultSets obtained from
PreparedStatements and CallableStatements.
- testPreparedStatement() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
-
- testPreparedStatement0007() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testPreparedStatement0008() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testPreparedStatement0009() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testPreparedStatement0040() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testPreparedStatement0041() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testPreparedStatement0042() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testPreparedStatementAddBatch1() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
-
- testPreparedStatementParsing1() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for [924030] EscapeProcesser problem with "{}" brackets
- testPreparedStatementParsing2() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for bug [1008882] Some queries with parameters cannot be executed with 0.9-rc1
- testPreparedStatementParsing3() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for "invalid parameter index" error.
- testPreparedStatementRollback1() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for [931090] ArrayIndexOutOfBoundsException in rollback()
- testPreparedStatementSetObject1() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for bug [938494] setObject(i, o, NUMERIC/DECIMAL) cuts off decimal places
- testPreparedStatementSetObject2() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for bug [938494] setObject(i, o, NUMERIC/DECIMAL) cuts off decimal places
- testPreparedStatementSetObject3() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for bug [938494] setObject(i, o, NUMERIC/DECIMAL) cuts off decimal places
- testPreparedStatementSetObject4() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for bug [938494] setObject(i, o, NUMERIC/DECIMAL) cuts off decimal places
- testPreparedStatementSetObject5() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for bug [938494] setObject(i, o, NUMERIC/DECIMAL) cuts off decimal places
- testPreparedStatementSetObject6() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for bug [1204658] Conversion from Number to BigDecimal causes data
corruption.
- testPrimaryKeyFloat0023() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testPrimaryKeyReal0024() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testProc1() -
Method in class net.sourceforge.jtds.test.AsTest
-
- testProc2() -
Method in class net.sourceforge.jtds.test.AsTest
-
- testProcedureColumns() -
Method in class net.sourceforge.jtds.test.DatabaseMetaDataTest
- Test for bug [1184376] Sybase getProcedureColumns bug
- testProcedureUseLOBsFalse() -
Method in class net.sourceforge.jtds.test.DatabaseMetaDataTest
- Test for bug [1245775] Column type inconsistency when useLOBs=false.
- testProcessUpdateCounts1() -
Method in class net.sourceforge.jtds.test.CallableStatementTest
- Test that procedure outputs are available immediately for procedures
that do not return ResultSets (i.e that update counts are cached).
- testProcessUpdateCounts2() -
Method in class net.sourceforge.jtds.test.CallableStatementTest
- Test that procedure outputs are available immediately after processing
the last ResultSet returned by the procedure (i.e that update counts
are cached).
- testProcessUpdateCounts3() -
Method in class net.sourceforge.jtds.test.CallableStatementTest
- Test that procedure outputs are available immediately after processing
the last ResultSet returned by the procedure (i.e that update counts
are cached) even if getMoreResults() is not called.
- testProcessUpdateCounts4() -
Method in class net.sourceforge.jtds.test.CallableStatementTest
- Test that procedure outputs are available immediately after processing
the last ResultSet returned by the procedure (i.e that update counts
are cached) even if getMoreResults() and ResultSet.close() are not
called.
- testPublicConstructor() -
Method in class net.sourceforge.jtds.test.JtdsDataSourceUnitTest
- Tests that the public constructor works.
- testQueryTimeout() -
Method in class net.sourceforge.jtds.test.SAfeTest
- Test for bug [1222199] Delayed exception thrown in statement close.
- testQueryTimeout() -
Method in class net.sourceforge.jtds.test.StatementTest
- Test for bug [1694194], queryTimeout does not work on MSSQL2005 when
property 'useCursors' is set to 'true'.
- testReadText() -
Method in class net.sourceforge.jtds.test.ReadTextTest
-
- testRelative() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test for bug [1182066] regression bug resultset: relative() not working
as expected.
- testRelativeLargeValue() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test that calling
absolute() with very large positive
values positions the cursor after the last row and with very large
negative values positions the cursor before the first row.
- testResultSet0043() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testResultSet0044() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testResultSet0045() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testResultSetColumnName1() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test for bug [1009233] ResultSet getColumnName, getColumnLabel return wrong values
- testResultSetError() -
Method in class net.sourceforge.jtds.test.BatchTest
- This test should generate an error as the second statement in the batch
returns a result set.
- testResultSetMetaData() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test for fixed bugs in ResultSetMetaData:
isNullable() always returns columnNoNulls.
- testResultSetMetaData() -
Method in class net.sourceforge.jtds.test.Tds5Test
- Test that resultset meta data is correct for short varchar/varbinary types.
- testResultSetMetaData2() -
Method in class net.sourceforge.jtds.test.Tds5Test
- Test that resultset meta data is correct for long varchar/varbinary types.
- testResultSetMetaData3() -
Method in class net.sourceforge.jtds.test.Tds5Test
- Test Sybase ASE misc data type metadata.
- testResultSetMetaData4() -
Method in class net.sourceforge.jtds.test.Tds5Test
- Test Sybase ASE 15+ misc data type metadata.
- testResultSetMetadate() -
Method in class net.sourceforge.jtds.test.DatabaseMetaDataTest
- Test for bug [1833720], invalid table names for large result sets.
- testResultSetScroll1() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test for bug [961594] ResultSet.
- testResultSetScroll2() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test for bug [945462] getResultSet() return null if you use scrollable/updatable.
- testResultSetScroll3() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test for bug [1028881] statement.execute() causes wrong ResultSet type.
- testResultSetUpdate1() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test for bug [1008208] 0.9-rc1 updateNull doesn't work.
- testResultSets() -
Method in class net.sourceforge.jtds.test.DatabaseMetaDataJDBC3Test
- Test meta data functions that return result sets.
- testResultSets() -
Method in class net.sourceforge.jtds.test.DatabaseMetaDataTest
- Test meta data functions that return result sets.
- testRowstat() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test for bug [1329765] Pseudo column ROWSTAT is back with SQL 2005
(September CTP).
- testSQL2005MetaData() -
Method in class net.sourceforge.jtds.test.Tds8Test
- Test for enhanced database metadata for SQL 2005.
- testSanity() -
Method in class net.sourceforge.jtds.test.SanityTest
- A simple test to make sure everything seems to be OK
- testSavepoint1() -
Method in class net.sourceforge.jtds.test.SavepointTest
- tests if rolling back to a savepoint restores the correct DB state
- testSavepoint2() -
Method in class net.sourceforge.jtds.test.SavepointTest
- rollback zu einem savepoint, dann test, ob weiter mit dem safepoint-objekt gearbeitet werden kann
- testSavepoint3() -
Method in class net.sourceforge.jtds.test.SavepointTest
-
- testSavepoint4() -
Method in class net.sourceforge.jtds.test.SavepointTest
- Test to ensure savepoint ids restart at 1.
- testSavepoint5() -
Method in class net.sourceforge.jtds.test.SavepointTest
- Test to ensure savepoints can be created even when no statements have
been issued.
- testSavepoint6() -
Method in class net.sourceforge.jtds.test.SavepointTest
- test for bug [2818256]
ensure a savepoint is still valid after rollback
- testSavepoint7() -
Method in class net.sourceforge.jtds.test.SavepointTest
- roll back to one savepoint and ensure earlier savepoints are still valid
- testSavepoint8() -
Method in class net.sourceforge.jtds.test.SavepointTest
- Test to ensure savepoints cannot be created in auto-commit mode
(Bug [2021839]).
- testSavepoint9() -
Method in class net.sourceforge.jtds.test.SavepointTest
- Test for bug [2021839], connection is rolled back instead of being
committed if setSavepoint is the first operation.
- testSavepointRelease() -
Method in class net.sourceforge.jtds.test.ConnectionJDBC3Test
- Test that temporary procedures created within transactions with
savepoints which are released are still kept in the procedure cache.
- testScrollablePreparedStatement() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
-
- testSelect() -
Method in class net.sourceforge.jtds.test.GenKeyTest
- Test that SELECT statements work correctly with
PreparedStatements created with
RETURN_GENERATED_KEYS.
- testSemicolonProcedures() -
Method in class net.sourceforge.jtds.test.CallableStatementTest
- Test that procedure names containing semicolons are parsed correctly.
- testSetDateObject() -
Method in class net.sourceforge.jtds.test.SunTest
- Test for bug [ 1012307 ] PreparedStatement.setObject(java.util.Date) not working.
- testSetFetchDirectiion() -
Method in class net.sourceforge.jtds.test.SunTest
- Test for SUN bug [ stmt2.testSetFetchDirection04 ]
fetch direction constant not validated.
- testSetFetchSize() -
Method in class net.sourceforge.jtds.test.SunTest
- Test for SUN bug [ resultSet1.testSetFetchSize02 ]
attempt to set non zero fetch size rejected.
- testSetObjectScale() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test for bug [1075977]
setObject() causes SQLException.
- testSocketConcurrency1() -
Method in class net.sourceforge.jtds.test.SAfeTest
-
- testSocketConcurrency2() -
Method in class net.sourceforge.jtds.test.SAfeTest
-
- testSocketConcurrency3() -
Method in class net.sourceforge.jtds.test.SAfeTest
-
- testSocketConcurrency4() -
Method in class net.sourceforge.jtds.test.SAfeTest
- Test running SELECT queries on one
Statement at the same
time as cancel() is called on a concurrent
Statement.
- testSocketConcurrency5() -
Method in class net.sourceforge.jtds.test.JDBC3Test
- Test closing a
ResultSet when it's out of scope.
- testSpHelpSysUsers0032() -
Method in class net.sourceforge.jtds.test.CSUnitTest
-
- testSpecTime() -
Method in class net.sourceforge.jtds.test.AsTest
-
- testSqlComments() -
Method in class net.sourceforge.jtds.test.SunTest
- Test for bug [ 1011650 ] 0.9-rc1: comments get parsed
- testSqlVariant() -
Method in class net.sourceforge.jtds.test.Tds8Test
-
- testStatements0020() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testStreamImage() -
Method in class net.sourceforge.jtds.test.Tds5Test
- Test writing image data from InputStream
- testStreamText() -
Method in class net.sourceforge.jtds.test.Tds5Test
- Test writing text data from Reader
- testStreamUniText() -
Method in class net.sourceforge.jtds.test.Tds5Test
- Test writing unitext data from Reader
- testStringFn() -
Method in class net.sourceforge.jtds.test.SunTest
- Test for scalar string functions.
- testStringOptions() -
Method in class net.sourceforge.jtds.test.DatabaseMetaDataTest
- Test meta data functions that return strings.
- testSybaseISO_1() -
Method in class net.sourceforge.jtds.test.EncodingTest
- Test for bug [1293415] Charset iso_1 is broken for Sybase.
- testTLSResume() -
Method in class net.sourceforge.jtds.test.TlsTest
- Test for problem resuming TLS session with SQL Server (bug [1102505] SSL
TLS resume failure).
- testTableMetaData() -
Method in class net.sourceforge.jtds.test.DatabaseMetaDataTest
- Test for bug [1023984] Protocol error processing table meta data.
- testTableParsing() -
Method in class net.sourceforge.jtds.test.SAfeTest
- Test that the SQL parser doesn't try to parse the table name unless
necessary (or that it is able to parse function calls if it does).
- testTemp() -
Method in class net.sourceforge.jtds.test.UpdateTest
-
- testTextColumns0031() -
Method in class net.sourceforge.jtds.test.CSUnitTest
-
- testThreadInterrupt() -
Method in class net.sourceforge.jtds.test.SAfeTest
- Test for bug [1596743] executeQuery absorbs thread interrupt status
- testTimeZone() -
Method in class net.sourceforge.jtds.test.TimeZoneTest
- Test timezone calendar conversions.
- testTimerStop() -
Method in class net.sourceforge.jtds.test.ConnectionJDBC3Test
- Test for bug [2871274], TimerThread prevents classloader from being GCed.
- testTimestampConversion() -
Method in class net.sourceforge.jtds.test.NtlmAuthTest
-
- testTimestampRange() -
Method in class net.sourceforge.jtds.test.TimestampTest
- Test for bug [1040475] Possible bug when converting to and from
datetime.
- testTimestampTimeZone() -
Method in class net.sourceforge.jtds.test.TimestampTest
- Test for bug [1036059] getTimestamp with Calendar applies tzone offset
wrong way.
- testTimestamps0001() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testTimestamps0004() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testTimestamps0037() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testTimestamps0047() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testTimestamps0048() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testTransactions0010() -
Method in class net.sourceforge.jtds.test.TimestampTest
-
- testTrigger1() -
Method in class net.sourceforge.jtds.test.GenKeyTest
- Test for bug [930305] getGeneratedKeys() does not work with triggers
- testTsEscape() -
Method in class net.sourceforge.jtds.test.CallableStatementTest
- Test for bug [ 1062671 ] SQLParser unable to parse CONVERT(char,{ts ?}
- testUnclosedSocket() -
Method in class net.sourceforge.jtds.test.ConnectionJDBC3Test
- Test for bug [1755448], login failure leaves unclosed sockets.
- testUniText() -
Method in class net.sourceforge.jtds.test.Tds5Test
- Test writing unitext data from memory
- testUnicodeStream() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test that
read() works ok on the stream returned by
ResultSet.getUnicodeStream() (i.e. it doesn't always fill
the buffer, regardless of whether there's available data or not).
- testUnsignedBigInt() -
Method in class net.sourceforge.jtds.test.Tds5Test
- Test Sybase ASE 15+ unsigned bigint data type.
- testUnsignedInt() -
Method in class net.sourceforge.jtds.test.Tds5Test
- Test Sybase ASE 15+ unsigned int data type.
- testUnsignedSmallInt() -
Method in class net.sourceforge.jtds.test.Tds5Test
- Test Sybase ASE 15+ unsigned smallint data type.
- testUnterminatedCommentParsing() -
Method in class net.sourceforge.jtds.test.SAfeTest
- Test for bug [1187927] Driver Hangs on Statement.execute().
- testUpdateCount1() -
Method in class net.sourceforge.jtds.test.PreparedStatementTest
- Test for bug [985754] row count is always 0
- testUpdateNoKeys() -
Method in class net.sourceforge.jtds.test.ClientSideCursorTest
- Test updateable result set where table is not keyed.
- testUpdateRow0011() -
Method in class net.sourceforge.jtds.test.SAfeTest
- Test
ResultSet.updateRow() on updateable result sets.
- testUpdateRowDuplicatesRow() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test that updated rows are marked as deleted and the new values inserted
at the end of the
ResultSet if the primary key is updated.
- testUpdateRowNoChanges() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test for bug [1170777] resultSet.updateRow() fails if no row has been
changed.
- testUpdateRowPosition() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test that after updateRow() the cursor is positioned correctly.
- testUpdateRowUpdatesRow() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test that updated rows are modified in place if the primary key is not
updated.
- testUpdateableClientCursor() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test for bug [1197603] Cursor downgrade error in CachedResultSet --
updateable result sets were incorrectly downgraded to read only forward
only ones when client side cursors were used.
- testUserFn() -
Method in class net.sourceforge.jtds.test.Tds8Test
-
- testVarcharTypes() -
Method in class net.sourceforge.jtds.test.TypeInfoTest
-
- testWriteDate() -
Method in class net.sourceforge.jtds.test.TimestampTest
- Test that
java.sql.Date objects are inserted and retrieved
correctly (ie no time component).
- testWritetext() -
Method in class net.sourceforge.jtds.test.CallableStatementTest
- Test for bug [1152329] Spurious output params assigned (TIMESTMP).
- testXAJoinTran() -
Method in class net.sourceforge.jtds.test.XaTest
- Test to demonstrate the use of the XA_JOIN command.
- testXARecover() -
Method in class net.sourceforge.jtds.test.XaTest
- Test to demonstrate the use of the XA_RECOVER command.
- testXaCommit() -
Method in class net.sourceforge.jtds.test.XaTest
- Test to demonstrate the XA_COMMIT function.
- testXaOnePhaseCommit() -
Method in class net.sourceforge.jtds.test.XaTest
- Test to demonstrate the single phase XA_COMMIT function.
- testXaRollback() -
Method in class net.sourceforge.jtds.test.XaTest
- Test to demonstrate the use of the XA_ROLLBACK command.
- testZeroFetchSize() -
Method in class net.sourceforge.jtds.test.ResultSetTest
- Test for bug [1232733] setFetchSize(0) causes exception.
- testZeroLengthStreams() -
Method in class net.sourceforge.jtds.test.LOBTest
- Test for incorrect handling of zero length streams (bug [1096086] Zero
length streams generate null values).
- test_addDefaultPropertyIfNotSet_DefaultKeyNotSet() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesUnitTest
- Tests that
DefaultProperties.addDefaultPropertyIfNotSet(java.util.Properties, java.lang.String, java.lang.String, java.util.Map)
does not set a default property if the defaultKey is not set.
- test_addDefaultPropertyIfNotSet_DefaultKeySet_PropertyAlreadySet() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesUnitTest
- Tests that
DefaultProperties.addDefaultPropertyIfNotSet(java.util.Properties, java.lang.String, java.lang.String, java.util.Map)
does not set a default property if the property is already set.
- test_addDefaultPropertyIfNotSet_DefaultKeySet_PropertyNotSet() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesUnitTest
- Tests that
DefaultProperties.addDefaultPropertyIfNotSet(java.util.Properties, java.lang.String, java.lang.String, java.util.Map)
sets a default property if the property is not already set.
- test_addDefaultPropertyIfNotSet_PropertyAlreadySet() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesUnitTest
- Tests that
DefaultProperties.addDefaultPropertyIfNotSet(java.util.Properties, java.lang.String, java.lang.String)
does not set a default property if the property is already set.
- test_addDefaultPropertyIfNotSet_PropertyNotSet() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesUnitTest
- Tests that
DefaultProperties.addDefaultPropertyIfNotSet(java.util.Properties, java.lang.String, java.lang.String)
sets a default property if the property is not already set.
- test_appName() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
appName property.
- test_batchSize() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
batchSize property.
- test_bindAddress() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
bindAddress property.
- test_bufferDir() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
bufferDir property.
- test_bufferMaxMemory() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
bufferMaxMemory property.
- test_bufferMinPackets() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
bufferMinPackets property.
- test_cacheMetaData() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
cacheMetaData property.
- test_databaseName() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
databaseName property.
- test_getNamedPipePath_DEFAULT() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesUnitTest
-
- test_getNamedPipePath_INVALID() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesUnitTest
-
- test_getNamedPipePath_SQLSERVER() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesUnitTest
-
- test_getNamedPipePath_SYBASE() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesUnitTest
-
- test_getPropertyInfo_Choices() -
Method in class net.sourceforge.jtds.test.DriverUnitTest
- Tests that the
DriverPropertyInfo array returned from
Driver.getPropertyInfo(String, Properties) contains
the correct choices value on each of the objects.
- test_getPropertyInfo_MatchesMessagesProperties() -
Method in class net.sourceforge.jtds.test.DriverUnitTest
- Tests that the
DriverPropertyInfo array returned from
Driver.getPropertyInfo(String, Properties)
matches the list of properties defined in Messages.properties.
- test_getPropertyInfo_Required() -
Method in class net.sourceforge.jtds.test.DriverUnitTest
- Tests that the
DriverPropertyInfo array returned from
Driver.getPropertyInfo(String, Properties) contains
the correct required value on each of the objects.
- test_getPropertyInfo_ThrowsSQLExceptionWithNonNullProperties() -
Method in class net.sourceforge.jtds.test.DriverUnitTest
- Tests that passing in a non-null properties argument to
Driver.getPropertyInfo(String, Properties)
causes the url to be parsed, which then throws a SQLException.
- test_getPropertyInfo_ThrowsSQLExceptionWithNullProperties() -
Method in class net.sourceforge.jtds.test.DriverUnitTest
- Tests that passing in a null properties argument to
Driver.getPropertyInfo(String, Properties)
causes the url to be parsed, which then throws a SQLException.
- test_getServerType_StringToInteger_Null() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesUnitTest
-
- test_getServerType_StringToInteger_SQLSERVER() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesUnitTest
-
- test_getServerType_StringToInteger_SYBASE() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesUnitTest
-
- test_getServerType_intToString_Null() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesUnitTest
-
- test_getServerType_intToString_SQLSERVER() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesUnitTest
-
- test_getServerType_intToString_SYBASE() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesUnitTest
-
- test_getTdsVersion_StringToInteger_Null() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesUnitTest
-
- test_getTdsVersion_StringToInteger_TDS42() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesUnitTest
-
- test_getTdsVersion_StringToInteger_TDS50() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesUnitTest
-
- test_getTdsVersion_StringToInteger_TDS70() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesUnitTest
-
- test_getTdsVersion_StringToInteger_TDS80() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesUnitTest
-
- test_lastUpdateCount() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
lastUpdateCount property.
- test_lobBuffer() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
lobBuffer property.
- test_loginTimeout() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
loginTimeout property.
- test_macAddress() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
macAddress property.
- test_namedPipe() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
namedPipe property.
- test_packetSize() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
packetSize property.
- test_portNumber() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
portNumber property.
- test_prepareSql() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
prepareSql property.
- test_processId() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
processId property.
- test_progName() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
progName property.
- test_sendStringParametersAsUnicode() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
sendStringParametersAsUnicode property.
- test_serverType() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
serverType property.
- test_socketKeepAlive() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
socketKeepAlive property.
- test_socketTimeout() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
socketTimeout property.
- test_tcpNoDelay() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
tcpNoDelay property.
- test_tds() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
tds (version) property.
- test_unpackProperties_invalidIntegerProperty() -
Method in class net.sourceforge.jtds.test.ConnectionJDBC2UnitTest
- Test that an
SQLException is thrown when
parsing invalid integer (and long) properties.
- test_useCursors() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
useCursors property.
- test_useJCIFS() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
useJCIFS property.
- test_useLOBs() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
useLOBs property.
- test_wsid() -
Method in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Test the
wsid property.
- tester -
Variable in class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
- Object used to run all of the tests.
- testxx0029() -
Method in class net.sourceforge.jtds.test.CSUnitTest
-
- testxx0050() -
Method in class net.sourceforge.jtds.test.CSUnitTest
-
- testxx0051() -
Method in class net.sourceforge.jtds.test.CSUnitTest
-
- testxx0052() -
Method in class net.sourceforge.jtds.test.CSUnitTest
-
- testxx0053() -
Method in class net.sourceforge.jtds.test.CSUnitTest
-
- testxx0055() -
Method in class net.sourceforge.jtds.test.CSUnitTest
-
- testxx0057() -
Method in class net.sourceforge.jtds.test.CSUnitTest
-
- testxx0059() -
Method in class net.sourceforge.jtds.test.CSUnitTest
-
- testxx005x() -
Method in class net.sourceforge.jtds.test.CSUnitTest
-
- textSize -
Variable in class net.sourceforge.jtds.jdbc.ConnectionJDBC2
- Connection's current maximum field size limit.
- thisInstance -
Static variable in class net.sourceforge.jtds.util.SSPIJNIClient
- Singleton instance.
- threadId -
Variable in class net.sourceforge.jtds.test.PreparedStatementTest.TestMultiThread
-
- time -
Variable in class net.sourceforge.jtds.jdbc.DateTime
- The time component of the server datetime value.
- time -
Variable in class net.sourceforge.jtds.util.TimerThread.TimerRequest
- The time when this timeout will expire.
- timeFromZone(Date, Calendar) -
Static method in class net.sourceforge.jtds.jdbc.Support
- Convert a timestamp from a different Timezone.
- timeMask -
Static variable in class net.sourceforge.jtds.jdbc.SQLParser
- Syntax mask for time escape.
- timeToZone(Date, Calendar) -
Static method in class net.sourceforge.jtds.jdbc.Support
- Convert a timestamp to a different Timezone.
- timeValue -
Variable in class net.sourceforge.jtds.jdbc.DateTime
- Cached value of the datetime as a
java.sql.Time.
- timeout -
Variable in class net.sourceforge.jtds.jdbc.MSSqlServerInfo
-
- timerExpired() -
Method in interface net.sourceforge.jtds.util.TimerThread.TimerListener
- Event to be fired when the timeout expires.
- timerList -
Variable in class net.sourceforge.jtds.util.TimerThread
- List of
TimerRequests to execute, ordered by time.
- timestampMask -
Static variable in class net.sourceforge.jtds.jdbc.SQLParser
- Syntax mask for timestamp escape.
- toBytesXid(Xid) -
Static method in class net.sourceforge.jtds.jdbc.XASupport
- Format an XA transaction ID into a 140 byte array.
- toDate() -
Method in class net.sourceforge.jtds.jdbc.DateTime
- Retrieves the current datetime value as a Date.
- toHex(byte[]) -
Static method in class net.sourceforge.jtds.jdbc.Support
- Convert a byte[] object to a hex string.
- toObject() -
Method in class net.sourceforge.jtds.jdbc.DateTime
- Retrieves the current datetime value as a Time, Date or Timestamp.
- toString() -
Method in class net.sourceforge.jtds.jdbc.CharsetInfo
-
- toString() -
Method in class net.sourceforge.jtds.jdbc.DateTime
- Retrieves the current datetime value as a String.
- toString() -
Method in class net.sourceforge.jtds.jdbc.Driver
- Returns the string form of the object.
- toString() -
Method in class net.sourceforge.jtds.jdbc.JtdsPreparedStatement
- Returns the SQL command provided at construction time.
- toString() -
Method in class net.sourceforge.jtds.jdbc.ProcEntry
- Retrieves the procedure or handle name.
- toString() -
Method in class net.sourceforge.jtds.jdbc.TypeInfo
-
- toString() -
Method in class net.sourceforge.jtds.jdbc.UniqueIdentifier
- Retrieve the unique identifier as a formatted string.
- toString() -
Method in class net.sourceforge.jtds.jdbcx.JtdsXid
-
- toTime() -
Method in class net.sourceforge.jtds.jdbc.DateTime
- Retrieves the current datetime value as a Time.
- toTimestamp() -
Method in class net.sourceforge.jtds.jdbc.DateTime
- Retrieves the current datetime value as a Timestamp.
- token -
Variable in class net.sourceforge.jtds.jdbc.TdsCore.TdsToken
- The current TDS token byte.
- totalSize -
Variable in class net.sourceforge.jtds.ssl.TdsTlsOutputStream
-
- totrot -
Static variable in class net.sourceforge.jtds.util.DESEngine
-
- transactionIsolation -
Variable in class net.sourceforge.jtds.jdbc.ConnectionJDBC2
- Default transaction isolation level.
- truncate(long) -
Method in class net.sourceforge.jtds.jdbc.BlobImpl
-
- truncate(long) -
Method in class net.sourceforge.jtds.jdbc.ClobImpl
-
- truncate(long) -
Method in class net.sourceforge.jtds.util.BlobBuffer
- Truncates the BLOB buffer to the specified size.
- trustManagers() -
Static method in class net.sourceforge.jtds.ssl.SocketFactories.TdsTlsSocketFactory
-
- trustManagers() -
Static method in class net.sourceforge.jtds.ssl.SocketFactoriesSUN.TdsTlsSocketFactory
-
- tsValue -
Variable in class net.sourceforge.jtds.jdbc.DateTime
- Cached value of the datetime as a
java.sql.Timestamp.
- type -
Variable in class net.sourceforge.jtds.jdbc.ProcEntry
- Type of statement referenced by this entry.
- typeInfoRs -
Variable in class net.sourceforge.jtds.test.DatabaseMetaDataTypeInfoTest
-
- typeMap -
Static variable in class net.sourceforge.jtds.jdbc.Support
- Convert java clases to java.sql.Type constant.
- typeName -
Variable in class net.sourceforge.jtds.jdbc.TypeInfo
-
- typemap -
Static variable in class net.sourceforge.jtds.test.DatabaseTestCase
-
- types -
Static variable in class net.sourceforge.jtds.jdbc.TdsData
- Array of TDS data type descriptors.
useCursors property.
useJCIFS property.
useLOBs property.
user property.
sendStringParametersAsUnicode property.
TimerThread.nextTimeout.
ResultSet.rowUpdated .
useCursors connection property has been set, the first
word in the SQL query is either SELECT or EXEC/EXECUTE and no generated
keys are returned.
wsid property.
XaEmulation property.
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Deprecated Methods | |
| net.sourceforge.jtds.util.Logger.setActive(boolean)
Use the JDBC standard mechanisms to enable logging. |
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| net.sourceforge.* |
| net.sourceforge.jtds.jdbc.CharsetInfo | ||
private static final java.lang.String |
CHARSETS_RESOURCE_NAME |
"net/sourceforge/jtds/jdbc/Charsets.properties" |
| net.sourceforge.jtds.jdbc.ClobImpl | ||
private static final java.lang.String |
EMPTY_CLOB |
"" |
| net.sourceforge.jtds.jdbc.ConnectionJDBC2 | ||
private static final java.lang.String |
SQL_SERVER_65_CHARSET_QUERY |
"select name from master.dbo.syscharsets where id = (select csid from master.dbo.syscharsets, master.dbo.sysconfigures where config=1123 and id = value)" |
private static final java.lang.String |
SQL_SERVER_INITIAL_SQL |
"SELECT @@MAX_PRECISION\r\nSET TRANSACTION ISOLATION LEVEL READ COMMITTED\r\nSET IMPLICIT_TRANSACTIONS OFF\r\nSET QUOTED_IDENTIFIER ON\r\nSET TEXTSIZE 2147483647" |
private static final java.lang.String |
SYBASE_INITIAL_SQL |
"SET TRANSACTION ISOLATION LEVEL 1\r\nSET CHAINED OFF\r\nSET QUOTED_IDENTIFIER ON\r\nSET TEXTSIZE 2147483647" |
private static final java.lang.String |
SYBASE_SERVER_CHARSET_QUERY |
"select name from master.dbo.syscharsets where id = (select value from master.dbo.sysconfigures where config=131)" |
public static final int |
TRANSACTION_SNAPSHOT |
4096 |
| net.sourceforge.jtds.jdbc.DateTime | ||
static final int |
DATE_NOT_USED |
-2147483648 |
static final int |
TIME_NOT_USED |
-2147483648 |
| net.sourceforge.jtds.jdbc.DefaultProperties | ||
public static final java.lang.String |
APP_NAME |
"jTDS" |
public static final java.lang.String |
BATCH_SIZE_SQLSERVER |
"0" |
public static final java.lang.String |
BATCH_SIZE_SYBASE |
"1000" |
public static final java.lang.String |
BIND_ADDRESS |
"" |
public static final java.lang.String |
BUFFER_MAX_MEMORY |
"1024" |
public static final java.lang.String |
BUFFER_MIN_PACKETS |
"8" |
public static final java.lang.String |
CACHEMETA |
"false" |
public static final java.lang.String |
CHARSET |
"" |
public static final java.lang.String |
DATABASE_NAME |
"" |
public static final java.lang.String |
DOMAIN |
"" |
public static final java.lang.String |
INSTANCE |
"" |
public static final java.lang.String |
LANGUAGE |
"" |
public static final java.lang.String |
LAST_UPDATE_COUNT |
"true" |
public static final java.lang.String |
LOB_BUFFER_SIZE |
"32768" |
public static final java.lang.String |
LOGFILE |
"" |
public static final java.lang.String |
LOGIN_TIMEOUT |
"0" |
public static final java.lang.String |
MAC_ADDRESS |
"000000000000" |
public static final java.lang.String |
MAX_STATEMENTS |
"500" |
public static final java.lang.String |
NAMED_PIPE |
"false" |
public static final java.lang.String |
NAMED_PIPE_PATH_SQLSERVER |
"/sql/query" |
public static final java.lang.String |
NAMED_PIPE_PATH_SYBASE |
"/sybase/query" |
public static final java.lang.String |
PACKET_SIZE_50 |
"0" |
public static final java.lang.String |
PACKET_SIZE_70_80 |
"0" |
public static final java.lang.String |
PASSWORD |
"" |
public static final java.lang.String |
PORT_NUMBER_SQLSERVER |
"1433" |
public static final java.lang.String |
PORT_NUMBER_SYBASE |
"7100" |
public static final java.lang.String |
PROCESS_ID |
"123" |
public static final java.lang.String |
PROG_NAME |
"jTDS" |
public static final java.lang.String |
SERVER_TYPE_SQLSERVER |
"sqlserver" |
public static final java.lang.String |
SERVER_TYPE_SYBASE |
"sybase" |
public static final java.lang.String |
SOCKET_KEEPALIVE |
"false" |
public static final java.lang.String |
SOCKET_TIMEOUT |
"0" |
public static final java.lang.String |
SSL |
"off" |
public static final java.lang.String |
TCP_NODELAY |
"true" |
public static final java.lang.String |
TDS_VERSION_42 |
"4.2" |
public static final java.lang.String |
TDS_VERSION_50 |
"5.0" |
public static final java.lang.String |
TDS_VERSION_70 |
"7.0" |
public static final java.lang.String |
TDS_VERSION_80 |
"8.0" |
public static final java.lang.String |
USE_UNICODE |
"true" |
public static final java.lang.String |
USECURSORS |
"false" |
public static final java.lang.String |
USEJCIFS |
"false" |
public static final java.lang.String |
USELOBS |
"true" |
public static final java.lang.String |
USER |
"" |
public static final java.lang.String |
WSID |
"" |
public static final java.lang.String |
XAEMULATION |
"true" |
| net.sourceforge.jtds.jdbc.Driver | ||
public static final java.lang.String |
APPNAME |
"prop.appname" |
public static final java.lang.String |
BATCHSIZE |
"prop.batchsize" |
public static final java.lang.String |
BINDADDRESS |
"prop.bindaddress" |
public static final java.lang.String |
BUFFERDIR |
"prop.bufferdir" |
public static final java.lang.String |
BUFFERMAXMEMORY |
"prop.buffermaxmemory" |
public static final java.lang.String |
BUFFERMINPACKETS |
"prop.bufferminpackets" |
public static final java.lang.String |
CACHEMETA |
"prop.cachemetadata" |
public static final java.lang.String |
CHARSET |
"prop.charset" |
public static final java.lang.String |
DATABASENAME |
"prop.databasename" |
public static final java.lang.String |
DOMAIN |
"prop.domain" |
public static final java.lang.String |
INSTANCE |
"prop.instance" |
public static final java.lang.String |
LANGUAGE |
"prop.language" |
public static final java.lang.String |
LASTUPDATECOUNT |
"prop.lastupdatecount" |
public static final java.lang.String |
LOBBUFFER |
"prop.lobbuffer" |
public static final java.lang.String |
LOGFILE |
"prop.logfile" |
public static final java.lang.String |
LOGINTIMEOUT |
"prop.logintimeout" |
public static final java.lang.String |
MACADDRESS |
"prop.macaddress" |
static final int |
MAJOR_VERSION |
1 |
public static final java.lang.String |
MAXSTATEMENTS |
"prop.maxstatements" |
static final int |
MINOR_VERSION |
2 |
static final java.lang.String |
MISC_VERSION |
".5" |
public static final java.lang.String |
NAMEDPIPE |
"prop.namedpipe" |
public static final java.lang.String |
PACKETSIZE |
"prop.packetsize" |
public static final java.lang.String |
PASSWORD |
"prop.password" |
public static final java.lang.String |
PORTNUMBER |
"prop.portnumber" |
public static final java.lang.String |
PREPARESQL |
"prop.preparesql" |
public static final java.lang.String |
PROCESSID |
"prop.processid" |
public static final java.lang.String |
PROGNAME |
"prop.progname" |
public static final java.lang.String |
SENDSTRINGPARAMETERSASUNICODE |
"prop.useunicode" |
public static final java.lang.String |
SERVERNAME |
"prop.servername" |
public static final java.lang.String |
SERVERTYPE |
"prop.servertype" |
public static final java.lang.String |
SOKEEPALIVE |
"prop.sokeepalive" |
public static final java.lang.String |
SOTIMEOUT |
"prop.sotimeout" |
public static final int |
SQLSERVER |
1 |
public static final java.lang.String |
SSL |
"prop.ssl" |
public static final int |
SYBASE |
2 |
public static final java.lang.String |
TCPNODELAY |
"prop.tcpnodelay" |
public static final java.lang.String |
TDS |
"prop.tds" |
public static final int |
TDS42 |
1 |
public static final int |
TDS50 |
2 |
public static final int |
TDS70 |
3 |
public static final int |
TDS80 |
4 |
public static final int |
TDS81 |
5 |
public static final java.lang.String |
USECURSORS |
"prop.usecursors" |
public static final java.lang.String |
USEJCIFS |
"prop.usejcifs" |
public static final java.lang.String |
USELOBS |
"prop.uselobs" |
public static final java.lang.String |
USENTLMV2 |
"prop.usentlmv2" |
public static final java.lang.String |
USER |
"prop.user" |
public static final java.lang.String |
WSID |
"prop.wsid" |
public static final java.lang.String |
XAEMULATION |
"prop.xaemulation" |
| net.sourceforge.jtds.jdbc.JtdsDatabaseMetaData | ||
static final int |
sqlStateXOpen |
1 |
| net.sourceforge.jtds.jdbc.JtdsResultSet | ||
static final int |
CLOSE_CURSORS_AT_COMMIT |
2 |
static final int |
HOLD_CURSORS_OVER_COMMIT |
1 |
protected static final int |
INITIAL_ROW_COUNT |
1000 |
protected static final int |
POS_AFTER_LAST |
-1 |
protected static final int |
POS_BEFORE_FIRST |
0 |
| net.sourceforge.jtds.jdbc.JtdsStatement | ||
static final int |
BOOLEAN |
16 |
static final int |
CLOSE_ALL_RESULTS |
3 |
static final int |
CLOSE_CURRENT_RESULT |
1 |
static final int |
DATALINK |
70 |
static final int |
DEFAULT_FETCH_SIZE |
100 |
static final int |
KEEP_CURRENT_RESULT |
2 |
static final int |
NO_GENERATED_KEYS |
2 |
static final int |
RETURN_GENERATED_KEYS |
1 |
| net.sourceforge.jtds.jdbc.Messages | ||
private static final java.lang.String |
DEFAULT_RESOURCE |
"net.sourceforge.jtds.jdbc.Messages" |
| net.sourceforge.jtds.jdbc.MSCursorResultSet | ||
private static final int |
CURSOR_CONCUR_OPTIMISTIC |
4 |
private static final int |
CURSOR_CONCUR_OPTIMISTIC_VALUES |
8 |
private static final int |
CURSOR_CONCUR_READ_ONLY |
1 |
private static final int |
CURSOR_CONCUR_SCROLL_LOCKS |
2 |
private static final int |
CURSOR_TYPE_AUTO_FETCH |
8192 |
private static final int |
CURSOR_TYPE_DYNAMIC |
2 |
private static final int |
CURSOR_TYPE_FASTFORWARDONLY |
16 |
private static final int |
CURSOR_TYPE_FORWARD |
4 |
private static final int |
CURSOR_TYPE_KEYSET |
1 |
private static final int |
CURSOR_TYPE_PARAMETERIZED |
4096 |
private static final int |
CURSOR_TYPE_STATIC |
8 |
| net.sourceforge.jtds.jdbc.net.sourceforge.jtds.jdbc.ParamInfo | ||
static final int |
INPUT |
0 |
static final int |
OUTPUT |
1 |
static final int |
RETVAL |
2 |
static final int |
UNICODE |
4 |
| net.sourceforge.jtds.jdbc.ProcEntry | ||
public static final int |
CURSOR |
3 |
public static final int |
PREP_FAILED |
4 |
public static final int |
PREPARE |
2 |
public static final int |
PROCEDURE |
1 |
| net.sourceforge.jtds.jdbc.net.sourceforge.jtds.jdbc.SharedSocket | ||
private static final int |
TDS_DONE_LEN |
9 |
private static final int |
TDS_DONE_TOKEN |
253 |
private static final int |
TDS_HDR_LEN |
8 |
| net.sourceforge.jtds.jdbc.TdsCore | ||
private static final int |
ASYNC_CANCEL |
0 |
public static final byte |
CANCEL_PKT |
6 |
public static final int |
DEFAULT_MIN_PKT_SIZE_TDS70 |
4096 |
static final byte |
DONE_CANCEL |
32 |
private static final byte |
DONE_END_OF_RESPONSE |
-128 |
private static final byte |
DONE_ERROR |
2 |
private static final byte |
DONE_MORE_RESULTS |
1 |
private static final byte |
DONE_ROW_COUNT |
16 |
public static final int |
EXECUTE_SQL |
2 |
public static final byte |
LOGIN_PKT |
2 |
public static final int |
MAX_PKT_SIZE |
32768 |
public static final int |
MIN_PKT_SIZE |
512 |
public static final byte |
MSDTC_PKT |
14 |
public static final byte |
MSLOGIN_PKT |
16 |
public static final byte |
NTLMAUTH_PKT |
17 |
public static final int |
PKT_HDR_LEN |
8 |
public static final byte |
PRELOGIN_PKT |
18 |
public static final int |
PREPARE |
3 |
public static final byte |
QUERY_PKT |
1 |
public static final byte |
REPLY_PKT |
4 |
public static final byte |
RPC_PKT |
3 |
public static final int |
SSL_CLIENT_FORCE_ENCRYPT |
1 |
public static final int |
SSL_ENCRYPT_LOGIN |
0 |
public static final int |
SSL_NO_ENCRYPT |
2 |
public static final int |
SSL_SERVER_FORCE_ENCRYPT |
3 |
static final int |
SYB_BIGINT |
64 |
static final int |
SYB_BITNULL |
4 |
static final int |
SYB_DATETIME |
2 |
static final int |
SYB_EXTCOLINFO |
8 |
static final int |
SYB_LONGDATA |
1 |
static final int |
SYB_UNICODE |
16 |
static final int |
SYB_UNITEXT |
32 |
public static final byte |
SYBQUERY_PKT |
15 |
private static final byte |
TDS_ALTROW |
-45 |
private static final byte |
TDS_AUTH_TOKEN |
-19 |
private static final byte |
TDS_CAP_TOKEN |
-30 |
private static final byte |
TDS_CLOSE_TOKEN |
113 |
private static final byte |
TDS_COLFMT_TOKEN |
-95 |
private static final byte |
TDS_COLINFO_TOKEN |
-91 |
private static final byte |
TDS_COLNAME_TOKEN |
-96 |
private static final byte |
TDS_COMP_NAMES_TOKEN |
-89 |
private static final byte |
TDS_COMP_RESULT_TOKEN |
-88 |
private static final byte |
TDS_CONTROL_TOKEN |
-82 |
private static final byte |
TDS_DBRPC_TOKEN |
-26 |
private static final byte |
TDS_DONE_TOKEN |
-3 |
private static final byte |
TDS_DONEINPROC_TOKEN |
-1 |
private static final byte |
TDS_DONEPROC_TOKEN |
-2 |
private static final byte |
TDS_ENV_CHARSET |
3 |
private static final byte |
TDS_ENV_DATABASE |
1 |
private static final byte |
TDS_ENV_LANG |
2 |
private static final byte |
TDS_ENV_LCID |
5 |
private static final byte |
TDS_ENV_PACKSIZE |
4 |
private static final byte |
TDS_ENV_SQLCOLLATION |
7 |
private static final byte |
TDS_ENVCHANGE_TOKEN |
-29 |
private static final byte |
TDS_ERROR_TOKEN |
-86 |
private static final byte |
TDS_INFO_TOKEN |
-85 |
private static final byte |
TDS_LANG_TOKEN |
33 |
private static final byte |
TDS_LOGINACK_TOKEN |
-83 |
private static final byte |
TDS_MSG50_TOKEN |
-27 |
private static final byte |
TDS_OFFSETS_TOKEN |
120 |
private static final byte |
TDS_OPTIONCMD_TOKEN |
-90 |
private static final byte |
TDS_ORDER_TOKEN |
-87 |
private static final byte |
TDS_PARAM_TOKEN |
-84 |
private static final byte |
TDS_PROCID |
124 |
private static final byte |
TDS_RESULT_TOKEN |
-18 |
private static final byte |
TDS_RETURNSTATUS_TOKEN |
121 |
private static final byte |
TDS_ROW_TOKEN |
-47 |
private static final byte |
TDS_TABNAME_TOKEN |
-92 |
private static final byte |
TDS5_DYNAMIC_TOKEN |
-25 |
private static final byte |
TDS5_PARAMFMT_TOKEN |
-20 |
private static final byte |
TDS5_PARAMFMT2_TOKEN |
32 |
private static final byte |
TDS5_PARAMS_TOKEN |
-41 |
private static final byte |
TDS5_WIDE_RESULT |
97 |
private static final byte |
TDS7_COMP_RESULT_TOKEN |
-120 |
private static final byte |
TDS7_RESULT_TOKEN |
-127 |
public static final int |
TEMPORARY_STORED_PROCEDURES |
1 |
private static final int |
TIMEOUT_CANCEL |
1 |
public static final int |
UNPREPARED |
0 |
| net.sourceforge.jtds.jdbc.TdsData | ||
static final int |
DEFAULT_PRECISION_28 |
28 |
static final int |
DEFAULT_PRECISION_38 |
38 |
static final int |
DEFAULT_SCALE |
10 |
private static final int |
MS_LONGVAR_MAX |
8000 |
private static final int |
SYB_CHUNK_SIZE |
8192 |
private static final int |
SYB_LONGVAR_MAX |
16384 |
private static final int |
SYBBINARY |
45 |
private static final int |
SYBBIT |
50 |
private static final int |
SYBBITN |
104 |
private static final int |
SYBCHAR |
47 |
private static final int |
SYBDATE |
49 |
private static final int |
SYBDATEN |
123 |
private static final int |
SYBDATETIME |
61 |
private static final int |
SYBDATETIME4 |
58 |
private static final int |
SYBDATETIMN |
111 |
private static final int |
SYBDECIMAL |
106 |
private static final int |
SYBFLT8 |
62 |
private static final int |
SYBFLTN |
109 |
private static final int |
SYBIMAGE |
34 |
private static final int |
SYBINT1 |
48 |
private static final int |
SYBINT2 |
52 |
private static final int |
SYBINT4 |
56 |
private static final int |
SYBINT8 |
127 |
private static final int |
SYBINTN |
38 |
private static final int |
SYBLONGBINARY |
225 |
static final int |
SYBLONGDATA |
36 |
private static final int |
SYBMONEY |
60 |
private static final int |
SYBMONEY4 |
122 |
private static final int |
SYBMONEYN |
110 |
private static final int |
SYBNTEXT |
99 |
private static final int |
SYBNUMERIC |
108 |
private static final int |
SYBNVARCHAR |
103 |
private static final int |
SYBREAL |
59 |
private static final int |
SYBSINT1 |
64 |
private static final int |
SYBSINT8 |
191 |
private static final int |
SYBTEXT |
35 |
private static final int |
SYBTIME |
51 |
private static final int |
SYBTIMEN |
147 |
private static final int |
SYBUINT2 |
65 |
private static final int |
SYBUINT4 |
66 |
private static final int |
SYBUINT8 |
67 |
private static final int |
SYBUINTN |
68 |
private static final int |
SYBUNIQUE |
36 |
private static final int |
SYBUNITEXT |
174 |
private static final int |
SYBVARBINARY |
37 |
private static final int |
SYBVARCHAR |
39 |
private static final int |
SYBVARIANT |
98 |
private static final int |
SYBVOID |
31 |
private static final int |
UDT_BINARY |
3 |
private static final int |
UDT_CHAR |
1 |
private static final int |
UDT_LONGSYSNAME |
42 |
private static final int |
UDT_NCHAR |
24 |
private static final int |
UDT_NEWSYSNAME |
256 |
private static final int |
UDT_NVARCHAR |
25 |
private static final int |
UDT_SYSNAME |
18 |
private static final int |
UDT_TIMESTAMP |
80 |
private static final int |
UDT_UNICHAR |
34 |
private static final int |
UDT_UNITEXT |
36 |
private static final int |
UDT_UNIVARCHAR |
35 |
private static final int |
UDT_VARBINARY |
4 |
private static final int |
UDT_VARCHAR |
2 |
private static final int |
VAR_MAX |
255 |
private static final int |
XSYBBINARY |
173 |
private static final int |
XSYBCHAR |
175 |
private static final int |
XSYBNCHAR |
239 |
private static final int |
XSYBNVARCHAR |
231 |
private static final int |
XSYBVARBINARY |
165 |
private static final int |
XSYBVARCHAR |
167 |
| net.sourceforge.jtds.jdbc.TypeInfo | ||
static final int |
NUM_COLS |
18 |
| net.sourceforge.jtds.jdbc.XASupport | ||
private static final java.lang.String |
TM_ID |
"TM=JTDS,RmRecoveryGuid=434CDE1A-F747-4942-9584-04937455CAB4" |
private static final int |
XA_CLOSE |
2 |
private static final int |
XA_COMMIT |
7 |
private static final int |
XA_COMPLETE |
10 |
private static final int |
XA_END |
4 |
private static final int |
XA_FORGET |
9 |
private static final int |
XA_OPEN |
1 |
private static final int |
XA_PREPARE |
6 |
private static final int |
XA_RECOVER |
8 |
private static final int |
XA_RMID |
1 |
private static final int |
XA_ROLLBACK |
5 |
private static final int |
XA_START |
3 |
private static final int |
XA_TRACE |
0 |
| net.sourceforge.jtds.jdbc.cache.ProcedureCache | ||
private static final int |
MAX_INITIAL_SIZE |
50 |
| net.sourceforge.jtds.jdbcx.JtdsDataSource | ||
static final long |
serialVersionUID |
266240l |
| net.sourceforge.jtds.jdbcx.JtdsXid | ||
public static final int |
XID_SIZE |
140 |
| net.sourceforge.jtds.ssl.Ssl | ||
public static final int |
HS_HEADER_SIZE |
4 |
public static final java.lang.String |
SSL_AUTHENTICATE |
"authenticate" |
public static final java.lang.String |
SSL_OFF |
"off" |
public static final java.lang.String |
SSL_REQUEST |
"request" |
public static final java.lang.String |
SSL_REQUIRE |
"require" |
public static final int |
TLS_HEADER_SIZE |
5 |
public static final byte |
TYPE_ALERT |
21 |
public static final byte |
TYPE_APPLICATIONDATA |
23 |
public static final byte |
TYPE_CHANGECIPHERSPEC |
20 |
public static final int |
TYPE_CLIENTHELLO |
1 |
public static final int |
TYPE_CLIENTKEYEXCHANGE |
16 |
public static final byte |
TYPE_HANDSHAKE |
22 |
| net.sourceforge.jtds.test.DefaultPropertiesTestLibrary | ||
private static final java.lang.String |
URL_SQLSERVER |
"jdbc:jtds:sqlserver://servername" |
private static final java.lang.String |
URL_SYBASE |
"jdbc:jtds:sybase://servername" |
| net.sourceforge.jtds.test.LargeLOBTest | ||
private static final int |
LOB_LENGTH |
100000000 |
| net.sourceforge.jtds.test.LOBTest | ||
private static final int |
LOB_LENGTH |
8000 |
| net.sourceforge.jtds.test.net.sourceforge.jtds.test.LOBTest.RealInputStream | ||
static final int |
LENGTH |
10000 |
| net.sourceforge.jtds.test.net.sourceforge.jtds.test.PreparedStatementTest.TestMultiThread | ||
static final int |
LOOP_MAX |
10 |
static final int |
ROWS_MAX |
10 |
static final int |
THREAD_MAX |
10 |
| net.sourceforge.jtds.test.SupportUnitTest | ||
private static final java.lang.String |
SYSTEM_PROPRETY_OS_NAME |
"os.name" |
| net.sourceforge.jtds.test.TestBase | ||
private static final java.lang.String |
CONNECTION_PROPERTIES |
"conf/connection.properties" |
| net.sourceforge.jtds.util.BlobBuffer | ||
private static final int |
BYTE_MASK |
1023 |
private static final int |
INVALID_PAGE |
-1 |
private static final int |
MAX_BUF_INC |
16384 |
private static final int |
PAGE_MASK |
-1024 |
private static final int |
PAGE_SIZE |
1024 |
| net.sourceforge.jtds.util.DESEngine | ||
protected static final int |
BLOCK_SIZE |
8 |
| net.sourceforge.jtds.util.MD4Digest | ||
private static final int |
DIGEST_LENGTH |
16 |
private static final int |
S11 |
3 |
private static final int |
S12 |
7 |
private static final int |
S13 |
11 |
private static final int |
S14 |
19 |
private static final int |
S21 |
3 |
private static final int |
S22 |
5 |
private static final int |
S23 |
9 |
private static final int |
S24 |
13 |
private static final int |
S31 |
3 |
private static final int |
S32 |
9 |
private static final int |
S33 |
11 |
private static final int |
S34 |
15 |
| net.sourceforge.jtds.util.MD5Digest | ||
private static final int |
DIGEST_LENGTH |
16 |
private static final int |
S11 |
7 |
private static final int |
S12 |
12 |
private static final int |
S13 |
17 |
private static final int |
S14 |
22 |
private static final int |
S21 |
5 |
private static final int |
S22 |
9 |
private static final int |
S23 |
14 |
private static final int |
S24 |
20 |
private static final int |
S31 |
4 |
private static final int |
S32 |
11 |
private static final int |
S33 |
16 |
private static final int |
S34 |
23 |
private static final int |
S41 |
6 |
private static final int |
S42 |
10 |
private static final int |
S43 |
15 |
private static final int |
S44 |
21 |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
libjtds-java-1.2.5.orig/doc/allclasses-frame.html 0000644 0001750 0001750 00000052403 11316672660 021263 0 ustar martin martin
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
SSL settings
| Field Summary | |
static int |
HS_HEADER_SIZE
TLS Hand shake Header Size. |
static java.lang.String |
SSL_AUTHENTICATE
SSL is required and the server must return a certificate signed by a client-trusted authority. |
static java.lang.String |
SSL_OFF
SSL is not used. |
static java.lang.String |
SSL_REQUEST
SSL is requested; a plain socket is used if SSL is not available. |
static java.lang.String |
SSL_REQUIRE
SSL is required; an exception if thrown if SSL is not available. |
static int |
TLS_HEADER_SIZE
Size of TLS record header. |
static byte |
TYPE_ALERT
TLS Alert record type. |
static byte |
TYPE_APPLICATIONDATA
TLS Application data record. |
static byte |
TYPE_CHANGECIPHERSPEC
TLS Change Cipher Spec record type. |
static int |
TYPE_CLIENTHELLO
TLS Hand shake client hello sub type. |
static int |
TYPE_CLIENTKEYEXCHANGE
TLS Hand shake client key exchange sub type. |
static byte |
TYPE_HANDSHAKE
TLS Handshake record. |
| Field Detail |
public static final java.lang.String SSL_OFF
public static final java.lang.String SSL_REQUEST
public static final java.lang.String SSL_REQUIRE
public static final java.lang.String SSL_AUTHENTICATE
public static final int TLS_HEADER_SIZE
public static final byte TYPE_CHANGECIPHERSPEC
public static final byte TYPE_ALERT
public static final byte TYPE_HANDSHAKE
public static final byte TYPE_APPLICATIONDATA
public static final int HS_HEADER_SIZE
public static final int TYPE_CLIENTKEYEXCHANGE
public static final int TYPE_CLIENTHELLO
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.ssl.SocketFactories
Used for acquiring a socket factory when SSL is enabled.
| Nested Class Summary | |
private static class |
SocketFactories.TdsTlsSocketFactory
The socket factory for creating sockets based on the SSL setting. |
| Constructor Summary | |
SocketFactories()
|
|
| Method Summary | |
static javax.net.SocketFactory |
getSocketFactory(java.lang.String ssl,
java.net.Socket socket)
Returns a socket factory, the behavior of which will depend on the SSL setting and whether or not the DB server supports SSL. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Constructor Detail |
public SocketFactories()
| Method Detail |
public static javax.net.SocketFactory getSocketFactory(java.lang.String ssl,
java.net.Socket socket)
ssl - the SSL settingsocket - plain TCP/IP socket to wrap
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjava.net.Socket
net.sourceforge.jtds.ssl.TdsTlsSocket
A socket that mediates between JSSE and the DB server.
| Field Summary | |
private java.net.Socket |
delegate
|
private java.io.InputStream |
istm
|
private java.io.OutputStream |
ostm
|
| Fields inherited from class java.net.Socket |
|
| Constructor Summary | |
(package private) |
TdsTlsSocket(java.net.Socket delegate)
Constructs a TdsTlsSocket around an underlying socket. |
| Method Summary | |
void |
close()
|
java.io.InputStream |
getInputStream()
|
java.io.OutputStream |
getOutputStream()
|
boolean |
isConnected()
|
void |
setKeepAlive(boolean keepAlive)
|
void |
setSoTimeout(int timeout)
|
void |
setTcpNoDelay(boolean on)
|
| Methods inherited from class java.net.Socket |
bind, connect, connect, getChannel, getInetAddress, getKeepAlive, getLocalAddress, getLocalPort, getLocalSocketAddress, getOOBInline, getPort, getReceiveBufferSize, getRemoteSocketAddress, getReuseAddress, getSendBufferSize, getSoLinger, getSoTimeout, getTcpNoDelay, getTrafficClass, isBound, isClosed, isInputShutdown, isOutputShutdown, sendUrgentData, setOOBInline, setReceiveBufferSize, setReuseAddress, setSendBufferSize, setSocketImplFactory, setSoLinger, setTrafficClass, shutdownInput, shutdownOutput, toString |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
private final java.net.Socket delegate
private final java.io.InputStream istm
private final java.io.OutputStream ostm
| Constructor Detail |
TdsTlsSocket(java.net.Socket delegate)
throws java.io.IOException
delegate - the underlying socket| Method Detail |
public void close()
throws java.io.IOException
java.io.IOException
public java.io.InputStream getInputStream()
throws java.io.IOException
java.io.IOException
public java.io.OutputStream getOutputStream()
throws java.io.IOException
java.io.IOExceptionpublic boolean isConnected()
public void setSoTimeout(int timeout)
throws java.net.SocketException
java.net.SocketException
public void setKeepAlive(boolean keepAlive)
throws java.net.SocketException
java.net.SocketException
public void setTcpNoDelay(boolean on)
throws java.net.SocketException
java.net.SocketException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjava.io.InputStream
java.io.FilterInputStream
net.sourceforge.jtds.ssl.TdsTlsInputStream
An input stream that filters out TDS headers so they are not returned to JSSE (which will not recognize them).
| Field Summary | |
(package private) java.io.InputStream |
bufferStream
|
(package private) int |
bytesOutstanding
|
(package private) boolean |
pureSSL
False if TLS packets are encapsulated in TDS packets. |
(package private) byte[] |
readBuffer
Temporary buffer used to de-encapsulate inital TLS packets. |
| Fields inherited from class java.io.FilterInputStream |
in |
| Fields inherited from class java.io.InputStream |
|
| Constructor Summary | |
TdsTlsInputStream(java.io.InputStream in)
Constructs a TdsTlsInputStream and bases it on an underlying stream. |
|
| Method Summary | |
private void |
primeBuffer()
Read in entire TLS record or TDS packet and store the TLS record in the buffer. |
int |
read(byte[] b,
int off,
int len)
|
private void |
readFully(byte[] b,
int off,
int len)
Reads len bytes or throws an IOException if
there aren't that many bytes available. |
| Methods inherited from class java.io.FilterInputStream |
available, close, mark, markSupported, read, read, reset, skip |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
int bytesOutstanding
final byte[] readBuffer
java.io.InputStream bufferStream
boolean pureSSL
| Constructor Detail |
public TdsTlsInputStream(java.io.InputStream in)
in - the underlying stream| Method Detail |
public int read(byte[] b,
int off,
int len)
throws java.io.IOException
java.io.IOException
private void primeBuffer()
throws java.io.IOException
java.io.IOException
private void readFully(byte[] b,
int off,
int len)
throws java.io.IOException
len bytes or throws an IOException if
there aren't that many bytes available.
b - buffer to read intooff - offset in the buffer where to start storinglen - amount of data to read
java.io.IOException - if an I/O error occurs or not enough data is
available
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV PACKAGE NEXT PACKAGE | FRAMES NO FRAMES | ||||||||||
| Interface Summary | |
| Ssl | SSL settings |
| Class Summary | |
| SocketFactories | Used for acquiring a socket factory when SSL is enabled. |
| SocketFactories.TdsTlsSocketFactory | The socket factory for creating sockets based on the SSL setting. |
| SocketFactoriesSUN | Used for acquiring a socket factory when SSL is enabled. |
| SocketFactoriesSUN.TdsTlsSocketFactory | The socket factory for creating sockets based on the SSL setting. |
| TdsTlsInputStream | An input stream that filters out TDS headers so they are not returned to JSSE (which will not recognize them). |
| TdsTlsOutputStream | An output stream that mediates between JSSE and the DB server. |
| TdsTlsSocket | A socket that mediates between JSSE and the DB server. |
|
|||||||||||
| PREV PACKAGE NEXT PACKAGE | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjavax.net.SocketFactory
net.sourceforge.jtds.ssl.SocketFactoriesSUN.TdsTlsSocketFactory
The socket factory for creating sockets based on the SSL setting.
| Field Summary | |
private static javax.net.ssl.SSLSocketFactory |
factorySingleton
|
private java.net.Socket |
socket
|
private java.lang.String |
ssl
|
| Fields inherited from class javax.net.SocketFactory |
|
| Constructor Summary | |
SocketFactoriesSUN.TdsTlsSocketFactory(java.lang.String ssl,
java.net.Socket socket)
Constructs a TdsTlsSocketFactory. |
|
| Method Summary | |
java.net.Socket |
createSocket(java.net.InetAddress host,
int port)
|
java.net.Socket |
createSocket(java.net.InetAddress host,
int port,
java.net.InetAddress localHost,
int localPort)
|
java.net.Socket |
createSocket(java.lang.String host,
int port)
Create the SSL socket. |
java.net.Socket |
createSocket(java.lang.String host,
int port,
java.net.InetAddress localHost,
int localPort)
|
private static javax.net.ssl.SSLSocketFactory |
factory()
Returns an SSLSocketFactory whose sockets will not authenticate the server. |
private javax.net.ssl.SSLSocketFactory |
getFactory()
Returns an SSLSocketFactory whose behavior will depend on the SSL setting. |
private static com.sun.net.ssl.TrustManager[] |
trustManagers()
|
| Methods inherited from class javax.net.SocketFactory |
createSocket, getDefault |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private static javax.net.ssl.SSLSocketFactory factorySingleton
private final java.lang.String ssl
private final java.net.Socket socket
| Constructor Detail |
public SocketFactoriesSUN.TdsTlsSocketFactory(java.lang.String ssl,
java.net.Socket socket)
ssl - the SSL settingsocket - the TCP/IP socket to wrap| Method Detail |
public java.net.Socket createSocket(java.lang.String host,
int port)
throws java.io.IOException,
java.net.UnknownHostException
java.io.IOException
java.net.UnknownHostException
public java.net.Socket createSocket(java.net.InetAddress host,
int port)
throws java.io.IOException
java.io.IOException
public java.net.Socket createSocket(java.lang.String host,
int port,
java.net.InetAddress localHost,
int localPort)
throws java.io.IOException,
java.net.UnknownHostException
java.io.IOException
java.net.UnknownHostException
public java.net.Socket createSocket(java.net.InetAddress host,
int port,
java.net.InetAddress localHost,
int localPort)
throws java.io.IOException
java.io.IOException
private javax.net.ssl.SSLSocketFactory getFactory()
throws java.io.IOException
SSLSocketFactory
java.io.IOException
private static javax.net.ssl.SSLSocketFactory factory()
throws java.security.NoSuchAlgorithmException,
java.security.KeyManagementException
SSLSocketFactory
java.security.NoSuchAlgorithmException
java.security.KeyManagementExceptionprivate static com.sun.net.ssl.TrustManager[] trustManagers()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjavax.net.SocketFactory
net.sourceforge.jtds.ssl.SocketFactories.TdsTlsSocketFactory
The socket factory for creating sockets based on the SSL setting.
| Field Summary | |
private static javax.net.ssl.SSLSocketFactory |
factorySingleton
|
private java.net.Socket |
socket
|
private java.lang.String |
ssl
|
| Fields inherited from class javax.net.SocketFactory |
|
| Constructor Summary | |
SocketFactories.TdsTlsSocketFactory(java.lang.String ssl,
java.net.Socket socket)
Constructs a TdsTlsSocketFactory. |
|
| Method Summary | |
java.net.Socket |
createSocket(java.net.InetAddress host,
int port)
|
java.net.Socket |
createSocket(java.net.InetAddress host,
int port,
java.net.InetAddress localHost,
int localPort)
|
java.net.Socket |
createSocket(java.lang.String host,
int port)
Create the SSL socket. |
java.net.Socket |
createSocket(java.lang.String host,
int port,
java.net.InetAddress localHost,
int localPort)
|
private static javax.net.ssl.SSLSocketFactory |
factory()
Returns an SSLSocketFactory whose sockets will not authenticate the server. |
private javax.net.ssl.SSLSocketFactory |
getFactory()
Returns an SSLSocketFactory whose behavior will depend on the SSL setting. |
private static javax.net.ssl.TrustManager[] |
trustManagers()
|
| Methods inherited from class javax.net.SocketFactory |
createSocket, getDefault |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private static javax.net.ssl.SSLSocketFactory factorySingleton
private final java.lang.String ssl
private final java.net.Socket socket
| Constructor Detail |
public SocketFactories.TdsTlsSocketFactory(java.lang.String ssl,
java.net.Socket socket)
ssl - the SSL settingsocket - the TCP/IP socket to wrap| Method Detail |
public java.net.Socket createSocket(java.lang.String host,
int port)
throws java.io.IOException,
java.net.UnknownHostException
java.io.IOException
java.net.UnknownHostException
public java.net.Socket createSocket(java.net.InetAddress host,
int port)
throws java.io.IOException
java.io.IOException
public java.net.Socket createSocket(java.lang.String host,
int port,
java.net.InetAddress localHost,
int localPort)
throws java.io.IOException,
java.net.UnknownHostException
java.io.IOException
java.net.UnknownHostException
public java.net.Socket createSocket(java.net.InetAddress host,
int port,
java.net.InetAddress localHost,
int localPort)
throws java.io.IOException
java.io.IOException
private javax.net.ssl.SSLSocketFactory getFactory()
throws java.io.IOException
SSLSocketFactory
java.io.IOException
private static javax.net.ssl.SSLSocketFactory factory()
throws java.security.NoSuchAlgorithmException,
java.security.KeyManagementException
SSLSocketFactory
java.security.NoSuchAlgorithmException
java.security.KeyManagementExceptionprivate static javax.net.ssl.TrustManager[] trustManagers()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjava.io.OutputStream
java.io.FilterOutputStream
net.sourceforge.jtds.ssl.TdsTlsOutputStream
An output stream that mediates between JSSE and the DB server.
SQL Server 2000 has the following requirements:
| Field Summary | |
private java.util.List |
bufferedRecords
Used for holding back CKE, CCS and FIN records. |
private int |
totalSize
|
| Fields inherited from class java.io.FilterOutputStream |
out |
| Constructor Summary | |
(package private) |
TdsTlsOutputStream(java.io.OutputStream out)
Constructs a TdsTlsOutputStream based on an underlying output stream. |
| Method Summary | |
private void |
deferRecord(byte[] record,
int len)
Holds back a record for batched transmission. |
void |
flush()
|
private void |
flushBufferedRecords()
Transmits the buffered batch of records. |
(package private) void |
putTdsPacket(byte[] b,
int len)
Write a TDS packet containing the TLS record(s). |
void |
write(byte[] b,
int off,
int len)
|
| Methods inherited from class java.io.FilterOutputStream |
close, write, write |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private final java.util.List bufferedRecords
private int totalSize
| Constructor Detail |
TdsTlsOutputStream(java.io.OutputStream out)
out - the underlying output stream| Method Detail |
private void deferRecord(byte[] record,
int len)
record - the TLS record to bufferlen - the length of the TLS record to buffer
private void flushBufferedRecords()
throws java.io.IOException
java.io.IOException
public void write(byte[] b,
int off,
int len)
throws java.io.IOException
java.io.IOException
void putTdsPacket(byte[] b,
int len)
throws java.io.IOException
b - the TLS recordlen - the length of the TLS record
java.io.IOException
public void flush()
throws java.io.IOException
java.io.IOException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
Interfaces
Ssl |
|
Classes
SocketFactories SocketFactories.TdsTlsSocketFactory SocketFactoriesSUN SocketFactoriesSUN.TdsTlsSocketFactory TdsTlsInputStream TdsTlsOutputStream TdsTlsSocket |
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.ssl.SocketFactoriesSUN
Used for acquiring a socket factory when SSL is enabled.
| Nested Class Summary | |
private static class |
SocketFactoriesSUN.TdsTlsSocketFactory
The socket factory for creating sockets based on the SSL setting. |
| Constructor Summary | |
SocketFactoriesSUN()
|
|
| Method Summary | |
static javax.net.SocketFactory |
getSocketFactory(java.lang.String ssl,
java.net.Socket socket)
Returns a socket factory, the behavior of which will depend on the SSL setting and whether or not the DB server supports SSL. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Constructor Detail |
public SocketFactoriesSUN()
| Method Detail |
public static javax.net.SocketFactory getSocketFactory(java.lang.String ssl,
java.net.Socket socket)
ssl - the SSL settingsocket - plain TCP/IP socket to wrap
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.CharsetInfo
Loads and stores information about character sets. Static fields and methods are concerned with loading, storing and retrieval of all character set information, while non-static fields and methods describe a particular character set (Java charset name and whether it's a multi-byte charset).
Note: Only one CharsetInfo instance exists per charset.
This allows simple equality comparisons between instances retrieved with any
of the get methods.
| Field Summary | |
private java.lang.String |
charset
The Java character set name. |
private static java.util.HashMap |
charsets
Server charset to Java charset map. |
private static java.lang.String |
CHARSETS_RESOURCE_NAME
Name of the Charsets.properties resource. |
private static java.util.HashMap |
lcidToCharsetMap
Locale id to Java charset map. |
private static CharsetInfo[] |
sortToCharsetMap
Sort order to Java charset map. |
private boolean |
wideChars
Indicates whether current charset is wide (ie multi-byte). |
| Constructor Summary | |
CharsetInfo(java.lang.String descriptor)
Constructs a CharsetInfo object from a character set
descriptor of the form: charset preceded by a numeric value indicating
whether it's a multibyte character set (>1) or not (1) and a vertical
bar (|), eg "1|Cp1252" or "2|MS936". |
|
| Method Summary | |
boolean |
equals(java.lang.Object o)
|
java.lang.String |
getCharset()
Retrieves the charset name. |
static CharsetInfo |
getCharset(byte[] collation)
Retrieves the CharsetInfo instance asociated with the
specified collation. |
static CharsetInfo |
getCharset(java.lang.String serverCharset)
Retrieves the CharsetInfo instance asociated with the
specified server charset. |
static CharsetInfo |
getCharsetForLCID(int lcid)
Retrieves the CharsetInfo instance asociated with the
specified LCID. |
static CharsetInfo |
getCharsetForSortOrder(int sortOrder)
Retrieves the CharsetInfo instance asociated with the
specified sort order. |
int |
hashCode()
|
boolean |
isWideChars()
Retrieves whether the caracter set is wide (ie multi-byte). |
java.lang.String |
toString()
|
| Methods inherited from class java.lang.Object |
clone, finalize, getClass, notify, notifyAll, wait, wait, wait |
| Field Detail |
private static final java.lang.String CHARSETS_RESOURCE_NAME
Charsets.properties resource.
private static final java.util.HashMap charsets
private static final java.util.HashMap lcidToCharsetMap
private static final CharsetInfo[] sortToCharsetMap
private final java.lang.String charset
private final boolean wideChars
| Constructor Detail |
public CharsetInfo(java.lang.String descriptor)
CharsetInfo object from a character set
descriptor of the form: charset preceded by a numeric value indicating
whether it's a multibyte character set (>1) or not (1) and a vertical
bar (|), eg "1|Cp1252" or "2|MS936".
descriptor - the charset descriptor| Method Detail |
public static CharsetInfo getCharset(java.lang.String serverCharset)
CharsetInfo instance asociated with the
specified server charset.
serverCharset - the server-specific character set name
CharsetInfopublic static CharsetInfo getCharsetForLCID(int lcid)
CharsetInfo instance asociated with the
specified LCID.
lcid - the server LCID
CharsetInfopublic static CharsetInfo getCharsetForSortOrder(int sortOrder)
CharsetInfo instance asociated with the
specified sort order.
sortOrder - the server sort order
CharsetInfopublic static CharsetInfo getCharset(byte[] collation) throws java.sql.SQLException
CharsetInfo instance asociated with the
specified collation.
collation - the server LCID
CharsetInfo
java.sql.SQLExceptionpublic java.lang.String getCharset()
public boolean isWideChars()
public boolean equals(java.lang.Object o)
public int hashCode()
public java.lang.String toString()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.SharedSocket
net.sourceforge.jtds.jdbc.SharedLocalNamedPipe
This class implements inter-process communication (IPC) to the database server using local named pipes (will only work on Windows).
| Field Summary | |
(package private) java.io.RandomAccessFile |
pipe
The named pipe as a file. |
protected int |
serverType
The servertype one of Driver.SQLSERVER or Driver.SYBASE |
| Constructor Summary | |
SharedLocalNamedPipe(ConnectionJDBC2 connection)
Creates a new instance of SharedLocalNamedPipe. |
|
| Method Summary | |
(package private) boolean |
cancel(int streamId)
Send a TDS cancel packet to the server. |
(package private) void |
close()
Close the named pipe and virtual sockets and release any resources. |
(package private) void |
closeStream(int streamId)
Deallocate a stream linked to this socket. |
(package private) void |
disableEncryption()
Disable TLS encryption and switch back to raw TCP/IP socket. |
(package private) void |
enableEncryption(java.lang.String ssl)
Enable TLS encryption by creating a TLS socket over the existing TCP/IP network socket. |
protected void |
finalize()
Finalize this object by releasing its resources. |
(package private) void |
forceClose()
Force close the socket causing any pending reads/writes to fail. |
(package private) java.lang.String |
getCharset()
Retrieve the character set name used to translate byte arrays to or from Strings. |
(package private) CharsetInfo |
getCharsetInfo()
Retrieve the character set descriptor used to translate byte arrays to or from Strings. |
protected java.lang.String |
getHost()
Get the server host name. |
protected java.io.DataInputStream |
getIn()
Getter for SharedSocket.in field. |
(package private) static int |
getMemoryBudget()
Get the global buffer memory limit for all instancs of this driver. |
(package private) static int |
getMinMemPkts()
Get the minimum number of memory cached packets. |
(package private) byte[] |
getNetPacket(int streamId,
byte[] buffer)
Get a network packet. |
protected java.io.DataOutputStream |
getOut()
Getter for SharedSocket.out field. |
(package private) static int |
getPktLen(byte[] buf)
Convert two bytes (in network byte order) in a byte array into a Java short integer. |
protected int |
getPort()
Get the server port number. |
(package private) RequestStream |
getRequestStream(int bufferSize,
int maxPrecision)
Obtain an instance of a server request stream for this socket. |
(package private) ResponseStream |
getResponseStream(RequestStream requestStream,
int bufferSize)
Obtain an instance of a server response stream for this socket. |
(package private) int |
getTdsVersion()
Retrieve the TDS version that is active on the connection supported by this socket. |
(package private) boolean |
isConnected()
Get the connected status of this socket. |
(package private) byte[] |
sendNetPacket(int streamId,
byte[] buffer)
Send an network packet. |
(package private) void |
setCharsetInfo(CharsetInfo charsetInfo)
Set the character set descriptor to be used to translate byte arrays to or from Strings. |
protected void |
setIn(java.io.DataInputStream in)
Setter for SharedSocket.in field. |
protected void |
setKeepAlive(boolean keepAlive)
Set the socket keep alive. |
(package private) static void |
setMemoryBudget(int memoryBudget)
Set the global buffer memory limit for all instances of this driver. |
(package private) static void |
setMinMemPkts(int minMemPkts)
Set the minimum number of packets to cache in memory before writing to disk. |
protected void |
setOut(java.io.DataOutputStream out)
Setter for SharedSocket.out field. |
protected void |
setTdsVersion(int tdsVersion)
Set the TDS version field. |
protected void |
setTimeout(int timeout)
Set the socket timeout. |
| Methods inherited from class java.lang.Object |
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
java.io.RandomAccessFile pipe
protected final int serverType
| Constructor Detail |
public SharedLocalNamedPipe(ConnectionJDBC2 connection) throws java.io.IOException
SharedLocalNamedPipe.
connection - the connection object
java.io.IOException - if an I/O error occurs| Method Detail |
boolean isConnected()
isConnected in class SharedSockettrue if the underlying named pipe is connected
byte[] sendNetPacket(int streamId,
byte[] buffer)
throws java.io.IOException
sendNetPacket in class SharedSocketstreamId - the originating RequestStream objectbuffer - the data to send
java.io.IOException - if an I/O error occurs
void close()
throws java.io.IOException
close in class SharedSocketjava.io.IOException - if the socket close failsvoid forceClose()
Used by the login timer to abort a login attempt.
forceClose in class SharedSocketprotected void setTimeout(int timeout)
setTimeout in class SharedSockettimeout - the timeout value in milliseconds
void enableEncryption(java.lang.String ssl)
throws java.io.IOException
ssl - the SSL URL property value
java.io.IOException - if an I/O error occurs
void disableEncryption()
throws java.io.IOException
java.io.IOException - if an I/O error occursvoid setCharsetInfo(CharsetInfo charsetInfo)
charsetInfo - the character set descriptorCharsetInfo getCharsetInfo()
java.lang.String getCharset()
StringRequestStream getRequestStream(int bufferSize, int maxPrecision)
bufferSize - the initial buffer size to be used by the
RequestStreammaxPrecision - the maximum precision for numeric/decimal types
RequestStreamResponseStream getResponseStream(RequestStream requestStream, int bufferSize)
requestStream - an existing server request stream object obtained
from this SharedSocketbufferSize - the initial buffer size to be used by the
RequestStream
ResponseStreamint getTdsVersion()
intprotected void setTdsVersion(int tdsVersion)
tdsVersion - the TDS version as an intstatic void setMemoryBudget(int memoryBudget)
memoryBudget - the global memory budgetstatic int getMemoryBudget()
intstatic void setMinMemPkts(int minMemPkts)
minMemPkts - the minimum number of packets to cachestatic int getMinMemPkts()
intboolean cancel(int streamId)
streamId - the RequestStream id
boolean true if a cancel is actually
issued by this method call.void closeStream(int streamId)
streamId - the ResponseStream id
byte[] getNetPacket(int streamId,
byte[] buffer)
throws java.io.IOException
streamId - the originating ResponseStream objectbuffer - the data buffer to receive the object (may be replaced)
byte[] buffer
java.io.IOException - if an I/O error occursstatic int getPktLen(byte[] buf)
buf - array of data
int
protected void setKeepAlive(boolean keepAlive)
throws java.net.SocketException
keepAlive - true to turn on socket keep alive
java.net.SocketExceptionprotected java.io.DataInputStream getIn()
SharedSocket.in field.
InputStream used for communicationprotected void setIn(java.io.DataInputStream in)
SharedSocket.in field.
in - the InputStream to be used for communicationprotected java.io.DataOutputStream getOut()
SharedSocket.out field.
OutputStream used for communicationprotected void setOut(java.io.DataOutputStream out)
SharedSocket.out field.
out - the OutputStream to be used for communicationprotected java.lang.String getHost()
Stringprotected int getPort()
int
protected void finalize()
throws java.lang.Throwable
java.lang.Throwable
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.NtlmAuth
This class calculates the two "responses" to the nonce supplied by the server as a part of NTLM authentication. Much gratitude to the authors of this page, esp. for NTLMv2 info: http://davenport.sourceforge.net/ntlm.html
| Constructor Summary | |
NtlmAuth()
|
|
| Method Summary | |
static byte[] |
answerLmChallenge(java.lang.String pwd,
byte[] nonce)
|
static byte[] |
answerLmv2Challenge(java.lang.String domain,
java.lang.String user,
java.lang.String password,
byte[] nonce,
byte[] clientNonce)
|
static byte[] |
answerNtChallenge(java.lang.String password,
byte[] nonce)
|
static byte[] |
answerNtlmv2Challenge(java.lang.String domain,
java.lang.String user,
java.lang.String password,
byte[] nonce,
byte[] targetInfo,
byte[] clientNonce)
|
static byte[] |
answerNtlmv2Challenge(java.lang.String domain,
java.lang.String user,
java.lang.String password,
byte[] nonce,
byte[] targetInfo,
byte[] clientNonce,
byte[] timestamp)
|
static byte[] |
answerNtlmv2Challenge(java.lang.String domain,
java.lang.String user,
java.lang.String password,
byte[] nonce,
byte[] targetInfo,
byte[] clientNonce,
long now)
|
private static byte[] |
convertPassword(java.lang.String password)
Used by answerNtlmChallenge. |
private static byte[] |
createBlob(byte[] targetInformation,
byte[] clientChallenge,
byte[] timestamp)
Creates the NTLMv2 blob from the given target information block and client challenge. |
static byte[] |
createTimestamp(long time)
Creates a timestamp in the format used in NTLMv2 responses. |
private static byte[] |
encryptNonce(byte[] key,
byte[] nonce)
|
private static byte[] |
hmacMD5(byte[] data,
byte[] key)
Calculates the HMAC-MD5 hash of the given data using the specified hashing key. |
private static byte[] |
lmv2Response(byte[] hash,
byte[] clientData,
byte[] challenge)
Creates the LMv2 Response from the given hash, client data, and Type 2 challenge. |
private static byte[] |
makeDESkey(byte[] buf,
int off)
Turns a 7-byte DES key into an 8-byte one by adding parity bits. |
private static byte[] |
md5(byte[] data)
|
private static byte[] |
ntHash(java.lang.String password)
Creates the md4 hash of the unicode password. |
private static byte[] |
ntv2Hash(java.lang.String domain,
java.lang.String user,
java.lang.String password)
|
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Constructor Detail |
public NtlmAuth()
| Method Detail |
public static byte[] answerNtChallenge(java.lang.String password,
byte[] nonce)
throws java.io.UnsupportedEncodingException
java.io.UnsupportedEncodingException
public static byte[] answerLmChallenge(java.lang.String pwd,
byte[] nonce)
throws java.io.UnsupportedEncodingException
java.io.UnsupportedEncodingException
public static byte[] answerNtlmv2Challenge(java.lang.String domain,
java.lang.String user,
java.lang.String password,
byte[] nonce,
byte[] targetInfo,
byte[] clientNonce)
throws java.io.UnsupportedEncodingException
java.io.UnsupportedEncodingException
public static byte[] answerNtlmv2Challenge(java.lang.String domain,
java.lang.String user,
java.lang.String password,
byte[] nonce,
byte[] targetInfo,
byte[] clientNonce,
byte[] timestamp)
throws java.io.UnsupportedEncodingException
java.io.UnsupportedEncodingException
public static byte[] answerNtlmv2Challenge(java.lang.String domain,
java.lang.String user,
java.lang.String password,
byte[] nonce,
byte[] targetInfo,
byte[] clientNonce,
long now)
throws java.io.UnsupportedEncodingException
java.io.UnsupportedEncodingException
public static byte[] answerLmv2Challenge(java.lang.String domain,
java.lang.String user,
java.lang.String password,
byte[] nonce,
byte[] clientNonce)
throws java.io.UnsupportedEncodingException
java.io.UnsupportedEncodingException
private static byte[] ntv2Hash(java.lang.String domain,
java.lang.String user,
java.lang.String password)
throws java.io.UnsupportedEncodingException
java.io.UnsupportedEncodingException
private static byte[] lmv2Response(byte[] hash,
byte[] clientData,
byte[] challenge)
hash - The NTLMv2 Hash.clientData - The client data (blob or client challenge).challenge - The server challenge from the Type 2 message.
private static byte[] hmacMD5(byte[] data,
byte[] key)
data - The data for which the hash will be calculated.key - The hashing key.
private static byte[] md5(byte[] data)
public static byte[] createTimestamp(long time)
time - current time, as returned from System.currentTimeMillis
private static byte[] createBlob(byte[] targetInformation,
byte[] clientChallenge,
byte[] timestamp)
targetInformation - The target information block from the Type 2
message.clientChallenge - The random 8-byte client challenge.
private static byte[] encryptNonce(byte[] key,
byte[] nonce)
private static byte[] ntHash(java.lang.String password)
throws java.io.UnsupportedEncodingException
java.io.UnsupportedEncodingException
private static byte[] convertPassword(java.lang.String password)
throws java.io.UnsupportedEncodingException
java.io.UnsupportedEncodingException
private static byte[] makeDESkey(byte[] buf,
int off)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.SQLParser
Process JDBC escape strings and parameter markers in the SQL string.
This code recognizes the following escapes:
| Nested Class Summary | |
private static class |
SQLParser.CachedSQLQuery
Serialized version of a parsed SQL query (the value stored in the cache for a parsed SQL). |
| Field Summary | |
private static SimpleLRUCache |
cache
LRU cache of previously parsed SQL |
private ConnectionJDBC2 |
connection
Connection object for server specific parsing. |
private static java.util.HashMap |
cvMap
Map of jdbc to server data types for convert |
private int |
d
Current position in output buffer. |
private static byte[] |
dateMask
Syntax mask for date escape. |
private static java.util.HashMap |
fnMap
Map of jdbc to sybase function names. |
private static boolean[] |
identifierChar
Lookup table to test if character is part of an identifier. |
private char[] |
in
Input buffer with SQL statement. |
private java.lang.String |
keyWord
First SQL keyword or identifier in statement. |
private int |
len
Length of input buffer. |
private static java.util.HashMap |
msFnMap
Map of jdbc to sql server function names. |
private char[] |
out
Output buffer to contain parsed SQL. |
private java.util.ArrayList |
params
Parameter list to be populated or null if no parameters
are expected. |
private java.lang.String |
procName
Procedure name in call escape. |
private int |
s
Current position in input buffer. |
private java.lang.String |
sql
Original SQL string |
private java.lang.String |
tableName
First table name in from clause |
private char |
terminator
Current expected terminator character. |
private static byte[] |
timeMask
Syntax mask for time escape. |
(package private) static byte[] |
timestampMask
Syntax mask for timestamp escape. |
| Constructor Summary | |
private |
SQLParser(java.lang.String sqlIn,
java.util.ArrayList paramList,
ConnectionJDBC2 connection)
Constructs a new parser object to process the supplied SQL. |
| Method Summary | |
private void |
callEscape()
Processes the JDBC {call procedure [(?,?,?)]} type escape. |
private java.lang.String |
copyKeyWord()
Copies over possible SQL keyword eg 'SELECT' |
private void |
copyLiteral(java.lang.String txt)
Inserts a String literal in the output buffer. |
private void |
copyParam(java.lang.String name,
int pos)
Builds a new parameter item. |
private java.lang.String |
copyParamName()
Copies an embedded parameter name to the output buffer. |
private java.lang.String |
copyProcName()
Copies an embedded stored procedure identifier over to the output buffer. |
private void |
copyString()
Copies over an embedded string literal unchanged. |
private void |
copyWhiteSpace()
Copies over white space. |
private void |
escape()
Processes the JDBC escape sequences. |
private void |
functionEscape()
Processes the JDBC escape {fn function()}. |
private static SimpleLRUCache |
getCache(ConnectionJDBC2 connection)
Retrieves the statement cache, creating it if required. |
private boolean |
getDateTimeField(byte[] mask)
Utility routine to validate date and time escapes. |
private java.lang.String |
getTableName()
Extracts the first table name following the keyword FROM. |
private static boolean |
isIdentifier(int ch)
Determines if character could be part of an SQL identifier. |
private void |
likeEscape()
Processes the JDBC escape {escape 'X'}. |
private void |
mustbe(char c,
boolean copy)
Checks that the next character is as expected. |
private void |
outerJoinEscape()
Processes the JDBC escape {oj left outer join etc}. |
(package private) java.lang.String[] |
parse(boolean extractTable)
Parses the SQL statement processing JDBC escapes and parameter markers. |
(package private) static java.lang.String[] |
parse(java.lang.String sql,
java.util.ArrayList paramList,
ConnectionJDBC2 connection,
boolean extractTable)
Parse the SQL statement processing JDBC escapes and parameter markers. |
private void |
skipMultiComments()
Skips multi-line comments |
private void |
skipSingleComments()
Skips single-line comments. |
private void |
skipWhiteSpace()
Skips embedded white space. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private static SimpleLRUCache cache
private final java.lang.String sql
private final char[] in
private int s
private final int len
private final char[] out
private int d
private final java.util.ArrayList params
null if no parameters
are expected.
private char terminator
private java.lang.String procName
private java.lang.String keyWord
private java.lang.String tableName
private final ConnectionJDBC2 connection
private static boolean[] identifierChar
private static final byte[] timeMask
private static final byte[] dateMask
static final byte[] timestampMask
private static java.util.HashMap fnMap
private static java.util.HashMap msFnMap
private static java.util.HashMap cvMap
| Constructor Detail |
private SQLParser(java.lang.String sqlIn,
java.util.ArrayList paramList,
ConnectionJDBC2 connection)
sqlIn - the SQL statement to parseparamList - the parameter list array to populate or
null if no parameters are expectedconnection - the parent Connection object| Method Detail |
static java.lang.String[] parse(java.lang.String sql,
java.util.ArrayList paramList,
ConnectionJDBC2 connection,
boolean extractTable)
throws java.sql.SQLException
extractTable - true to return the first table name in the FROM clause of a select
String[].
java.sql.SQLException - if a parse error occursprivate static SimpleLRUCache getCache(ConnectionJDBC2 connection)
SimpleLRUCacheprivate static boolean isIdentifier(int ch)
ch - the character to test.
boolean true if ch in A-Z a-z 0-9 @ $ # _.
private void copyLiteral(java.lang.String txt)
throws java.sql.SQLException
txt - The text to insert.
java.sql.SQLExceptionprivate void copyString()
private java.lang.String copyKeyWord()
private void copyParam(java.lang.String name,
int pos)
throws java.sql.SQLException
name - Optional parameter name or null.pos - The parameter marker position in the output buffer.
java.sql.SQLException
private java.lang.String copyProcName()
throws java.sql.SQLException
String.
java.sql.SQLExceptionprivate java.lang.String copyParamName()
String.private void copyWhiteSpace()
private void mustbe(char c,
boolean copy)
throws java.sql.SQLException
c - The expected character.copy - True if found character should be copied.
java.sql.SQLException - if expected characeter not found.private void skipWhiteSpace()
private void skipSingleComments()
private void skipMultiComments()
throws java.sql.SQLException
java.sql.SQLException
private void callEscape()
throws java.sql.SQLException
java.sql.SQLException - if an error occurs
private boolean getDateTimeField(byte[] mask)
throws java.sql.SQLException
mask - The validation mask
java.sql.SQLException
private void outerJoinEscape()
throws java.sql.SQLException
java.sql.SQLException
private void functionEscape()
throws java.sql.SQLException
java.sql.SQLException
private void likeEscape()
throws java.sql.SQLException
java.sql.SQLException
private void escape()
throws java.sql.SQLException
java.sql.SQLException
private java.lang.String getTableName()
throws java.sql.SQLException
String
java.sql.SQLException
java.lang.String[] parse(boolean extractTable)
throws java.sql.SQLException
extractTable - true to return the first table name in the FROM clause of a select
String[].
java.sql.SQLException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.MSSqlServerInfo
This class communicates with SQL Server 2k to determine what ports its instances are listening to. It does this by sending a UDP packet with the byte 0x02 in it, and parsing the response.
An example of the return packet format is as follows:
< 00000000 05 ea 00 53 65 72 76 65 72 4e 61 6d 65 3b 42 52 # ...ServerName;BR < 00000010 49 4e 4b 4c 45 59 3b 49 6e 73 74 61 6e 63 65 4e # INKLEY;InstanceN < 00000020 61 6d 65 3b 4d 53 53 51 4c 53 45 52 56 45 52 3b # ame;MSSQLSERVER; < 00000030 49 73 43 6c 75 73 74 65 72 65 64 3b 4e 6f 3b 56 # IsClustered;No;V < 00000040 65 72 73 69 6f 6e 3b 38 2e 30 30 2e 31 39 34 3b # ersion;8.00.194; < 00000050 74 63 70 3b 31 34 33 33 3b 6e 70 3b 5c 5c 42 52 # tcp;1433;np;\\BR < 00000060 49 4e 4b 4c 45 59 5c 70 69 70 65 5c 73 71 6c 5c # INKLEY\pipe\sql\ < 00000070 71 75 65 72 79 3b 3b 53 65 72 76 65 72 4e 61 6d # query;;ServerNam < 00000080 65 3b 42 52 49 4e 4b 4c 45 59 3b 49 6e 73 74 61 # e;BRINKLEY;Insta < 00000090 6e 63 65 4e 61 6d 65 3b 44 4f 47 3b 49 73 43 6c # nceName;DOG;IsCl < 000000a0 75 73 74 65 72 65 64 3b 4e 6f 3b 56 65 72 73 69 # ustered;No;Versi < 000000b0 6f 6e 3b 38 2e 30 30 2e 31 39 34 3b 74 63 70 3b # on;8.00.194;tcp; < 000000c0 33 35 34 36 3b 6e 70 3b 5c 5c 42 52 49 4e 4b 4c # 3546;np;\\BRINKL < 000000d0 45 59 5c 70 69 70 65 5c 4d 53 53 51 4c 24 44 4f # EY\pipe\MSSQL$DO < 000000e0 47 5c 73 71 6c 5c 71 75 65 72 79 3b 3b # G\sql\query;;
| Field Summary | |
private int |
numRetries
|
private java.lang.String[] |
serverInfoStrings
|
private int |
timeout
|
| Constructor Summary | |
MSSqlServerInfo(java.lang.String host)
|
|
| Method Summary | |
private static java.lang.String |
extractString(byte[] buf,
int len)
|
int |
getPortForInstance(java.lang.String instanceName)
Call getInfo() before calling this method. |
static java.lang.String[] |
split(java.lang.String s,
int ch)
|
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private int numRetries
private int timeout
private java.lang.String[] serverInfoStrings
| Constructor Detail |
public MSSqlServerInfo(java.lang.String host)
throws java.sql.SQLException
| Method Detail |
public int getPortForInstance(java.lang.String instanceName)
throws java.sql.SQLException
instanceName -
java.sql.SQLException
private static final java.lang.String extractString(byte[] buf,
int len)
public static java.lang.String[] split(java.lang.String s,
int ch)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.SQLDiagnostic
Helper class for handling SQL warnings and errors.
Assigns SQL state values in accordance to the native error number returned by the database server.
| Field Summary | |
(package private) java.sql.SQLException |
exceptions
|
private static java.util.HashMap |
mssqlStates
Map to convert Microsoft SQL server error codes to ANSI SQLSTATE codes. |
private int |
serverType
SQL Server type. |
private static java.util.HashMap |
sybStates
Map to convert Sybase SQL server error codes to ANSI SQLSTATE codes. |
(package private) java.sql.SQLWarning |
warnings
|
| Constructor Summary | |
(package private) |
SQLDiagnostic(int serverType)
Create an SQL message for a specific server type. |
| Method Summary | |
(package private) void |
addDiagnostic(int number,
int state,
int serverity,
java.lang.String message,
java.lang.String server,
java.lang.String procName,
int line)
Create a dianostic SQLException or SQLWarning. |
(package private) void |
addException(java.sql.SQLException e)
|
(package private) void |
addWarning(java.sql.SQLWarning w)
|
(package private) void |
checkErrors()
Check the exception chain for errors and throw any found as an SQLException. |
(package private) void |
clearWarnings()
Clear the warning chain. |
private static java.lang.String |
getStateCode(int number,
int serverType,
java.lang.String defState)
Map an SQL Server error code to an ANSI SQLSTATE code. |
(package private) java.sql.SQLWarning |
getWarnings()
Return the warning chain. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private static final java.util.HashMap mssqlStates
private static final java.util.HashMap sybStates
private final int serverType
Driver.SQLSERVER or
Driver.SYBASE.
java.sql.SQLException exceptions
java.sql.SQLWarning warnings
| Constructor Detail |
SQLDiagnostic(int serverType)
serverType - either Driver.SQLSERVER or Driver.SYBASE| Method Detail |
void addWarning(java.sql.SQLWarning w)
void addException(java.sql.SQLException e)
void addDiagnostic(int number,
int state,
int serverity,
java.lang.String message,
java.lang.String server,
java.lang.String procName,
int line)
number - SQL Server error number.state - SQL Server state code.serverity - SQL Server serverity > 10 = error.message - SQL Server error message text.server - SQL Server name.procName - SQL Server stored procedure name.line - SQL Server error line number in SQL source.void clearWarnings()
void checkErrors()
throws java.sql.SQLException
java.sql.SQLExceptionjava.sql.SQLWarning getWarnings()
SQLWarning.
private static java.lang.String getStateCode(int number,
int serverType,
java.lang.String defState)
number - the SQL Server error numberserverType - Driver.SQLSERVER or Driver.SYBASEdefState - the default state code to return if the mapping fails
String
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.SQLParser.CachedSQLQuery
Serialized version of a parsed SQL query (the value stored in the cache for a parsed SQL).
Holds the parsed SQL query and the names, positions and return value and unicode flags for the parameters.
| Field Summary | |
(package private) boolean[] |
paramIsRetVal
|
(package private) boolean[] |
paramIsUnicode
|
(package private) int[] |
paramMarkerPos
|
(package private) java.lang.String[] |
paramNames
|
(package private) java.lang.String[] |
parsedSql
|
| Constructor Summary | |
(package private) |
SQLParser.CachedSQLQuery(java.lang.String[] parsedSql,
java.util.ArrayList params)
|
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
final java.lang.String[] parsedSql
final java.lang.String[] paramNames
final int[] paramMarkerPos
final boolean[] paramIsRetVal
final boolean[] paramIsUnicode
| Constructor Detail |
SQLParser.CachedSQLQuery(java.lang.String[] parsedSql,
java.util.ArrayList params)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.UniqueIdentifier
This class encapsulates the MS SQL2000 UniqueIdentifer data type.
| Field Summary | |
private byte[] |
bytes
|
| Constructor Summary | |
UniqueIdentifier(byte[] id)
Construct a unique identifier with the supplied byte array. |
|
| Method Summary | |
byte[] |
getBytes()
Retrieve the unique identifier as a byte array. |
java.lang.String |
toString()
Retrieve the unique identifier as a formatted string. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
private final byte[] bytes
| Constructor Detail |
public UniqueIdentifier(byte[] id)
| Method Detail |
public byte[] getBytes()
byte[].public java.lang.String toString()
Format is NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN.
String.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.JtdsStatement
net.sourceforge.jtds.jdbc.JtdsPreparedStatement
net.sourceforge.jtds.jdbc.JtdsCallableStatement
jTDS implementation of the java.sql.CallableStatement interface.
Implementation note:
| Field Summary | |
protected boolean |
paramWasNull
Last parameter retrieved was null. |
| Fields inherited from class net.sourceforge.jtds.jdbc.JtdsPreparedStatement |
handles, parameters, paramMetaData, procName, sql, sqlWord |
| Fields inherited from class net.sourceforge.jtds.jdbc.JtdsStatement |
batchValues, BOOLEAN, CLOSE_ALL_RESULTS, CLOSE_CURRENT_RESULT, closed, colMetaData, connection, currentResult, cursorName, DATALINK, DEFAULT_FETCH_SIZE, escapeProcessing, EXECUTE_FAILED, fetchDirection, fetchSize, genKeyResultSet, KEEP_CURRENT_RESULT, maxFieldSize, maxRows, messages, NO_GENERATED_KEYS, openResultSets, queryTimeout, resultQueue, resultSetConcurrency, resultSetType, RETURN_GENERATED_KEYS, SUCCESS_NO_INFO, tds |
| Fields inherited from interface java.sql.Statement |
CLOSE_ALL_RESULTS, CLOSE_CURRENT_RESULT, EXECUTE_FAILED, KEEP_CURRENT_RESULT, NO_GENERATED_KEYS, RETURN_GENERATED_KEYS, SUCCESS_NO_INFO |
| Constructor Summary | |
(package private) |
JtdsCallableStatement(ConnectionJDBC2 connection,
java.lang.String sql,
int resultSetType,
int concurrency)
Construct a CallableStatement object. |
| Method Summary | |
protected void |
checkOpen()
Check that this statement is still open. |
protected java.sql.SQLException |
executeMSBatch(int size,
int executeSize,
java.util.ArrayList counts)
Execute the SQL batch on a MS server. |
protected java.sql.SQLException |
executeSybaseBatch(int size,
int executeSize,
java.util.ArrayList counts)
Execute the SQL batch on a Sybase server. |
(package private) int |
findParameter(java.lang.String name,
boolean set)
Find a parameter by name. |
java.sql.Array |
getArray(int parameterIndex)
|
java.sql.Array |
getArray(java.lang.String parameterName)
|
java.math.BigDecimal |
getBigDecimal(int parameterIndex)
|
java.math.BigDecimal |
getBigDecimal(int parameterIndex,
int scale)
|
java.math.BigDecimal |
getBigDecimal(java.lang.String parameterName)
|
java.sql.Blob |
getBlob(int parameterIndex)
|
java.sql.Blob |
getBlob(java.lang.String parameterName)
|
boolean |
getBoolean(int parameterIndex)
|
boolean |
getBoolean(java.lang.String parameterName)
|
byte |
getByte(int parameterIndex)
|
byte |
getByte(java.lang.String parameterName)
|
byte[] |
getBytes(int parameterIndex)
|
byte[] |
getBytes(java.lang.String parameterName)
|
java.sql.Clob |
getClob(int parameterIndex)
|
java.sql.Clob |
getClob(java.lang.String parameterName)
|
java.sql.Date |
getDate(int parameterIndex)
|
java.sql.Date |
getDate(int parameterIndex,
java.util.Calendar cal)
|
java.sql.Date |
getDate(java.lang.String parameterName)
|
java.sql.Date |
getDate(java.lang.String parameterName,
java.util.Calendar cal)
|
double |
getDouble(int parameterIndex)
|
double |
getDouble(java.lang.String parameterName)
|
float |
getFloat(int parameterIndex)
|
float |
getFloat(java.lang.String parameterName)
|
int |
getInt(int parameterIndex)
|
int |
getInt(java.lang.String parameterName)
|
long |
getLong(int parameterIndex)
|
long |
getLong(java.lang.String parameterName)
|
java.lang.Object |
getObject(int parameterIndex)
|
java.lang.Object |
getObject(int parameterIndex,
java.util.Map map)
|
java.lang.Object |
getObject(java.lang.String parameterName)
|
java.lang.Object |
getObject(java.lang.String parameterName,
java.util.Map map)
|
protected java.lang.Object |
getOutputValue(int parameterIndex)
Retrieve the value of an output parameter. |
java.sql.Ref |
getRef(int parameterIndex)
|
java.sql.Ref |
getRef(java.lang.String parameterName)
|
short |
getShort(int parameterIndex)
|
short |
getShort(java.lang.String parameterName)
|
java.lang.String |
getString(int parameterIndex)
|
java.lang.String |
getString(java.lang.String parameterName)
|
java.sql.Time |
getTime(int parameterIndex)
|
java.sql.Time |
getTime(int parameterIndex,
java.util.Calendar cal)
|
java.sql.Time |
getTime(java.lang.String parameterName)
|
java.sql.Time |
getTime(java.lang.String parameterName,
java.util.Calendar cal)
|
java.sql.Timestamp |
getTimestamp(int parameterIndex)
|
java.sql.Timestamp |
getTimestamp(int parameterIndex,
java.util.Calendar cal)
|
java.sql.Timestamp |
getTimestamp(java.lang.String parameterName)
|
java.sql.Timestamp |
getTimestamp(java.lang.String parameterName,
java.util.Calendar cal)
|
java.net.URL |
getURL(int parameterIndex)
|
java.net.URL |
getURL(java.lang.String parameterName)
|
void |
registerOutParameter(int parameterIndex,
int sqlType)
|
void |
registerOutParameter(int parameterIndex,
int sqlType,
int scale)
|
void |
registerOutParameter(int parameterIndex,
int sqlType,
java.lang.String typeName)
|
void |
registerOutParameter(java.lang.String parameterName,
int sqlType)
|
void |
registerOutParameter(java.lang.String parameterName,
int sqlType,
int scale)
|
void |
registerOutParameter(java.lang.String parameterName,
int sqlType,
java.lang.String typeName)
|
void |
setAsciiStream(java.lang.String parameterName,
java.io.InputStream x,
int length)
|
void |
setBigDecimal(java.lang.String parameterName,
java.math.BigDecimal x)
|
void |
setBinaryStream(java.lang.String parameterName,
java.io.InputStream x,
int length)
|
void |
setBoolean(java.lang.String parameterName,
boolean x)
|
void |
setByte(java.lang.String parameterName,
byte x)
|
void |
setBytes(java.lang.String parameterName,
byte[] x)
|
void |
setCharacterStream(java.lang.String parameterName,
java.io.Reader reader,
int length)
|
void |
setDate(java.lang.String parameterName,
java.sql.Date x)
|
void |
setDate(java.lang.String parameterName,
java.sql.Date x,
java.util.Calendar cal)
|
void |
setDouble(java.lang.String parameterName,
double x)
|
void |
setFloat(java.lang.String parameterName,
float x)
|
void |
setInt(java.lang.String parameterName,
int x)
|
void |
setLong(java.lang.String parameterName,
long x)
|
void |
setNull(java.lang.String parameterName,
int sqlType)
|
void |
setNull(java.lang.String parameterName,
int sqlType,
java.lang.String typeName)
|
void |
setObject(java.lang.String parameterName,
java.lang.Object x)
|
void |
setObject(java.lang.String parameterName,
java.lang.Object x,
int targetSqlType)
|
void |
setObject(java.lang.String parameterName,
java.lang.Object x,
int targetSqlType,
int scale)
|
void |
setShort(java.lang.String parameterName,
short x)
|
void |
setString(java.lang.String parameterName,
java.lang.String x)
|
void |
setTime(java.lang.String parameterName,
java.sql.Time x)
|
void |
setTime(java.lang.String parameterName,
java.sql.Time x,
java.util.Calendar cal)
|
void |
setTimestamp(java.lang.String parameterName,
java.sql.Timestamp x)
|
void |
setTimestamp(java.lang.String parameterName,
java.sql.Timestamp x,
java.util.Calendar cal)
|
void |
setURL(java.lang.String parameterName,
java.net.URL x)
|
boolean |
wasNull()
|
| Methods inherited from class net.sourceforge.jtds.jdbc.JtdsPreparedStatement |
addBatch, addBatch, clearParameters, close, execute, execute, execute, execute, execute, executeQuery, executeQuery, executeUpdate, executeUpdate, executeUpdate, executeUpdate, executeUpdate, getMetaData, getParameter, getParameterMetaData, normalizeCall, notSupported, setArray, setAsciiStream, setBigDecimal, setBinaryStream, setBlob, setBoolean, setByte, setBytes, setCharacterStream, setClob, setColMetaData, setDate, setDate, setDouble, setFloat, setInt, setLong, setNull, setNull, setObject, setObject, setObject, setObjectBase, setParameter, setParamMetaData, setRef, setShort, setString, setTime, setTime, setTimestamp, setTimestamp, setUnicodeStream, setURL, toString |
| Methods inherited from class java.lang.Object |
clone, equals, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Methods inherited from interface java.sql.PreparedStatement |
addBatch, clearParameters, execute, executeQuery, executeUpdate, getMetaData, getParameterMetaData, setArray, setAsciiStream, setBigDecimal, setBinaryStream, setBlob, setBoolean, setByte, setBytes, setCharacterStream, setClob, setDate, setDate, setDouble, setFloat, setInt, setLong, setNull, setNull, setObject, setObject, setObject, setRef, setShort, setString, setTime, setTime, setTimestamp, setTimestamp, setUnicodeStream, setURL |
| Methods inherited from interface java.sql.Statement |
addBatch, cancel, clearBatch, clearWarnings, close, execute, execute, execute, execute, executeBatch, executeQuery, executeUpdate, executeUpdate, executeUpdate, executeUpdate, getConnection, getFetchDirection, getFetchSize, getGeneratedKeys, getMaxFieldSize, getMaxRows, getMoreResults, getMoreResults, getQueryTimeout, getResultSet, getResultSetConcurrency, getResultSetHoldability, getResultSetType, getUpdateCount, getWarnings, setCursorName, setEscapeProcessing, setFetchDirection, setFetchSize, setMaxFieldSize, setMaxRows, setQueryTimeout |
| Field Detail |
protected boolean paramWasNull
| Constructor Detail |
JtdsCallableStatement(ConnectionJDBC2 connection, java.lang.String sql, int resultSetType, int concurrency) throws java.sql.SQLException
connection - The connection owning this statement.sql - The SQL statement specifying the procedure to call.resultSetType - The result set type eg FORWARD_ONLY.concurrency - The result set concurrency eg READ_ONLY.
java.sql.SQLException| Method Detail |
int findParameter(java.lang.String name,
boolean set)
throws java.sql.SQLException
name - The name of the parameter to locate.set - True if function is called from a set / register method.
int.
java.sql.SQLException
protected java.lang.Object getOutputValue(int parameterIndex)
throws java.sql.SQLException
parameterIndex - the ordinal position of the parameter
Object
java.sql.SQLException - if the parameter has not been set
protected void checkOpen()
throws java.sql.SQLException
checkOpen in class JtdsPreparedStatementjava.sql.SQLException - if statement closed.
protected java.sql.SQLException executeMSBatch(int size,
int executeSize,
java.util.ArrayList counts)
throws java.sql.SQLException
executeMSBatch in class JtdsPreparedStatementsize - the total size of the batch.executeSize - the maximum number of statements to send in one request.counts - the returned update counts.
SQLException.
java.sql.SQLException
protected java.sql.SQLException executeSybaseBatch(int size,
int executeSize,
java.util.ArrayList counts)
throws java.sql.SQLException
executeSybaseBatch in class JtdsPreparedStatementsize - the total size of the batchexecuteSize - the maximum number of statements to send in one request (ignored for this version of the
method as only one statement will be sent at a time)counts - the returned update counts
SQLException
java.sql.SQLException - if a serious error occurs during execution
public boolean wasNull()
throws java.sql.SQLException
wasNull in interface java.sql.CallableStatementjava.sql.SQLException
public byte getByte(int parameterIndex)
throws java.sql.SQLException
getByte in interface java.sql.CallableStatementjava.sql.SQLException
public double getDouble(int parameterIndex)
throws java.sql.SQLException
getDouble in interface java.sql.CallableStatementjava.sql.SQLException
public float getFloat(int parameterIndex)
throws java.sql.SQLException
getFloat in interface java.sql.CallableStatementjava.sql.SQLException
public int getInt(int parameterIndex)
throws java.sql.SQLException
getInt in interface java.sql.CallableStatementjava.sql.SQLException
public long getLong(int parameterIndex)
throws java.sql.SQLException
getLong in interface java.sql.CallableStatementjava.sql.SQLException
public short getShort(int parameterIndex)
throws java.sql.SQLException
getShort in interface java.sql.CallableStatementjava.sql.SQLException
public boolean getBoolean(int parameterIndex)
throws java.sql.SQLException
getBoolean in interface java.sql.CallableStatementjava.sql.SQLException
public byte[] getBytes(int parameterIndex)
throws java.sql.SQLException
getBytes in interface java.sql.CallableStatementjava.sql.SQLException
public void registerOutParameter(int parameterIndex,
int sqlType)
throws java.sql.SQLException
registerOutParameter in interface java.sql.CallableStatementjava.sql.SQLException
public void registerOutParameter(int parameterIndex,
int sqlType,
int scale)
throws java.sql.SQLException
registerOutParameter in interface java.sql.CallableStatementjava.sql.SQLException
public java.lang.Object getObject(int parameterIndex)
throws java.sql.SQLException
getObject in interface java.sql.CallableStatementjava.sql.SQLException
public java.lang.String getString(int parameterIndex)
throws java.sql.SQLException
getString in interface java.sql.CallableStatementjava.sql.SQLException
public void registerOutParameter(int parameterIndex,
int sqlType,
java.lang.String typeName)
throws java.sql.SQLException
registerOutParameter in interface java.sql.CallableStatementjava.sql.SQLException
public byte getByte(java.lang.String parameterName)
throws java.sql.SQLException
getByte in interface java.sql.CallableStatementjava.sql.SQLException
public double getDouble(java.lang.String parameterName)
throws java.sql.SQLException
getDouble in interface java.sql.CallableStatementjava.sql.SQLException
public float getFloat(java.lang.String parameterName)
throws java.sql.SQLException
getFloat in interface java.sql.CallableStatementjava.sql.SQLException
public int getInt(java.lang.String parameterName)
throws java.sql.SQLException
getInt in interface java.sql.CallableStatementjava.sql.SQLException
public long getLong(java.lang.String parameterName)
throws java.sql.SQLException
getLong in interface java.sql.CallableStatementjava.sql.SQLException
public short getShort(java.lang.String parameterName)
throws java.sql.SQLException
getShort in interface java.sql.CallableStatementjava.sql.SQLException
public boolean getBoolean(java.lang.String parameterName)
throws java.sql.SQLException
getBoolean in interface java.sql.CallableStatementjava.sql.SQLException
public byte[] getBytes(java.lang.String parameterName)
throws java.sql.SQLException
getBytes in interface java.sql.CallableStatementjava.sql.SQLException
public void setByte(java.lang.String parameterName,
byte x)
throws java.sql.SQLException
setByte in interface java.sql.CallableStatementjava.sql.SQLException
public void setDouble(java.lang.String parameterName,
double x)
throws java.sql.SQLException
setDouble in interface java.sql.CallableStatementjava.sql.SQLException
public void setFloat(java.lang.String parameterName,
float x)
throws java.sql.SQLException
setFloat in interface java.sql.CallableStatementjava.sql.SQLException
public void registerOutParameter(java.lang.String parameterName,
int sqlType)
throws java.sql.SQLException
registerOutParameter in interface java.sql.CallableStatementjava.sql.SQLException
public void setInt(java.lang.String parameterName,
int x)
throws java.sql.SQLException
setInt in interface java.sql.CallableStatementjava.sql.SQLException
public void setNull(java.lang.String parameterName,
int sqlType)
throws java.sql.SQLException
setNull in interface java.sql.CallableStatementjava.sql.SQLException
public void registerOutParameter(java.lang.String parameterName,
int sqlType,
int scale)
throws java.sql.SQLException
registerOutParameter in interface java.sql.CallableStatementjava.sql.SQLException
public void setLong(java.lang.String parameterName,
long x)
throws java.sql.SQLException
setLong in interface java.sql.CallableStatementjava.sql.SQLException
public void setShort(java.lang.String parameterName,
short x)
throws java.sql.SQLException
setShort in interface java.sql.CallableStatementjava.sql.SQLException
public void setBoolean(java.lang.String parameterName,
boolean x)
throws java.sql.SQLException
setBoolean in interface java.sql.CallableStatementjava.sql.SQLException
public void setBytes(java.lang.String parameterName,
byte[] x)
throws java.sql.SQLException
setBytes in interface java.sql.CallableStatementjava.sql.SQLException
public java.math.BigDecimal getBigDecimal(int parameterIndex)
throws java.sql.SQLException
getBigDecimal in interface java.sql.CallableStatementjava.sql.SQLException
public java.math.BigDecimal getBigDecimal(int parameterIndex,
int scale)
throws java.sql.SQLException
getBigDecimal in interface java.sql.CallableStatementjava.sql.SQLException
public java.net.URL getURL(int parameterIndex)
throws java.sql.SQLException
getURL in interface java.sql.CallableStatementjava.sql.SQLException
public java.sql.Array getArray(int parameterIndex)
throws java.sql.SQLException
getArray in interface java.sql.CallableStatementjava.sql.SQLException
public java.sql.Blob getBlob(int parameterIndex)
throws java.sql.SQLException
getBlob in interface java.sql.CallableStatementjava.sql.SQLException
public java.sql.Clob getClob(int parameterIndex)
throws java.sql.SQLException
getClob in interface java.sql.CallableStatementjava.sql.SQLException
public java.sql.Date getDate(int parameterIndex)
throws java.sql.SQLException
getDate in interface java.sql.CallableStatementjava.sql.SQLException
public java.sql.Ref getRef(int parameterIndex)
throws java.sql.SQLException
getRef in interface java.sql.CallableStatementjava.sql.SQLException
public java.sql.Time getTime(int parameterIndex)
throws java.sql.SQLException
getTime in interface java.sql.CallableStatementjava.sql.SQLException
public java.sql.Timestamp getTimestamp(int parameterIndex)
throws java.sql.SQLException
getTimestamp in interface java.sql.CallableStatementjava.sql.SQLException
public void setAsciiStream(java.lang.String parameterName,
java.io.InputStream x,
int length)
throws java.sql.SQLException
setAsciiStream in interface java.sql.CallableStatementjava.sql.SQLException
public void setBinaryStream(java.lang.String parameterName,
java.io.InputStream x,
int length)
throws java.sql.SQLException
setBinaryStream in interface java.sql.CallableStatementjava.sql.SQLException
public void setCharacterStream(java.lang.String parameterName,
java.io.Reader reader,
int length)
throws java.sql.SQLException
setCharacterStream in interface java.sql.CallableStatementjava.sql.SQLException
public java.lang.Object getObject(java.lang.String parameterName)
throws java.sql.SQLException
getObject in interface java.sql.CallableStatementjava.sql.SQLException
public void setObject(java.lang.String parameterName,
java.lang.Object x)
throws java.sql.SQLException
setObject in interface java.sql.CallableStatementjava.sql.SQLException
public void setObject(java.lang.String parameterName,
java.lang.Object x,
int targetSqlType)
throws java.sql.SQLException
setObject in interface java.sql.CallableStatementjava.sql.SQLException
public void setObject(java.lang.String parameterName,
java.lang.Object x,
int targetSqlType,
int scale)
throws java.sql.SQLException
setObject in interface java.sql.CallableStatementjava.sql.SQLException
public java.lang.Object getObject(int parameterIndex,
java.util.Map map)
throws java.sql.SQLException
getObject in interface java.sql.CallableStatementjava.sql.SQLException
public java.lang.String getString(java.lang.String parameterName)
throws java.sql.SQLException
getString in interface java.sql.CallableStatementjava.sql.SQLException
public void registerOutParameter(java.lang.String parameterName,
int sqlType,
java.lang.String typeName)
throws java.sql.SQLException
registerOutParameter in interface java.sql.CallableStatementjava.sql.SQLException
public void setNull(java.lang.String parameterName,
int sqlType,
java.lang.String typeName)
throws java.sql.SQLException
setNull in interface java.sql.CallableStatementjava.sql.SQLException
public void setString(java.lang.String parameterName,
java.lang.String x)
throws java.sql.SQLException
setString in interface java.sql.CallableStatementjava.sql.SQLException
public java.math.BigDecimal getBigDecimal(java.lang.String parameterName)
throws java.sql.SQLException
getBigDecimal in interface java.sql.CallableStatementjava.sql.SQLException
public void setBigDecimal(java.lang.String parameterName,
java.math.BigDecimal x)
throws java.sql.SQLException
setBigDecimal in interface java.sql.CallableStatementjava.sql.SQLException
public java.net.URL getURL(java.lang.String parameterName)
throws java.sql.SQLException
getURL in interface java.sql.CallableStatementjava.sql.SQLException
public void setURL(java.lang.String parameterName,
java.net.URL x)
throws java.sql.SQLException
setURL in interface java.sql.CallableStatementjava.sql.SQLException
public java.sql.Array getArray(java.lang.String parameterName)
throws java.sql.SQLException
getArray in interface java.sql.CallableStatementjava.sql.SQLException
public java.sql.Blob getBlob(java.lang.String parameterName)
throws java.sql.SQLException
getBlob in interface java.sql.CallableStatementjava.sql.SQLException
public java.sql.Clob getClob(java.lang.String parameterName)
throws java.sql.SQLException
getClob in interface java.sql.CallableStatementjava.sql.SQLException
public java.sql.Date getDate(java.lang.String parameterName)
throws java.sql.SQLException
getDate in interface java.sql.CallableStatementjava.sql.SQLException
public void setDate(java.lang.String parameterName,
java.sql.Date x)
throws java.sql.SQLException
setDate in interface java.sql.CallableStatementjava.sql.SQLException
public java.sql.Date getDate(int parameterIndex,
java.util.Calendar cal)
throws java.sql.SQLException
getDate in interface java.sql.CallableStatementjava.sql.SQLException
public java.sql.Ref getRef(java.lang.String parameterName)
throws java.sql.SQLException
getRef in interface java.sql.CallableStatementjava.sql.SQLException
public java.sql.Time getTime(java.lang.String parameterName)
throws java.sql.SQLException
getTime in interface java.sql.CallableStatementjava.sql.SQLException
public void setTime(java.lang.String parameterName,
java.sql.Time x)
throws java.sql.SQLException
setTime in interface java.sql.CallableStatementjava.sql.SQLException
public java.sql.Time getTime(int parameterIndex,
java.util.Calendar cal)
throws java.sql.SQLException
getTime in interface java.sql.CallableStatementjava.sql.SQLException
public java.sql.Timestamp getTimestamp(java.lang.String parameterName)
throws java.sql.SQLException
getTimestamp in interface java.sql.CallableStatementjava.sql.SQLException
public void setTimestamp(java.lang.String parameterName,
java.sql.Timestamp x)
throws java.sql.SQLException
setTimestamp in interface java.sql.CallableStatementjava.sql.SQLException
public java.sql.Timestamp getTimestamp(int parameterIndex,
java.util.Calendar cal)
throws java.sql.SQLException
getTimestamp in interface java.sql.CallableStatementjava.sql.SQLException
public java.lang.Object getObject(java.lang.String parameterName,
java.util.Map map)
throws java.sql.SQLException
getObject in interface java.sql.CallableStatementjava.sql.SQLException
public java.sql.Date getDate(java.lang.String parameterName,
java.util.Calendar cal)
throws java.sql.SQLException
getDate in interface java.sql.CallableStatementjava.sql.SQLException
public java.sql.Time getTime(java.lang.String parameterName,
java.util.Calendar cal)
throws java.sql.SQLException
getTime in interface java.sql.CallableStatementjava.sql.SQLException
public java.sql.Timestamp getTimestamp(java.lang.String parameterName,
java.util.Calendar cal)
throws java.sql.SQLException
getTimestamp in interface java.sql.CallableStatementjava.sql.SQLException
public void setDate(java.lang.String parameterName,
java.sql.Date x,
java.util.Calendar cal)
throws java.sql.SQLException
setDate in interface java.sql.CallableStatementjava.sql.SQLException
public void setTime(java.lang.String parameterName,
java.sql.Time x,
java.util.Calendar cal)
throws java.sql.SQLException
setTime in interface java.sql.CallableStatementjava.sql.SQLException
public void setTimestamp(java.lang.String parameterName,
java.sql.Timestamp x,
java.util.Calendar cal)
throws java.sql.SQLException
setTimestamp in interface java.sql.CallableStatementjava.sql.SQLException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.SharedSocket.VirtualSocket
This inner class contains the state information for the virtual socket.
| Field Summary | |
(package private) boolean |
complete
True if output is complete TDS packet. |
(package private) java.io.RandomAccessFile |
diskQueue
I/O Stream for disk packet queue. |
(package private) boolean |
flushInput
True to discard network data. |
(package private) int |
inputPkts
Total of input packets in memory or disk. |
(package private) int |
owner
The stream ID of the stream objects owning this state. |
(package private) java.util.LinkedList |
pktQueue
Memory resident packet queue. |
(package private) int |
pktsOnDisk
Number of packets cached to disk. |
(package private) java.io.File |
queueFile
File object for disk packet queue. |
| Constructor Summary | |
(package private) |
SharedSocket.VirtualSocket(int streamId)
Constuct object to hold state information for each caller. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
final int owner
final java.util.LinkedList pktQueue
boolean flushInput
boolean complete
java.io.File queueFile
java.io.RandomAccessFile diskQueue
int pktsOnDisk
int inputPkts
| Constructor Detail |
SharedSocket.VirtualSocket(int streamId)
streamId - the Response/Request stream id.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.TdsCore.TableMetaData
Inner static class used to hold table meta data.
| Field Summary | |
(package private) java.lang.String |
catalog
Table catalog (database) name. |
(package private) java.lang.String |
name
Table name. |
(package private) java.lang.String |
schema
Table schema (user) name. |
| Constructor Summary | |
private |
TdsCore.TableMetaData()
|
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
java.lang.String catalog
java.lang.String schema
java.lang.String name
| Constructor Detail |
private TdsCore.TableMetaData()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use CharsetInfo | |
| net.sourceforge.jtds.jdbc | |
| Uses of CharsetInfo in net.sourceforge.jtds.jdbc |
| Fields in net.sourceforge.jtds.jdbc declared as CharsetInfo | |
private CharsetInfo |
SharedSocket.charsetInfo
The character set to use for converting strings to/from bytes. |
(package private) CharsetInfo |
ParamInfo.charsetInfo
Character set descriptor (if different from default) |
private CharsetInfo |
ConnectionJDBC2.charsetInfo
Java charset for encoding. |
(package private) CharsetInfo |
ColInfo.charsetInfo
Character set descriptor (if different from default) |
private static CharsetInfo[] |
CharsetInfo.sortToCharsetMap
Sort order to Java charset map. |
| Methods in net.sourceforge.jtds.jdbc that return CharsetInfo | |
(package private) CharsetInfo |
SharedSocket.getCharsetInfo()
Retrieve the character set descriptor used to translate byte arrays to or from Strings. |
protected CharsetInfo |
ConnectionJDBC2.getCharsetInfo()
Retrieve the CharsetInfo instance used by this connection. |
static CharsetInfo |
CharsetInfo.getCharset(java.lang.String serverCharset)
Retrieves the CharsetInfo instance asociated with the
specified server charset. |
static CharsetInfo |
CharsetInfo.getCharsetForLCID(int lcid)
Retrieves the CharsetInfo instance asociated with the
specified LCID. |
static CharsetInfo |
CharsetInfo.getCharsetForSortOrder(int sortOrder)
Retrieves the CharsetInfo instance asociated with the
specified sort order. |
static CharsetInfo |
CharsetInfo.getCharset(byte[] collation)
Retrieves the CharsetInfo instance asociated with the
specified collation. |
| Methods in net.sourceforge.jtds.jdbc with parameters of type CharsetInfo | |
(package private) static void |
TdsData.writeTds5Param(RequestStream out,
CharsetInfo charsetInfo,
ParamInfo pi)
Write the actual TDS 5 parameter data. |
(package private) static void |
TdsData.writeParam(RequestStream out,
CharsetInfo charsetInfo,
byte[] collation,
ParamInfo pi)
Write a parameter to the server request stream. |
(package private) void |
SharedSocket.setCharsetInfo(CharsetInfo charsetInfo)
Set the character set descriptor to be used to translate byte arrays to or from Strings. |
(package private) java.lang.String |
ResponseStream.readNonUnicodeString(int len,
CharsetInfo charsetInfo)
Reads a String from the server response stream, translating
it from a byte array using the specified character set. |
(package private) java.lang.String |
ResponseStream.readString(int len,
CharsetInfo info)
Reads a String from the server response stream, creating
it from a translated byte array. |
private void |
ConnectionJDBC2.loadCharset(CharsetInfo ci,
java.lang.String ref)
Load the Java charset to match the server character set. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use SQLDiagnostic | |
| net.sourceforge.jtds.jdbc | |
| Uses of SQLDiagnostic in net.sourceforge.jtds.jdbc |
| Fields in net.sourceforge.jtds.jdbc declared as SQLDiagnostic | |
private SQLDiagnostic |
TdsCore.messages
The head of the diagnostic messages chain. |
protected SQLDiagnostic |
JtdsStatement.messages
SQL Diagnostic exceptions and warnings. |
private SQLDiagnostic |
ConnectionJDBC2.messages
Diagnostc messages for this connection. |
| Methods in net.sourceforge.jtds.jdbc that return SQLDiagnostic | |
SQLDiagnostic |
TdsCore.getMessages()
Returns the diagnostic chain for this instance. |
(package private) SQLDiagnostic |
JtdsStatement.getMessages()
Get the statement's warnings list. |
| Constructors in net.sourceforge.jtds.jdbc with parameters of type SQLDiagnostic | |
TdsCore(ConnectionJDBC2 connection,
SQLDiagnostic messages)
Construct a TdsCore object. |
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use JtdsCallableStatement | |
| net.sourceforge.jtds.jdbcx.proxy | |
| Uses of JtdsCallableStatement in net.sourceforge.jtds.jdbcx.proxy |
| Fields in net.sourceforge.jtds.jdbcx.proxy declared as JtdsCallableStatement | |
private JtdsCallableStatement |
CallableStatementProxy._callableStatement
|
| Constructors in net.sourceforge.jtds.jdbcx.proxy with parameters of type JtdsCallableStatement | |
CallableStatementProxy(ConnectionProxy connection,
JtdsCallableStatement callableStatement)
|
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use SharedSocket.VirtualSocket | |
| net.sourceforge.jtds.jdbc | |
| Uses of SharedSocket.VirtualSocket in net.sourceforge.jtds.jdbc |
| Methods in net.sourceforge.jtds.jdbc that return SharedSocket.VirtualSocket | |
private SharedSocket.VirtualSocket |
SharedSocket.lookup(int streamId)
Retrieves the virtual socket with the given id. |
| Methods in net.sourceforge.jtds.jdbc with parameters of type SharedSocket.VirtualSocket | |
private void |
SharedSocket.enqueueInput(SharedSocket.VirtualSocket vsock,
byte[] buffer)
Save a packet buffer in a memory queue or to a disk queue if the global memory limit for the driver has been exceeded. |
private byte[] |
SharedSocket.dequeueInput(SharedSocket.VirtualSocket vsock)
Read a cached packet from the in memory queue or from a disk based queue. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use TdsCore.TableMetaData | |
| net.sourceforge.jtds.jdbc | |
| Uses of TdsCore.TableMetaData in net.sourceforge.jtds.jdbc |
| Fields in net.sourceforge.jtds.jdbc declared as TdsCore.TableMetaData | |
private TdsCore.TableMetaData[] |
TdsCore.tables
The array of table names associated with this result. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use TdsCore.TdsToken | |
| net.sourceforge.jtds.jdbc | |
| Uses of TdsCore.TdsToken in net.sourceforge.jtds.jdbc |
| Fields in net.sourceforge.jtds.jdbc declared as TdsCore.TdsToken | |
private TdsCore.TdsToken |
TdsCore.currentToken
The descriptor object for the current TDS token. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use JtdsResultSet | |
| net.sourceforge.jtds.jdbc | |
| Uses of JtdsResultSet in net.sourceforge.jtds.jdbc |
| Subclasses of JtdsResultSet in net.sourceforge.jtds.jdbc | |
class |
CachedResultSet
A memory cached scrollable/updateable result set. |
class |
MSCursorResultSet
This class extends the JtdsResultSet to support scrollable and or updateable cursors on Microsoft servers. |
| Fields in net.sourceforge.jtds.jdbc declared as JtdsResultSet | |
protected JtdsResultSet |
JtdsStatement.currentResult
The current ResultSet. |
protected JtdsResultSet |
JtdsStatement.genKeyResultSet
Dummy result set for getGeneratedKeys. |
| Methods in net.sourceforge.jtds.jdbc with parameters of type JtdsResultSet | |
private static void |
JtdsDatabaseMetaData.upperCaseColumnNames(JtdsResultSet results)
Uppercase all column names. |
private static CachedResultSet |
JtdsDatabaseMetaData.createTypeInfoResultSet(JtdsResultSet rs,
boolean useLOBs)
|
| Constructors in net.sourceforge.jtds.jdbc with parameters of type JtdsResultSet | |
CachedResultSet(JtdsResultSet rs,
boolean load)
Creates a cached result set with the same columns (and optionally data) as an existing result set. |
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use ParamInfo | |
| net.sourceforge.jtds.jdbc | |
| Uses of ParamInfo in net.sourceforge.jtds.jdbc |
| Fields in net.sourceforge.jtds.jdbc declared as ParamInfo | |
private static ParamInfo[] |
TdsCore.EMPTY_PARAMETER_INFO
Used to optimize the TdsCore.getParameters() call |
private ParamInfo |
TdsCore.returnParam
The return parameter meta data object for the current procedure call. |
private ParamInfo[] |
TdsCore.parameters
The array of parameter meta data objects for the current procedure call. |
private ParamInfo[] |
ProcEntry.paramMetaData
Parameter meta data (Sybase only). |
private ParamInfo[] |
ParameterMetaDataImpl.parameterList
|
private ParamInfo[] |
MSCursorResultSet.insertRow
The "insert row". |
private ParamInfo[] |
MSCursorResultSet.updateRow
The "update row". |
private ParamInfo |
MSCursorResultSet.PARAM_CURSOR_HANDLE
Cursor handle parameter. |
private ParamInfo |
MSCursorResultSet.PARAM_FETCHTYPE
sp_cursorfetch fetchtype parameter. |
private ParamInfo |
MSCursorResultSet.PARAM_ROWNUM_IN
sp_cursorfetch rownum IN parameter (for actual fetches). |
private ParamInfo |
MSCursorResultSet.PARAM_NUMROWS_IN
sp_cursorfetch numrows IN parameter (for actual fetches). |
private ParamInfo |
MSCursorResultSet.PARAM_ROWNUM_OUT
sp_cursorfetch rownum OUT parameter (for FETCH_INFO). |
private ParamInfo |
MSCursorResultSet.PARAM_NUMROWS_OUT
sp_cursorfetch numrows OUT parameter (for FETCH_INFO). |
private ParamInfo |
MSCursorResultSet.PARAM_OPTYPE
sp_cursor optype parameter. |
private ParamInfo |
MSCursorResultSet.PARAM_ROWNUM
sp_cursor rownum parameter. |
private ParamInfo |
MSCursorResultSet.PARAM_TABLE
sp_cursor table parameter. |
protected ParamInfo[] |
JtdsPreparedStatement.parameters
The parameter list for the call. |
protected ParamInfo[] |
JtdsPreparedStatement.paramMetaData
The cached parameter meta data. |
protected ParamInfo[] |
CachedResultSet.insertRow
Buffer row used for inserts. |
protected ParamInfo[] |
CachedResultSet.updateRow
The "update" row. |
protected ParamInfo[] |
CachedResultSet.procedureParams
Original parameters. |
| Methods in net.sourceforge.jtds.jdbc that return ParamInfo | |
(package private) ParamInfo[] |
TdsCore.getParameters()
Retrieve the parameter meta data from a Sybase prepare. |
ParamInfo[] |
ProcEntry.getParamMetaData()
Retrieves the parameter meta data array. |
private ParamInfo |
ParameterMetaDataImpl.getParameter(int param)
|
protected ParamInfo |
JtdsPreparedStatement.getParameter(int parameterIndex)
Check the supplied index and return the selected parameter. |
protected static ParamInfo |
CachedResultSet.buildParameter(int pos,
ColInfo info,
java.lang.Object value,
boolean isUnicode)
Creates a parameter object for an UPDATE, DELETE or INSERT statement. |
(package private) ParamInfo[] |
CachedResultSet.buildWhereClause(java.lang.StringBuffer sql,
java.util.ArrayList params,
boolean select)
Builds a WHERE clause for UPDATE or DELETE statements. |
| Methods in net.sourceforge.jtds.jdbc with parameters of type ParamInfo | |
(package private) static void |
TdsData.getNativeType(ConnectionJDBC2 connection,
ParamInfo pi)
Retrieve the TDS native type code for the parameter. |
(package private) static int |
TdsData.getTds5ParamSize(java.lang.String charset,
boolean isWideChar,
ParamInfo pi,
boolean useParamNames)
Calculate the size of the parameter descriptor array for TDS 5 packets. |
(package private) static void |
TdsData.writeTds5ParamFmt(RequestStream out,
java.lang.String charset,
boolean isWideChar,
ParamInfo pi,
boolean useParamNames)
Write a TDS 5 parameter format descriptor. |
(package private) static void |
TdsData.writeTds5Param(RequestStream out,
CharsetInfo charsetInfo,
ParamInfo pi)
Write the actual TDS 5 parameter data. |
(package private) static void |
TdsData.putCollation(RequestStream out,
ParamInfo pi)
TDS 8 requires collation information for char data descriptors. |
(package private) static void |
TdsData.writeParam(RequestStream out,
CharsetInfo charsetInfo,
byte[] collation,
ParamInfo pi)
Write a parameter to the server request stream. |
(package private) void |
TdsCore.executeSQL(java.lang.String sql,
java.lang.String procName,
ParamInfo[] parameters,
boolean noMetaData,
int timeOut,
int maxRows,
int maxFieldSize,
boolean sendNow)
Send an SQL statement with optional parameters to the server. |
(package private) java.lang.String |
TdsCore.microsoftPrepare(java.lang.String sql,
ParamInfo[] params,
boolean needCursor,
int resultSetType,
int resultSetConcurrency)
Prepares the SQL for use with Microsoft server. |
(package private) java.lang.String |
TdsCore.sybasePrepare(java.lang.String sql,
ParamInfo[] params)
Creates a light weight stored procedure on a Sybase server. |
private void |
TdsCore.executeSQL42(java.lang.String sql,
java.lang.String procName,
ParamInfo[] parameters,
boolean noMetaData,
boolean sendNow)
Execute SQL using TDS 4.2 protocol. |
private void |
TdsCore.executeSQL50(java.lang.String sql,
java.lang.String procName,
ParamInfo[] parameters)
Execute SQL using TDS 5.0 protocol. |
private void |
TdsCore.executeSQL70(java.lang.String sql,
java.lang.String procName,
ParamInfo[] parameters,
boolean noMetaData,
boolean sendNow)
Execute SQL using TDS 7.0 protocol. |
(package private) static java.lang.String |
Support.getStatementKey(java.lang.String sql,
ParamInfo[] params,
int serverType,
java.lang.String catalog,
boolean autoCommit,
boolean cursor)
Generates a unique statement key for a given SQL statement. |
(package private) static java.lang.String |
Support.getParameterDefinitions(ParamInfo[] parameters)
Constructs a parameter definition string for use with sp_executesql, sp_prepare, sp_prepexec, sp_cursoropen, sp_cursorprepare and sp_cursorprepexec. |
(package private) static java.lang.String |
Support.substituteParamMarkers(java.lang.String sql,
ParamInfo[] list)
Update the SQL string and replace the ? |
(package private) static java.lang.String |
Support.substituteParameters(java.lang.String sql,
ParamInfo[] list,
ConnectionJDBC2 connection)
Substitute actual data for the parameter markers to simulate parameter substitution in a PreparedStatement. |
void |
ProcEntry.setParamMetaData(ParamInfo[] paramMetaData)
Sets the parameter meta data. |
private void |
MSCursorResultSet.cursorCreate(java.lang.String sql,
java.lang.String procName,
ParamInfo[] parameters)
Create a new Cursor result set using the internal sp_cursoropen procedure. |
private void |
MSCursorResultSet.cursor(java.lang.Integer opType,
ParamInfo[] row)
Support general cursor operations such as delete, update etc. |
protected java.sql.ResultSet |
JtdsStatement.executeSQLQuery(java.lang.String sql,
java.lang.String spName,
ParamInfo[] params,
boolean useCursor)
Executes SQL to obtain a result set. |
protected boolean |
JtdsStatement.executeSQL(java.lang.String sql,
java.lang.String spName,
ParamInfo[] params,
boolean returnKeys,
boolean update,
boolean useCursor)
Executes any type of SQL. |
(package private) void |
JtdsPreparedStatement.setParamMetaData(ParamInfo[] value)
Update the cached parameter meta data information. |
(package private) java.lang.String |
ConnectionJDBC2.prepareSQL(JtdsPreparedStatement pstmt,
java.lang.String sql,
ParamInfo[] params,
boolean returnKeys,
boolean cursorNeeded)
Try to convert the SQL statement into a statement prepare. |
| Constructors in net.sourceforge.jtds.jdbc with parameters of type ParamInfo | |
ParameterMetaDataImpl(ParamInfo[] parameterList,
ConnectionJDBC2 connection)
|
|
MSCursorResultSet(JtdsStatement statement,
java.lang.String sql,
java.lang.String procName,
ParamInfo[] procedureParams,
int resultSetType,
int concurrency)
Construct a cursor result set using Microsoft sp_cursorcreate etc. |
|
CachedResultSet(JtdsStatement statement,
java.lang.String sql,
java.lang.String procName,
ParamInfo[] procedureParams,
int resultSetType,
int concurrency)
Constructs a new cached result set. |
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use ConnectionJDBC2 | |
| net.sourceforge.jtds.jdbc | |
| net.sourceforge.jtds.jdbc.cache | |
| net.sourceforge.jtds.jdbcx.proxy | |
| Uses of ConnectionJDBC2 in net.sourceforge.jtds.jdbc |
| Subclasses of ConnectionJDBC2 in net.sourceforge.jtds.jdbc | |
class |
ConnectionJDBC3
Implements JDBC 3.0 specific functionality. |
| Fields in net.sourceforge.jtds.jdbc declared as ConnectionJDBC2 | |
private ConnectionJDBC2 |
TdsCore.connection
The Connection object that created this object. |
private ConnectionJDBC2 |
SQLParser.connection
Connection object for server specific parsing. |
protected ConnectionJDBC2 |
JtdsStatement.connection
The connection owning this statement object. |
private ConnectionJDBC2 |
JtdsDatabaseMetaData.connection
|
protected ConnectionJDBC2 |
CachedResultSet.connection
The parent connection object |
| Methods in net.sourceforge.jtds.jdbc that return ConnectionJDBC2 | |
private static ConnectionJDBC2 |
Support.getConnection(java.lang.Object callerReference)
Returns the connection for a given ResultSet,
Statement or Connection object. |
private ConnectionJDBC2 |
JtdsResultSet.getConnection()
Returns the ConnectionJDBC2 object referenced by the
JtdsResultSet.statement instance variable. |
| Methods in net.sourceforge.jtds.jdbc with parameters of type ConnectionJDBC2 | |
(package private) static void |
TdsData.setColumnCharset(ColInfo ci,
ConnectionJDBC2 connection)
Set the charsetInfo field of ci according to
the value of its collation field.
|
(package private) static java.lang.Object |
TdsData.readData(ConnectionJDBC2 connection,
ResponseStream in,
ColInfo ci)
Read the TDS data item from the Response Stream. |
(package private) static void |
TdsData.getNativeType(ConnectionJDBC2 connection,
ParamInfo pi)
Retrieve the TDS native type code for the parameter. |
private static java.lang.Object |
TdsData.getVariant(ConnectionJDBC2 connection,
ResponseStream in)
Read a MSQL 2000 sql_variant data value from the input stream. |
(package private) static void |
Support.embedData(java.lang.StringBuffer buf,
java.lang.Object value,
boolean isUnicode,
ConnectionJDBC2 connection)
Embed the data object as a string literal in the buffer supplied. |
(package private) static java.lang.String |
Support.substituteParameters(java.lang.String sql,
ParamInfo[] list,
ConnectionJDBC2 connection)
Substitute actual data for the parameter markers to simulate parameter substitution in a PreparedStatement. |
(package private) static java.lang.String[] |
SQLParser.parse(java.lang.String sql,
java.util.ArrayList paramList,
ConnectionJDBC2 connection,
boolean extractTable)
Parse the SQL statement processing JDBC escapes and parameter markers. |
private static SimpleLRUCache |
SQLParser.getCache(ConnectionJDBC2 connection)
Retrieves the statement cache, creating it if required. |
private java.net.Socket |
SharedSocket.createSocketForJDBC3(ConnectionJDBC2 connection)
Creates a SharedSocket.VirtualSocket through reflection when Driver.JDBC3
is true. |
private SharedSocket |
ConnectionJDBC2.createNamedPipe(ConnectionJDBC2 connection)
Creates a SharedSocket object representing a connection to a named
pipe. |
| Constructors in net.sourceforge.jtds.jdbc with parameters of type ConnectionJDBC2 | |
TdsCore(ConnectionJDBC2 connection,
SQLDiagnostic messages)
Construct a TdsCore object. |
|
SQLParser(java.lang.String sqlIn,
java.util.ArrayList paramList,
ConnectionJDBC2 connection)
Constructs a new parser object to process the supplied SQL. |
|
SharedSocket(ConnectionJDBC2 connection)
Construct a SharedSocket object specifying host name and
port. |
|
SharedNamedPipe(ConnectionJDBC2 connection)
Creates a new instance of SharedNamedPipe. |
|
SharedLocalNamedPipe(ConnectionJDBC2 connection)
Creates a new instance of SharedLocalNamedPipe. |
|
ParameterMetaDataImpl(ParamInfo[] parameterList,
ConnectionJDBC2 connection)
|
|
JtdsStatement(ConnectionJDBC2 connection,
int resultSetType,
int resultSetConcurrency)
Construct a new Statement object. |
|
JtdsPreparedStatement(ConnectionJDBC2 connection,
java.lang.String sql,
int resultSetType,
int concurrency,
boolean returnKeys)
Construct a new preparedStatement object. |
|
JtdsDatabaseMetaData(ConnectionJDBC2 connection)
|
|
JtdsCallableStatement(ConnectionJDBC2 connection,
java.lang.String sql,
int resultSetType,
int concurrency)
Construct a CallableStatement object. |
|
ClobImpl(ConnectionJDBC2 connection)
Constructs a new empty Clob instance. |
|
ClobImpl(ConnectionJDBC2 connection,
java.lang.String str)
Constructs a new initialized Clob instance. |
|
BlobImpl(ConnectionJDBC2 connection)
Constructs a new empty Blob instance. |
|
BlobImpl(ConnectionJDBC2 connection,
byte[] bytes)
Constructs a new Blob instance initialized with data. |
|
| Uses of ConnectionJDBC2 in net.sourceforge.jtds.jdbc.cache |
| Constructors in net.sourceforge.jtds.jdbc.cache with parameters of type ConnectionJDBC2 | |
SQLCacheKey(java.lang.String sql,
ConnectionJDBC2 connection)
|
|
| Uses of ConnectionJDBC2 in net.sourceforge.jtds.jdbcx.proxy |
| Fields in net.sourceforge.jtds.jdbcx.proxy declared as ConnectionJDBC2 | |
private ConnectionJDBC2 |
ConnectionProxy._connection
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use SavepointImpl | |
| net.sourceforge.jtds.jdbc | |
| Uses of SavepointImpl in net.sourceforge.jtds.jdbc |
| Methods in net.sourceforge.jtds.jdbc with parameters of type SavepointImpl | |
private void |
ConnectionJDBC3.setSavepoint(SavepointImpl savepoint)
Add a savepoint to the list maintained by this connection. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use TdsData.TypeInfo | |
| net.sourceforge.jtds.jdbc | |
| Uses of TdsData.TypeInfo in net.sourceforge.jtds.jdbc |
| Fields in net.sourceforge.jtds.jdbc declared as TdsData.TypeInfo | |
private static TdsData.TypeInfo[] |
TdsData.types
Array of TDS data type descriptors. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use TdsCore | |
| net.sourceforge.jtds.jdbc | |
| Uses of TdsCore in net.sourceforge.jtds.jdbc |
| Fields in net.sourceforge.jtds.jdbc declared as TdsCore | |
protected TdsCore |
JtdsStatement.tds
The TDS object used for server access. |
private TdsCore |
ConnectionJDBC2.baseTds
The cored TDS protocol object. |
private TdsCore |
ConnectionJDBC2.cachedTds
A cached TdsCore instance to reuse on new statements. |
protected TdsCore |
CachedResultSet.cursorTds
Cursor TdsCore object. |
protected TdsCore |
CachedResultSet.updateTds
Updates TdsCore object used for positioned updates. |
| Methods in net.sourceforge.jtds.jdbc that return TdsCore | |
(package private) TdsCore |
JtdsStatement.getTds()
Get the Statement's TDS object. |
(package private) TdsCore |
ConnectionJDBC2.getCachedTds()
Retrieves the cached TdsCore or null if
nothing is cached and resets the cache (sets it to null). |
| Methods in net.sourceforge.jtds.jdbc with parameters of type TdsCore | |
private void |
MSCursorResultSet.processOutput(TdsCore tds,
boolean setMeta)
Processes the output of a cursor open or fetch operation. |
(package private) void |
ConnectionJDBC2.releaseTds(TdsCore tds)
Releases (either closes or caches) a TdsCore. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use CachedResultSet | |
| net.sourceforge.jtds.jdbc | |
| Uses of CachedResultSet in net.sourceforge.jtds.jdbc |
| Methods in net.sourceforge.jtds.jdbc that return CachedResultSet | |
private static CachedResultSet |
JtdsDatabaseMetaData.createTypeInfoResultSet(JtdsResultSet rs,
boolean useLOBs)
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use TypeInfo | |
| net.sourceforge.jtds.test | |
| Uses of TypeInfo in net.sourceforge.jtds.test |
| Methods in net.sourceforge.jtds.test with parameters of type TypeInfo | |
private void |
TypeInfoTest.assertComparesLessThan(TypeInfo t1,
TypeInfo t2)
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use JtdsPreparedStatement | |
| net.sourceforge.jtds.jdbc | |
| net.sourceforge.jtds.jdbcx.proxy | |
| Uses of JtdsPreparedStatement in net.sourceforge.jtds.jdbc |
| Subclasses of JtdsPreparedStatement in net.sourceforge.jtds.jdbc | |
class |
JtdsCallableStatement
jTDS implementation of the java.sql.CallableStatement interface. |
| Methods in net.sourceforge.jtds.jdbc with parameters of type JtdsPreparedStatement | |
(package private) java.lang.String |
ConnectionJDBC2.prepareSQL(JtdsPreparedStatement pstmt,
java.lang.String sql,
ParamInfo[] params,
boolean returnKeys,
boolean cursorNeeded)
Try to convert the SQL statement into a statement prepare. |
| Uses of JtdsPreparedStatement in net.sourceforge.jtds.jdbcx.proxy |
| Fields in net.sourceforge.jtds.jdbcx.proxy declared as JtdsPreparedStatement | |
private JtdsPreparedStatement |
PreparedStatementProxy._preparedStatement
|
| Constructors in net.sourceforge.jtds.jdbcx.proxy with parameters of type JtdsPreparedStatement | |
PreparedStatementProxy(ConnectionProxy connection,
JtdsPreparedStatement preparedStatement)
|
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use SharedSocket | |
| net.sourceforge.jtds.jdbc | |
| Uses of SharedSocket in net.sourceforge.jtds.jdbc |
| Subclasses of SharedSocket in net.sourceforge.jtds.jdbc | |
class |
SharedLocalNamedPipe
This class implements inter-process communication (IPC) to the database server using local named pipes (will only work on Windows). |
class |
SharedNamedPipe
This class implements inter-process communication (IPC) to the database server using named pipes. |
| Fields in net.sourceforge.jtds.jdbc declared as SharedSocket | |
private SharedSocket |
TdsCore.socket
The Shared network socket object. |
private SharedSocket |
ResponseStream.socket
The shared network socket. |
private SharedSocket |
RequestStream.socket
The shared network socket. |
private SharedSocket |
ConnectionJDBC2.socket
The network TCP/IP socket. |
| Methods in net.sourceforge.jtds.jdbc that return SharedSocket | |
private SharedSocket |
ConnectionJDBC2.createNamedPipe(ConnectionJDBC2 connection)
Creates a SharedSocket object representing a connection to a named
pipe. |
(package private) SharedSocket |
ConnectionJDBC2.getSocket()
Retrive the shared socket. |
| Constructors in net.sourceforge.jtds.jdbc with parameters of type SharedSocket | |
ResponseStream(SharedSocket socket,
int streamId,
int bufferSize)
Constructs a RequestStream object. |
|
RequestStream(SharedSocket socket,
int streamId,
int bufferSize,
int maxPrecision)
Construct a RequestStream object. |
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use ResponseStream | |
| net.sourceforge.jtds.jdbc | |
| Uses of ResponseStream in net.sourceforge.jtds.jdbc |
| Fields in net.sourceforge.jtds.jdbc declared as ResponseStream | |
private ResponseStream |
TdsCore.in
The input server response stream. |
(package private) ResponseStream |
ResponseStream.TdsInputStream.tds
The underlying ResponseStream. |
| Methods in net.sourceforge.jtds.jdbc that return ResponseStream | |
(package private) ResponseStream |
SharedSocket.getResponseStream(RequestStream requestStream,
int bufferSize)
Obtain an instance of a server response stream for this socket. |
| Methods in net.sourceforge.jtds.jdbc with parameters of type ResponseStream | |
(package private) static int |
TdsData.getCollation(ResponseStream in,
ColInfo ci)
TDS 8 supplies collation information for character data types. |
(package private) static int |
TdsData.readType(ResponseStream in,
ColInfo ci)
Read the TDS datastream and populate the ColInfo parameter with data type and related information. |
(package private) static java.lang.Object |
TdsData.readData(ConnectionJDBC2 connection,
ResponseStream in,
ColInfo ci)
Read the TDS data item from the Response Stream. |
private static java.lang.Object |
TdsData.getDatetimeValue(ResponseStream in,
int type)
Get a DATETIME value from the server response stream. |
private static java.lang.Object |
TdsData.getMoneyValue(ResponseStream in,
int type)
Read a MONEY value from the server response stream. |
private static java.lang.Object |
TdsData.getVariant(ConnectionJDBC2 connection,
ResponseStream in)
Read a MSQL 2000 sql_variant data value from the input stream. |
| Constructors in net.sourceforge.jtds.jdbc with parameters of type ResponseStream | |
ResponseStream.TdsInputStream(ResponseStream tds,
int maxLen)
Creates a TdsInputStream instance. |
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use Semaphore | |
| net.sourceforge.jtds.jdbc | |
| Uses of Semaphore in net.sourceforge.jtds.jdbc |
| Fields in net.sourceforge.jtds.jdbc declared as Semaphore | |
private Semaphore |
TdsCore.connectionLock
Mutual exclusion lock on connection. |
private Semaphore |
ConnectionJDBC2.mutex
Mutual exclusion lock to control access to connection. |
| Methods in net.sourceforge.jtds.jdbc that return Semaphore | |
(package private) Semaphore |
ConnectionJDBC2.getMutex()
Retrieves the connection mutex and acquires an exclusive lock on the network connection. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use JtdsStatement | |
| net.sourceforge.jtds.jdbc | |
| net.sourceforge.jtds.jdbcx.proxy | |
| Uses of JtdsStatement in net.sourceforge.jtds.jdbc |
| Subclasses of JtdsStatement in net.sourceforge.jtds.jdbc | |
class |
JtdsCallableStatement
jTDS implementation of the java.sql.CallableStatement interface. |
class |
JtdsPreparedStatement
jTDS implementation of the java.sql.PreparedStatement interface. |
| Fields in net.sourceforge.jtds.jdbc declared as JtdsStatement | |
protected JtdsStatement |
JtdsResultSet.statement
The parent statement. |
| Methods in net.sourceforge.jtds.jdbc with parameters of type JtdsStatement | |
(package private) void |
ConnectionJDBC2.removeStatement(JtdsStatement statement)
Removes a statement object from the list maintained by the connection and cleans up the statement cache if necessary. |
(package private) void |
ConnectionJDBC2.addStatement(JtdsStatement statement)
Adds a statement object to the list maintained by the connection. |
| Constructors in net.sourceforge.jtds.jdbc with parameters of type JtdsStatement | |
MSCursorResultSet(JtdsStatement statement,
java.lang.String sql,
java.lang.String procName,
ParamInfo[] procedureParams,
int resultSetType,
int concurrency)
Construct a cursor result set using Microsoft sp_cursorcreate etc. |
|
JtdsResultSet(JtdsStatement statement,
int resultSetType,
int concurrency,
ColInfo[] columns)
Construct a simple result set from a statement, metadata or generated keys. |
|
CachedResultSet(JtdsStatement statement,
java.lang.String sql,
java.lang.String procName,
ParamInfo[] procedureParams,
int resultSetType,
int concurrency)
Constructs a new cached result set. |
|
CachedResultSet(JtdsStatement statement,
java.lang.String[] colName,
int[] colType)
Constructs a cached result set based on locally generated data. |
|
CachedResultSet(JtdsStatement statement,
ColInfo[] columns,
java.lang.Object[] data)
Creates a cached result set containing one row. |
|
| Uses of JtdsStatement in net.sourceforge.jtds.jdbcx.proxy |
| Fields in net.sourceforge.jtds.jdbcx.proxy declared as JtdsStatement | |
private JtdsStatement |
StatementProxy._statement
|
| Constructors in net.sourceforge.jtds.jdbcx.proxy with parameters of type JtdsStatement | |
StatementProxy(ConnectionProxy connection,
JtdsStatement statement)
|
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use RequestStream | |
| net.sourceforge.jtds.jdbc | |
| Uses of RequestStream in net.sourceforge.jtds.jdbc |
| Fields in net.sourceforge.jtds.jdbc declared as RequestStream | |
private RequestStream |
TdsCore.out
The output server request stream. |
| Methods in net.sourceforge.jtds.jdbc that return RequestStream | |
(package private) RequestStream |
SharedSocket.getRequestStream(int bufferSize,
int maxPrecision)
Obtain an instance of a server request stream for this socket. |
| Methods in net.sourceforge.jtds.jdbc with parameters of type RequestStream | |
(package private) static void |
TdsData.writeTds5ParamFmt(RequestStream out,
java.lang.String charset,
boolean isWideChar,
ParamInfo pi,
boolean useParamNames)
Write a TDS 5 parameter format descriptor. |
(package private) static void |
TdsData.writeTds5Param(RequestStream out,
CharsetInfo charsetInfo,
ParamInfo pi)
Write the actual TDS 5 parameter data. |
(package private) static void |
TdsData.putCollation(RequestStream out,
ParamInfo pi)
TDS 8 requires collation information for char data descriptors. |
(package private) static void |
TdsData.writeParam(RequestStream out,
CharsetInfo charsetInfo,
byte[] collation,
ParamInfo pi)
Write a parameter to the server request stream. |
private static void |
TdsData.putDateTimeValue(RequestStream out,
DateTime value)
Output a java.sql.Date/Time/Timestamp value to the server as a Sybase datetime value. |
(package private) ResponseStream |
SharedSocket.getResponseStream(RequestStream requestStream,
int bufferSize)
Obtain an instance of a server response stream for this socket. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use ColInfo | |
| net.sourceforge.jtds.jdbc | |
| Uses of ColInfo in net.sourceforge.jtds.jdbc |
| Fields in net.sourceforge.jtds.jdbc declared as ColInfo | |
private ColInfo[] |
TdsCore.columns
The array of column meta data objects for this result set. |
(package private) ColInfo[] |
TdsCore.TdsToken.dynamParamInfo
The dynamic parameters from the last TDS_DYNAMIC token. |
private ColInfo[] |
ProcEntry.colMetaData
Column meta data (Sybase only). |
protected ColInfo[] |
JtdsStatement.colMetaData
The cached column meta data. |
private ColInfo[] |
JtdsResultSetMetaData.columns
|
protected ColInfo[] |
JtdsResultSet.columns
The array of column descriptors. |
| Methods in net.sourceforge.jtds.jdbc that return ColInfo | |
(package private) ColInfo[] |
TdsCore.getColumns()
Retrieve the current result set column descriptors. |
ColInfo[] |
ProcEntry.getColMetaData()
Retrieves the column meta data array. |
(package private) ColInfo |
JtdsResultSetMetaData.getColumn(int column)
Return the column descriptor given a column index. |
protected ColInfo[] |
JtdsResultSet.getColumns()
Retrieve the column descriptor array. |
protected ColInfo[] |
JtdsResultSet.copyInfo(ColInfo[] info)
Copy an existing result set column descriptor array. |
| Methods in net.sourceforge.jtds.jdbc with parameters of type ColInfo | |
(package private) static int |
TdsData.getCollation(ResponseStream in,
ColInfo ci)
TDS 8 supplies collation information for character data types. |
(package private) static void |
TdsData.setColumnCharset(ColInfo ci,
ConnectionJDBC2 connection)
Set the charsetInfo field of ci according to
the value of its collation field.
|
(package private) static int |
TdsData.readType(ResponseStream in,
ColInfo ci)
Read the TDS datastream and populate the ColInfo parameter with data type and related information. |
(package private) static java.lang.Object |
TdsData.readData(ConnectionJDBC2 connection,
ResponseStream in,
ColInfo ci)
Read the TDS data item from the Response Stream. |
(package private) static boolean |
TdsData.isSigned(ColInfo ci)
Retrieve the signed status of the column. |
(package private) static boolean |
TdsData.isCollation(ColInfo ci)
Retrieve the collation status of the column. |
(package private) static boolean |
TdsData.isCurrency(ColInfo ci)
Retrieve the currency status of the column. |
(package private) static boolean |
TdsData.isSearchable(ColInfo ci)
Retrieve the searchable status of the column. |
(package private) static boolean |
TdsData.isUnicode(ColInfo ci)
Determines whether the column is Unicode encoded. |
(package private) static void |
TdsData.fillInType(ColInfo ci)
Fill in the TDS native type code and all other fields for a ColInfo instance with the JDBC type set. |
(package private) void |
TdsCore.setColumns(ColInfo[] columns)
Sets the column meta data. |
void |
ProcEntry.setColMetaData(ColInfo[] colMetaData)
Sets the column meta data. |
protected static int |
JtdsResultSet.getColumnCount(ColInfo[] columns)
Retrieve the column count excluding hidden columns |
protected ColInfo[] |
JtdsResultSet.copyInfo(ColInfo[] info)
Copy an existing result set column descriptor array. |
(package private) void |
JtdsPreparedStatement.setColMetaData(ColInfo[] value)
Update the cached column meta data information. |
protected static ParamInfo |
CachedResultSet.buildParameter(int pos,
ColInfo info,
java.lang.Object value,
boolean isUnicode)
Creates a parameter object for an UPDATE, DELETE or INSERT statement. |
| Constructors in net.sourceforge.jtds.jdbc with parameters of type ColInfo | |
ParamInfo(ColInfo ci,
java.lang.String name,
java.lang.Object value,
int length)
Construct a parameter based on a result set column. |
|
JtdsResultSetMetaData(ColInfo[] columns,
int columnCount,
boolean useLOBs)
Construct ResultSetMetaData object over the current ColInfo array. |
|
JtdsResultSet(JtdsStatement statement,
int resultSetType,
int concurrency,
ColInfo[] columns)
Construct a simple result set from a statement, metadata or generated keys. |
|
CachedResultSet(JtdsStatement statement,
ColInfo[] columns,
java.lang.Object[] data)
Creates a cached result set containing one row. |
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use DateTime | |
| net.sourceforge.jtds.jdbc | |
| Uses of DateTime in net.sourceforge.jtds.jdbc |
| Methods in net.sourceforge.jtds.jdbc with parameters of type DateTime | |
private static void |
TdsData.putDateTimeValue(RequestStream out,
DateTime value)
Output a java.sql.Date/Time/Timestamp value to the server as a Sybase datetime value. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use Driver | |
| net.sourceforge.jtds.jdbcx | |
| Uses of Driver in net.sourceforge.jtds.jdbcx |
| Fields in net.sourceforge.jtds.jdbcx declared as Driver | |
private static Driver |
JtdsDataSource.driver
Driver instance used for obtaining connections. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use ProcEntry | |
| net.sourceforge.jtds.jdbc | |
| net.sourceforge.jtds.jdbc.cache | |
| Uses of ProcEntry in net.sourceforge.jtds.jdbc |
| Methods in net.sourceforge.jtds.jdbc with parameters of type ProcEntry | |
(package private) void |
ConnectionJDBC3.addCachedProcedure(java.lang.String key,
ProcEntry proc)
Add a stored procedure to the cache. |
(package private) void |
ConnectionJDBC2.addCachedProcedure(java.lang.String key,
ProcEntry proc)
Add a stored procedure to the cache. |
| Uses of ProcEntry in net.sourceforge.jtds.jdbc.cache |
| Fields in net.sourceforge.jtds.jdbc.cache declared as ProcEntry | |
(package private) ProcEntry |
ProcedureCache.CacheEntry.value
|
| Constructors in net.sourceforge.jtds.jdbc.cache with parameters of type ProcEntry | |
ProcedureCache.CacheEntry(java.lang.String key,
ProcEntry value)
Constructs a new cache entry encapsulating the supplied key and value. |
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use ProtocolException | |
| net.sourceforge.jtds.jdbc | |
| Uses of ProtocolException in net.sourceforge.jtds.jdbc |
| Methods in net.sourceforge.jtds.jdbc that throw ProtocolException | |
(package private) static int |
TdsData.readType(ResponseStream in,
ColInfo ci)
Read the TDS datastream and populate the ColInfo parameter with data type and related information. |
(package private) static java.lang.Object |
TdsData.readData(ConnectionJDBC2 connection,
ResponseStream in,
ColInfo ci)
Read the TDS data item from the Response Stream. |
private static java.lang.Object |
TdsData.getDatetimeValue(ResponseStream in,
int type)
Get a DATETIME value from the server response stream. |
private static java.lang.Object |
TdsData.getMoneyValue(ResponseStream in,
int type)
Read a MONEY value from the server response stream. |
private static java.lang.Object |
TdsData.getVariant(ConnectionJDBC2 connection,
ResponseStream in)
Read a MSQL 2000 sql_variant data value from the input stream. |
private void |
TdsCore.tdsInvalidToken()
Report unsupported TDS token in input stream. |
private void |
TdsCore.tds5ParamFmt2Token()
Process TDS 5 Sybase 12+ Dynamic results parameter descriptor. |
private void |
TdsCore.tds5WideResultToken()
Process Sybase 12+ wide result token which provides enhanced column meta data. |
private void |
TdsCore.tds7ResultToken()
Process a TDS 7.0 result set token. |
private void |
TdsCore.tds4ColFormatToken()
Process a TDS 4.2 column format token. |
private void |
TdsCore.tdsTableNameToken()
Process a table name token. |
private void |
TdsCore.tdsColumnInfoToken()
Process a column infomation token. |
private void |
TdsCore.tdsOutputParamToken()
Process output parameters. |
private void |
TdsCore.tdsRowToken()
Process a row data token. |
private void |
TdsCore.tds5ParamsToken()
Process TDS 5.0 Params Token. |
private void |
TdsCore.tdsCapabilityToken()
Processes a TDS 5.0 capability token. |
private void |
TdsCore.tds5ParamFmtToken()
Process TDS 5 Dynamic results parameter descriptors. |
private void |
TdsCore.tdsNtlmAuthToken()
Process a NTLM Authentication challenge. |
private void |
TdsCore.tds5ResultToken()
Process a TDS 5.0 result set packet. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.TdsData
Implement TDS data types and related I/O logic.
Implementation notes:
| Nested Class Summary | |
private static class |
TdsData.TypeInfo
This class implements a descriptor for TDS data types; |
| Field Summary | |
(package private) static int |
DEFAULT_PRECISION_28
Default precision for SQL Server 6.5 and 7. |
(package private) static int |
DEFAULT_PRECISION_38
Default precision for Sybase and SQL Server 2000 and newer. |
(package private) static int |
DEFAULT_SCALE
Default Decimal Scale. |
private static int |
MS_LONGVAR_MAX
|
private static int |
SYB_CHUNK_SIZE
|
private static int |
SYB_LONGVAR_MAX
|
private static int |
SYBBINARY
|
private static int |
SYBBIT
|
private static int |
SYBBITN
|
private static int |
SYBCHAR
|
private static int |
SYBDATE
|
private static int |
SYBDATEN
|
private static int |
SYBDATETIME
|
private static int |
SYBDATETIME4
|
private static int |
SYBDATETIMN
|
private static int |
SYBDECIMAL
|
private static int |
SYBFLT8
|
private static int |
SYBFLTN
|
private static int |
SYBIMAGE
|
private static int |
SYBINT1
|
private static int |
SYBINT2
|
private static int |
SYBINT4
|
private static int |
SYBINT8
|
private static int |
SYBINTN
|
private static int |
SYBLONGBINARY
|
(package private) static int |
SYBLONGDATA
|
private static int |
SYBMONEY
|
private static int |
SYBMONEY4
|
private static int |
SYBMONEYN
|
private static int |
SYBNTEXT
|
private static int |
SYBNUMERIC
|
private static int |
SYBNVARCHAR
|
private static int |
SYBREAL
|
private static int |
SYBSINT1
|
private static int |
SYBSINT8
|
private static int |
SYBTEXT
|
private static int |
SYBTIME
|
private static int |
SYBTIMEN
|
private static int |
SYBUINT2
|
private static int |
SYBUINT4
|
private static int |
SYBUINT8
|
private static int |
SYBUINTN
|
private static int |
SYBUNIQUE
|
private static int |
SYBUNITEXT
|
private static int |
SYBVARBINARY
|
private static int |
SYBVARCHAR
|
private static int |
SYBVARIANT
|
private static int |
SYBVOID
|
private static TdsData.TypeInfo[] |
types
Array of TDS data type descriptors. |
private static int |
UDT_BINARY
|
private static int |
UDT_CHAR
|
private static int |
UDT_LONGSYSNAME
|
private static int |
UDT_NCHAR
|
private static int |
UDT_NEWSYSNAME
|
private static int |
UDT_NVARCHAR
|
private static int |
UDT_SYSNAME
|
private static int |
UDT_TIMESTAMP
|
private static int |
UDT_UNICHAR
|
private static int |
UDT_UNITEXT
|
private static int |
UDT_UNIVARCHAR
|
private static int |
UDT_VARBINARY
|
private static int |
UDT_VARCHAR
|
private static int |
VAR_MAX
|
private static int |
XSYBBINARY
|
private static int |
XSYBCHAR
|
private static int |
XSYBNCHAR
|
private static int |
XSYBNVARCHAR
|
private static int |
XSYBVARBINARY
|
private static int |
XSYBVARCHAR
|
| Constructor Summary | |
private |
TdsData()
Private constructor to prevent users creating an actual instance of this class. |
| Method Summary | |
private static boolean |
canEncode(java.lang.String value,
java.lang.String charset)
Establish if a String can be converted to a byte based character set. |
(package private) static void |
fillInType(ColInfo ci)
Fill in the TDS native type code and all other fields for a ColInfo instance with the JDBC type set. |
(package private) static int |
getCollation(ResponseStream in,
ColInfo ci)
TDS 8 supplies collation information for character data types. |
private static java.lang.Object |
getDatetimeValue(ResponseStream in,
int type)
Get a DATETIME value from the server response stream. |
private static java.lang.Object |
getMoneyValue(ResponseStream in,
int type)
Read a MONEY value from the server response stream. |
static java.lang.String |
getMSTypeName(java.lang.String typeName,
int tdsType)
For SQL 2005 This routine will modify the meta data to allow the caller to distinguish between varchar(max) and text or varbinary(max) and image or nvarchar(max) and ntext. |
(package private) static void |
getNativeType(ConnectionJDBC2 connection,
ParamInfo pi)
Retrieve the TDS native type code for the parameter. |
(package private) static int |
getTds5ParamSize(java.lang.String charset,
boolean isWideChar,
ParamInfo pi,
boolean useParamNames)
Calculate the size of the parameter descriptor array for TDS 5 packets. |
static int |
getTdsVersion(int rawTdsVersion)
Extract the TDS protocol version from the value returned by the server in the LOGINACK packet. |
private static java.lang.Object |
getVariant(ConnectionJDBC2 connection,
ResponseStream in)
Read a MSQL 2000 sql_variant data value from the input stream. |
(package private) static boolean |
isCollation(ColInfo ci)
Retrieve the collation status of the column. |
(package private) static boolean |
isCurrency(ColInfo ci)
Retrieve the currency status of the column. |
(package private) static boolean |
isSearchable(ColInfo ci)
Retrieve the searchable status of the column. |
(package private) static boolean |
isSigned(ColInfo ci)
Retrieve the signed status of the column. |
(package private) static boolean |
isUnicode(ColInfo ci)
Determines whether the column is Unicode encoded. |
(package private) static void |
putCollation(RequestStream out,
ParamInfo pi)
TDS 8 requires collation information for char data descriptors. |
private static void |
putDateTimeValue(RequestStream out,
DateTime value)
Output a java.sql.Date/Time/Timestamp value to the server as a Sybase datetime value. |
(package private) static java.lang.Object |
readData(ConnectionJDBC2 connection,
ResponseStream in,
ColInfo ci)
Read the TDS data item from the Response Stream. |
(package private) static int |
readType(ResponseStream in,
ColInfo ci)
Read the TDS datastream and populate the ColInfo parameter with data type and related information. |
(package private) static void |
setColumnCharset(ColInfo ci,
ConnectionJDBC2 connection)
Set the charsetInfo field of ci according to
the value of its collation field.
|
(package private) static void |
writeParam(RequestStream out,
CharsetInfo charsetInfo,
byte[] collation,
ParamInfo pi)
Write a parameter to the server request stream. |
(package private) static void |
writeTds5Param(RequestStream out,
CharsetInfo charsetInfo,
ParamInfo pi)
Write the actual TDS 5 parameter data. |
(package private) static void |
writeTds5ParamFmt(RequestStream out,
java.lang.String charset,
boolean isWideChar,
ParamInfo pi,
boolean useParamNames)
Write a TDS 5 parameter format descriptor. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private static final int SYBCHAR
private static final int SYBVARCHAR
private static final int SYBINTN
private static final int SYBINT1
private static final int SYBDATE
private static final int SYBTIME
private static final int SYBINT2
private static final int SYBINT4
private static final int SYBINT8
private static final int SYBFLT8
private static final int SYBDATETIME
private static final int SYBBIT
private static final int SYBTEXT
private static final int SYBNTEXT
private static final int SYBIMAGE
private static final int SYBMONEY4
private static final int SYBMONEY
private static final int SYBDATETIME4
private static final int SYBREAL
private static final int SYBBINARY
private static final int SYBVOID
private static final int SYBVARBINARY
private static final int SYBNVARCHAR
private static final int SYBBITN
private static final int SYBNUMERIC
private static final int SYBDECIMAL
private static final int SYBFLTN
private static final int SYBMONEYN
private static final int SYBDATETIMN
private static final int SYBDATEN
private static final int SYBTIMEN
private static final int XSYBCHAR
private static final int XSYBVARCHAR
private static final int XSYBNVARCHAR
private static final int XSYBNCHAR
private static final int XSYBVARBINARY
private static final int XSYBBINARY
private static final int SYBUNITEXT
private static final int SYBLONGBINARY
private static final int SYBSINT1
private static final int SYBUINT2
private static final int SYBUINT4
private static final int SYBUINT8
private static final int SYBUINTN
private static final int SYBUNIQUE
private static final int SYBVARIANT
private static final int SYBSINT8
static final int SYBLONGDATA
private static final int UDT_CHAR
private static final int UDT_VARCHAR
private static final int UDT_BINARY
private static final int UDT_VARBINARY
private static final int UDT_SYSNAME
private static final int UDT_NCHAR
private static final int UDT_NVARCHAR
private static final int UDT_UNICHAR
private static final int UDT_UNIVARCHAR
private static final int UDT_UNITEXT
private static final int UDT_LONGSYSNAME
private static final int UDT_TIMESTAMP
private static final int UDT_NEWSYSNAME
private static final int VAR_MAX
private static final int SYB_LONGVAR_MAX
private static final int MS_LONGVAR_MAX
private static final int SYB_CHUNK_SIZE
private static final TdsData.TypeInfo[] types
static final int DEFAULT_SCALE
static final int DEFAULT_PRECISION_28
static final int DEFAULT_PRECISION_38
| Constructor Detail |
private TdsData()
| Method Detail |
static int getCollation(ResponseStream in, ColInfo ci) throws java.io.IOException
in - the server response streamci - the column descriptor
int
java.io.IOExceptionstatic void setColumnCharset(ColInfo ci, ConnectionJDBC2 connection) throws java.sql.SQLException
charsetInfo field of ci according to
the value of its collation field.
The Connection is used to find out whether a specific
charset was requested. In this case, the column charset will be ignored.
ci - the ColInfo instance to updateconnection - a Connection instance to check whether it
has a fixed charset or not
java.sql.SQLException - if a CharsetInfo is not found for this
particular column collationstatic int readType(ResponseStream in, ColInfo ci) throws java.io.IOException, ProtocolException
The type infomation conforms to one of the following formats:
in - The server response stream.ci - The ColInfo column descriptor object.
java.io.IOException
ProtocolExceptionstatic java.lang.Object readData(ConnectionJDBC2 connection, ResponseStream in, ColInfo ci) throws java.io.IOException, ProtocolException
The data size is either implicit in the type for example fixed size integers, or a count field precedes the actual data. The size of the count field varies with the data type.
connection - an object reference to the caller of this method;
must be a Connection, Statement or
ResultSetin - The server ResponseStream.ci - The ColInfo column descriptor object.
java.io.IOException
ProtocolExceptionstatic boolean isSigned(ColInfo ci)
ci - the column meta data
true if the column is a signed numeric.static boolean isCollation(ColInfo ci)
ci - the column meta data
true if the column requires collation data.static boolean isCurrency(ColInfo ci)
ci - The column meta data.
boolean true if the column is a currency type.static boolean isSearchable(ColInfo ci)
ci - the column meta data
true if the column is not a text or image type.static boolean isUnicode(ColInfo ci)
ci - the column meta data
true if the column is Unicode encodedstatic void fillInType(ColInfo ci) throws java.sql.SQLException
ColInfo instance with the JDBC type set.
ci - the ColInfo instance
java.sql.SQLExceptionstatic void getNativeType(ConnectionJDBC2 connection, ParamInfo pi) throws java.sql.SQLException
connection - the connectionJDBC objectpi - the parameter descriptor
java.sql.SQLException
static int getTds5ParamSize(java.lang.String charset,
boolean isWideChar,
ParamInfo pi,
boolean useParamNames)
charset - The encoding character set.isWideChar - True if multi byte encoding.pi - The parameter to describe.useParamNames - True if named parameters should be used.
int.static void writeTds5ParamFmt(RequestStream out, java.lang.String charset, boolean isWideChar, ParamInfo pi, boolean useParamNames) throws java.io.IOException
out - The server RequestStream.charset - The encoding character set.isWideChar - True if multi byte encoding.pi - The parameter to describe.useParamNames - True if named parameters should be used.
java.io.IOExceptionstatic void writeTds5Param(RequestStream out, CharsetInfo charsetInfo, ParamInfo pi) throws java.io.IOException, java.sql.SQLException
out - the server RequestStreamcharsetInfo - the encoding character setpi - the parameter to output
java.io.IOException
java.sql.SQLExceptionstatic void putCollation(RequestStream out, ParamInfo pi) throws java.io.IOException
out - The Server request stream.pi - The parameter descriptor.
java.io.IOExceptionstatic void writeParam(RequestStream out, CharsetInfo charsetInfo, byte[] collation, ParamInfo pi) throws java.io.IOException
out - the server request streamcharsetInfo - the default character setcollation - the default SQL Server 2000 collationpi - the parameter descriptor
java.io.IOExceptionprivate static java.lang.Object getDatetimeValue(ResponseStream in, int type) throws java.io.IOException, ProtocolException
in - The server response stream.type - The TDS data type.
java.io.IOException
ProtocolExceptionprivate static void putDateTimeValue(RequestStream out, DateTime value) throws java.io.IOException
out - the server request streamvalue - the date value to write
java.io.IOExceptionprivate static java.lang.Object getMoneyValue(ResponseStream in, int type) throws java.io.IOException, ProtocolException
in - The server response stream.type - The TDS data type.
java.io.IOException
ProtocolExceptionprivate static java.lang.Object getVariant(ConnectionJDBC2 connection, ResponseStream in) throws java.io.IOException, ProtocolException
SQL_VARIANT has the following structure:
connection - used to obtain collation/charset informationin - the server response stream
java.io.IOException
ProtocolException
public static java.lang.String getMSTypeName(java.lang.String typeName,
int tdsType)
typeName - the SQL type returned by sp_columnstdsType - the TDS type returned by sp_columns
Stringpublic static int getTdsVersion(int rawTdsVersion)
rawTdsVersion - the TDS protocol version as returned by the server
Driver.TDSXX values)
private static boolean canEncode(java.lang.String value,
java.lang.String charset)
value - The String to test.charset - The server character set in force.
boolean true if string can be converted.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.TdsCore.TdsToken
Inner static class used to hold information about TDS tokens read.
| Field Summary | |
(package private) java.lang.Object[] |
dynamParamData
The dynamic parameter data from the last TDS_DYNAMIC token. |
(package private) ColInfo[] |
dynamParamInfo
The dynamic parameters from the last TDS_DYNAMIC token. |
(package private) byte[] |
nonce
The nonce from an NTLM challenge packet. |
(package private) byte[] |
ntlmMessage
NTLM authentication message. |
(package private) byte[] |
ntlmTarget
target info for NTLM message TODO: I don't need to store these!!! |
(package private) byte |
operation
The operation field from a DONE packet. |
(package private) byte |
status
The status field from a DONE packet. |
(package private) byte |
token
The current TDS token byte. |
(package private) int |
updateCount
The update count from a DONE packet. |
| Constructor Summary | |
private |
TdsCore.TdsToken()
|
| Method Summary | |
(package private) boolean |
isAuthToken()
Retrieve the NTLM challenge status. |
(package private) boolean |
isEndToken()
Retrieve the DONE token status. |
(package private) boolean |
isResultSet()
Retrieve the result set status. |
boolean |
isRowData()
Retrieve the row data status. |
(package private) boolean |
isUpdateCount()
Retrieve the update count status. |
(package private) boolean |
resultsPending()
Retrieve the results pending status. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
byte token
byte status
byte operation
int updateCount
byte[] nonce
byte[] ntlmMessage
byte[] ntlmTarget
ColInfo[] dynamParamInfo
java.lang.Object[] dynamParamData
| Constructor Detail |
private TdsCore.TdsToken()
| Method Detail |
boolean isUpdateCount()
boolean true if the update count is valid.boolean isEndToken()
boolean true if the current token is a DONE packet.boolean isAuthToken()
boolean true if the current token is an NTLM challenge.boolean resultsPending()
boolean true if more results in input.boolean isResultSet()
boolean true if the current token is a result set.public boolean isRowData()
boolean true if the current token is a result row.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.JtdsDatabaseMetaData
jTDS implementation of the java.sql.DatabaseMetaData interface.
Implementation note:
This is basically the code from the original jTDS driver. Main changes relate to the need to support the new ResultSet implementation.
TODO: Many of the system limits need to be revised to more accurately reflect the target database constraints. In many cases limits are soft and determined by bytes per column for example. Probably more of these functions should be altered to return 0 but for now the original jTDS values are returned.
| Field Summary | |
(package private) java.lang.Boolean |
caseSensitive
Boolean.TRUE if identifiers are case sensitive (the server
was installed that way). |
private ConnectionJDBC2 |
connection
|
private int |
serverType
|
(package private) static int |
sqlStateXOpen
|
(package private) int |
sysnameLength
Length of a sysname object (table name, catalog name etc.) -- 128 for TDS 7.0, 30 for earlier versions. |
private int |
tdsVersion
|
| Fields inherited from interface java.sql.DatabaseMetaData |
attributeNoNulls, attributeNullable, attributeNullableUnknown, bestRowNotPseudo, bestRowPseudo, bestRowSession, bestRowTemporary, bestRowTransaction, bestRowUnknown, columnNoNulls, columnNullable, columnNullableUnknown, importedKeyCascade, importedKeyInitiallyDeferred, importedKeyInitiallyImmediate, importedKeyNoAction, importedKeyNotDeferrable, importedKeyRestrict, importedKeySetDefault, importedKeySetNull, procedureColumnIn, procedureColumnInOut, procedureColumnOut, procedureColumnResult, procedureColumnReturn, procedureColumnUnknown, procedureNoNulls, procedureNoResult, procedureNullable, procedureNullableUnknown, procedureResultUnknown, procedureReturnsResult, sqlStateSQL99, tableIndexClustered, tableIndexHashed, tableIndexOther, tableIndexStatistic, typeNoNulls, typeNullable, typeNullableUnknown, typePredBasic, typePredChar, typePredNone, typeSearchable, versionColumnNotPseudo, versionColumnPseudo, versionColumnUnknown |
| Constructor Summary | |
JtdsDatabaseMetaData(ConnectionJDBC2 connection)
|
|
| Method Summary | |
boolean |
allProceduresAreCallable()
Can all the procedures returned by getProcedures be called by the current user? |
boolean |
allTablesAreSelectable()
Can all the tables returned by getTable be SELECTed by the current user? |
private static CachedResultSet |
createTypeInfoResultSet(JtdsResultSet rs,
boolean useLOBs)
|
boolean |
dataDefinitionCausesTransactionCommit()
Does a data definition statement within a transaction force the transaction to commit? |
boolean |
dataDefinitionIgnoredInTransactions()
Is a data definition statement within a transaction ignored? |
boolean |
deletesAreDetected(int type)
JDBC 2.0 Indicates whether or not a visible row delete can be detected by calling ResultSet.rowDeleted(). |
boolean |
doesMaxRowSizeIncludeBlobs()
Did getMaxRowSize() include LONGVARCHAR and LONGVARBINARY blobs? |
java.sql.ResultSet |
getAttributes(java.lang.String catalog,
java.lang.String schemaPattern,
java.lang.String typeNamePattern,
java.lang.String attributeNamePattern)
|
java.sql.ResultSet |
getBestRowIdentifier(java.lang.String catalog,
java.lang.String schema,
java.lang.String table,
int scope,
boolean nullable)
Get a description of a table's optimal set of columns that uniquely identifies a row. |
java.sql.ResultSet |
getCatalogs()
Get the catalog names available in this database. |
java.lang.String |
getCatalogSeparator()
What's the separator between catalog and table name? |
java.lang.String |
getCatalogTerm()
What's the database vendor's preferred term for "catalog"? |
java.sql.ResultSet |
getColumnPrivileges(java.lang.String catalog,
java.lang.String schema,
java.lang.String table,
java.lang.String columnNamePattern)
Get a description of the access rights for a table's columns. |
java.sql.ResultSet |
getColumns(java.lang.String catalog,
java.lang.String schemaPattern,
java.lang.String tableNamePattern,
java.lang.String columnNamePattern)
Get a description of table columns available in a catalog. |
java.sql.Connection |
getConnection()
JDBC 2.0 Retrieves the connection that produced this metadata object. |
java.sql.ResultSet |
getCrossReference(java.lang.String primaryCatalog,
java.lang.String primarySchema,
java.lang.String primaryTable,
java.lang.String foreignCatalog,
java.lang.String foreignSchema,
java.lang.String foreignTable)
Get a description of the foreign key columns in the foreign key table that reference the primary key columns of the primary key table (describe how one table imports another's key). |
int |
getDatabaseMajorVersion()
Returns the database major version. |
int |
getDatabaseMinorVersion()
Returns the database minor version. |
java.lang.String |
getDatabaseProductName()
Returns the name of this database product. |
java.lang.String |
getDatabaseProductVersion()
Returns the version of this database product. |
int |
getDefaultTransactionIsolation()
Returns the database's default transaction isolation level. |
int |
getDriverMajorVersion()
Returns this JDBC driver's major version number. |
int |
getDriverMinorVersion()
Returns this JDBC driver's minor version number. |
java.lang.String |
getDriverName()
Returns the name of this JDBC driver. |
java.lang.String |
getDriverVersion()
Returns the version of this JDBC driver. |
java.sql.ResultSet |
getExportedKeys(java.lang.String catalog,
java.lang.String schema,
java.lang.String table)
Get a description of the foreign key columns that reference a table's primary key columns (the foreign keys exported by a table). |
java.lang.String |
getExtraNameCharacters()
Get all the "extra" characters that can be used in unquoted identifier names (those beyond a-z, A-Z, 0-9 and _). |
java.lang.String |
getIdentifierQuoteString()
Returns the string used to quote SQL identifiers. |
java.sql.ResultSet |
getImportedKeys(java.lang.String catalog,
java.lang.String schema,
java.lang.String table)
Get a description of the primary key columns that are referenced by a table's foreign key columns (the primary keys imported by a table). |
java.sql.ResultSet |
getIndexInfo(java.lang.String catalog,
java.lang.String schema,
java.lang.String table,
boolean unique,
boolean approximate)
Get a description of a table's indices and statistics. |
int |
getJDBCMajorVersion()
Returns the JDBC major version. |
int |
getJDBCMinorVersion()
Returns the JDBC minor version. |
int |
getMaxBinaryLiteralLength()
How many hex characters can you have in an inline binary literal? |
int |
getMaxCatalogNameLength()
What's the maximum length of a catalog name? |
int |
getMaxCharLiteralLength()
What's the max length for a character literal? |
int |
getMaxColumnNameLength()
What's the limit on column name length? |
int |
getMaxColumnsInGroupBy()
What's the maximum number of columns in a "GROUP BY" clause? |
int |
getMaxColumnsInIndex()
What's the maximum number of columns allowed in an index? |
int |
getMaxColumnsInOrderBy()
What's the maximum number of columns in an "ORDER BY" clause? |
int |
getMaxColumnsInSelect()
What's the maximum number of columns in a "SELECT" list? |
int |
getMaxColumnsInTable()
What's the maximum number of columns in a table? |
int |
getMaxConnections()
How many active connections can we have at a time to this database? |
int |
getMaxCursorNameLength()
What's the maximum cursor name length? |
int |
getMaxIndexLength()
What's the maximum length of an index (in bytes)? |
int |
getMaxProcedureNameLength()
What's the maximum length of a procedure name? |
int |
getMaxRowSize()
What's the maximum length of a single row? |
int |
getMaxSchemaNameLength()
What's the maximum length allowed for a schema name? |
int |
getMaxStatementLength()
What's the maximum length of a SQL statement? |
int |
getMaxStatements()
How many active statements can we have open at one time to this database? |
int |
getMaxTableNameLength()
What's the maximum length of a table name? |
int |
getMaxTablesInSelect()
What's the maximum number of tables in a SELECT? |
int |
getMaxUserNameLength()
What's the maximum length of a user name? |
java.lang.String |
getNumericFunctions()
Get a comma separated list of math functions. |
java.sql.ResultSet |
getPrimaryKeys(java.lang.String catalog,
java.lang.String schema,
java.lang.String table)
Get a description of a table's primary key columns. |
java.sql.ResultSet |
getProcedureColumns(java.lang.String catalog,
java.lang.String schemaPattern,
java.lang.String procedureNamePattern,
java.lang.String columnNamePattern)
Get a description of a catalog's stored procedure parameters and result columns. |
java.sql.ResultSet |
getProcedures(java.lang.String catalog,
java.lang.String schemaPattern,
java.lang.String procedureNamePattern)
Get a description of stored procedures available in a catalog. |
java.lang.String |
getProcedureTerm()
What's the database vendor's preferred term for "procedure"? |
int |
getResultSetHoldability()
|
java.sql.ResultSet |
getSchemas()
Get the schema names available in this database. |
java.lang.String |
getSchemaTerm()
What's the database vendor's preferred term for "schema"? |
java.lang.String |
getSearchStringEscape()
This is the string that can be used to escape '_' or '%' in the string pattern style catalog search parameters. |
private static java.util.Collection |
getSortedTypes(java.sql.ResultSet rs,
boolean useLOBs)
|
java.lang.String |
getSQLKeywords()
Get a comma separated list of all a database's SQL keywords that are NOT also SQL92 keywords. |
int |
getSQLStateType()
|
java.lang.String |
getStringFunctions()
Get a comma separated list of string functions. |
java.sql.ResultSet |
getSuperTables(java.lang.String catalog,
java.lang.String schemaPattern,
java.lang.String tableNamePattern)
|
java.sql.ResultSet |
getSuperTypes(java.lang.String catalog,
java.lang.String schemaPattern,
java.lang.String typeNamePattern)
|
java.lang.String |
getSystemFunctions()
Get a comma separated list of system functions. |
java.sql.ResultSet |
getTablePrivileges(java.lang.String catalog,
java.lang.String schemaPattern,
java.lang.String tableNamePattern)
Get a description of the access rights for each table available in a catalog. |
java.sql.ResultSet |
getTables(java.lang.String catalog,
java.lang.String schemaPattern,
java.lang.String tableNamePattern,
java.lang.String[] types)
Get a description of tables available in a catalog. |
java.sql.ResultSet |
getTableTypes()
Get the table types available in this database. |
java.lang.String |
getTimeDateFunctions()
Get a comma separated list of time and date functions. |
java.sql.ResultSet |
getTypeInfo()
Get a description of all the standard SQL types supported by this database. |
java.sql.ResultSet |
getUDTs(java.lang.String catalog,
java.lang.String schemaPattern,
java.lang.String typeNamePattern,
int[] types)
JDBC 2.0 Gets a description of the user-defined types defined in a particular schema. |
java.lang.String |
getURL()
What's the URL for this database? |
java.lang.String |
getUserName()
What's our user name as known to the database? |
java.sql.ResultSet |
getVersionColumns(java.lang.String catalog,
java.lang.String schema,
java.lang.String table)
Get a description of a table's columns that are automatically updated when any value in a row is updated. |
boolean |
insertsAreDetected(int type)
JDBC 2.0 Indicates whether or not a visible row insert can be detected by calling ResultSet.rowInserted(). |
boolean |
isCatalogAtStart()
Retrieves whether a catalog appears at the start of a fully qualified table name. |
boolean |
isReadOnly()
Is the database in read-only mode? |
boolean |
locatorsUpdateCopy()
Returns true if updates are made to a copy of the LOB; returns
false if LOB updates are made directly to the database.
|
boolean |
nullPlusNonNullIsNull()
Retrieves whether this database supports concatenations between NULL and non-NULL values being
NULL. |
boolean |
nullsAreSortedAtEnd()
Are NULL values sorted at the end regardless of sort order? |
boolean |
nullsAreSortedAtStart()
Are NULL values sorted at the start regardless of sort order? |
boolean |
nullsAreSortedHigh()
Are NULL values sorted high? |
boolean |
nullsAreSortedLow()
Are NULL values sorted low? |
boolean |
othersDeletesAreVisible(int type)
JDBC 2.0 Indicates whether deletes made by others are visible. |
boolean |
othersInsertsAreVisible(int type)
JDBC 2.0 Indicates whether inserts made by others are visible. |
boolean |
othersUpdatesAreVisible(int type)
JDBC 2.0 Indicates whether updates made by others are visible. |
boolean |
ownDeletesAreVisible(int type)
JDBC 2.0 Indicates whether a result set's own deletes are visible. |
boolean |
ownInsertsAreVisible(int type)
JDBC 2.0 Indicates whether a result set's own inserts are visible. |
boolean |
ownUpdatesAreVisible(int type)
JDBC 2.0 Indicates whether a result set's own updates are visible. |
private static java.lang.String |
processEscapes(java.lang.String pattern)
Format the supplied search pattern to transform the escape \x into [x]. |
private void |
setCaseSensitiveFlag()
|
boolean |
storesLowerCaseIdentifiers()
Does the database treat mixed case unquoted SQL identifiers as case insensitive and store them in lower case? |
boolean |
storesLowerCaseQuotedIdentifiers()
Does the database treat mixed case quoted SQL identifiers as case insensitive and store them in lower case? |
boolean |
storesMixedCaseIdentifiers()
Does the database treat mixed case unquoted SQL identifiers as case insensitive and store them in mixed case? |
boolean |
storesMixedCaseQuotedIdentifiers()
Does the database treat mixed case quoted SQL identifiers as case insensitive and store them in mixed case? |
boolean |
storesUpperCaseIdentifiers()
Does the database treat mixed case unquoted SQL identifiers as case insensitive and store them in upper case? |
boolean |
storesUpperCaseQuotedIdentifiers()
Does the database treat mixed case quoted SQL identifiers as case insensitive and store them in upper case? |
boolean |
supportsAlterTableWithAddColumn()
Is "ALTER TABLE" with add column supported? |
boolean |
supportsAlterTableWithDropColumn()
Is "ALTER TABLE" with drop column supported? |
boolean |
supportsANSI92EntryLevelSQL()
Retrieves whether this database supports the ANSI92 entry level SQL grammar. |
boolean |
supportsANSI92FullSQL()
Is the ANSI92 full SQL grammar supported? |
boolean |
supportsANSI92IntermediateSQL()
Is the ANSI92 intermediate SQL grammar supported? |
boolean |
supportsBatchUpdates()
JDBC 2.0 Indicates whether the driver supports batch updates. |
boolean |
supportsCatalogsInDataManipulation()
Can a catalog name be used in a data manipulation statement? |
boolean |
supportsCatalogsInIndexDefinitions()
Can a catalog name be used in an index definition statement? |
boolean |
supportsCatalogsInPrivilegeDefinitions()
Can a catalog name be used in a privilege definition statement? |
boolean |
supportsCatalogsInProcedureCalls()
Can a catalog name be used in a procedure call statement? |
boolean |
supportsCatalogsInTableDefinitions()
Can a catalog name be used in a table definition statement? |
boolean |
supportsColumnAliasing()
Retrieves whether this database supports column aliasing. |
boolean |
supportsConvert()
Is the CONVERT function between SQL types supported? |
boolean |
supportsConvert(int fromType,
int toType)
Is CONVERT between the given SQL types supported? |
boolean |
supportsCoreSQLGrammar()
Is the ODBC Core SQL grammar supported? |
boolean |
supportsCorrelatedSubqueries()
Retrieves whether this database supports correlated subqueries. |
boolean |
supportsDataDefinitionAndDataManipulationTransactions()
Are both data definition and data manipulation statements within a transaction supported? |
boolean |
supportsDataManipulationTransactionsOnly()
Are only data manipulation statements within a transaction supported? |
boolean |
supportsDifferentTableCorrelationNames()
If table correlation names are supported, are they restricted to be different from the names of the tables? |
boolean |
supportsExpressionsInOrderBy()
Are expressions in "ORDER BY" lists supported? |
boolean |
supportsExtendedSQLGrammar()
Is the ODBC Extended SQL grammar supported? |
boolean |
supportsFullOuterJoins()
Are full nested outer joins supported? |
boolean |
supportsGetGeneratedKeys()
Returns true if getting auto-generated keys is supported after a
statment is executed; returns false otherwise |
boolean |
supportsGroupBy()
Is some form of "GROUP BY" clause supported? |
boolean |
supportsGroupByBeyondSelect()
Can a "GROUP BY" clause add columns not in the SELECT provided it specifies all the columns in the SELECT? |
boolean |
supportsGroupByUnrelated()
Can a "GROUP BY" clause use columns not in the SELECT? |
boolean |
supportsIntegrityEnhancementFacility()
Is the SQL Integrity Enhancement Facility supported? |
boolean |
supportsLikeEscapeClause()
Retrieves whether this database supports specifying a LIKE
escape clause. |
boolean |
supportsLimitedOuterJoins()
Retrieves whether this database provides limited support for outer joins. |
boolean |
supportsMinimumSQLGrammar()
Retrieves whether this database supports the ODBC Minimum SQL grammar. |
boolean |
supportsMixedCaseIdentifiers()
Retrieves whether this database treats mixed case unquoted SQL identifiers as case sensitive and as a result stores them in mixed case. |
boolean |
supportsMixedCaseQuotedIdentifiers()
Retrieves whether this database treats mixed case quoted SQL identifiers as case sensitive and as a result stores them in mixed case. |
boolean |
supportsMultipleOpenResults()
Returns true if Callable statements can return multiple result sets;
returns false if they can only return one result set. |
boolean |
supportsMultipleResultSets()
Are multiple ResultSets from a single execute supported? |
boolean |
supportsMultipleTransactions()
Can we have multiple transactions open at once (on different connections)? |
boolean |
supportsNamedParameters()
Returns true if the database supports named parameters;
returns false if the database does not support named parameters. |
boolean |
supportsNonNullableColumns()
Retrieves whether columns in this database may be defined as non-nullable. |
boolean |
supportsOpenCursorsAcrossCommit()
Can cursors remain open across commits? |
boolean |
supportsOpenCursorsAcrossRollback()
Can cursors remain open across rollbacks? |
boolean |
supportsOpenStatementsAcrossCommit()
Can statements remain open across commits? |
boolean |
supportsOpenStatementsAcrossRollback()
Can statements remain open across rollbacks? |
boolean |
supportsOrderByUnrelated()
Can an "ORDER BY" clause use columns not in the SELECT? |
boolean |
supportsOuterJoins()
Is some form of outer join supported? |
boolean |
supportsPositionedDelete()
Is positioned DELETE supported? |
boolean |
supportsPositionedUpdate()
Is positioned UPDATE supported? |
boolean |
supportsResultSetConcurrency(int type,
int concurrency)
Does the database support the concurrency type in combination with the given result set type? |
boolean |
supportsResultSetHoldability(int param)
|
boolean |
supportsResultSetType(int type)
Does the database support the given result set type? |
boolean |
supportsSavepoints()
Returns true if savepoints are supported; returns
false otherwise |
boolean |
supportsSchemasInDataManipulation()
Can a schema name be used in a data manipulation statement? |
boolean |
supportsSchemasInIndexDefinitions()
Can a schema name be used in an index definition statement? |
boolean |
supportsSchemasInPrivilegeDefinitions()
Can a schema name be used in a privilege definition statement? |
boolean |
supportsSchemasInProcedureCalls()
Can a schema name be used in a procedure call statement? |
boolean |
supportsSchemasInTableDefinitions()
Can a schema name be used in a table definition statement? |
boolean |
supportsSelectForUpdate()
Is SELECT for UPDATE supported? |
boolean |
supportsStatementPooling()
Returns true if the database supports statement pooling;
returns false otherwise. |
boolean |
supportsStoredProcedures()
Are stored procedure calls using the stored procedure escape syntax supported? |
boolean |
supportsSubqueriesInComparisons()
Retrieves whether this database supports subqueries in comparison expressions. |
boolean |
supportsSubqueriesInExists()
Retrieves whether this database supports subqueries in EXISTS expressions. |
boolean |
supportsSubqueriesInIns()
Retrieves whether this database supports subqueries in IN statements. |
boolean |
supportsSubqueriesInQuantifieds()
Retrieves whether this database supports subqueries in quantified expressions. |
boolean |
supportsTableCorrelationNames()
Retrieves whether this database supports table correlation names. |
boolean |
supportsTransactionIsolationLevel(int level)
Does the database support the given transaction isolation level? |
boolean |
supportsTransactions()
Retrieves whether this database supports transactions. |
boolean |
supportsUnion()
Is SQL UNION supported? |
boolean |
supportsUnionAll()
Is SQL UNION ALL supported? |
private java.lang.String |
syscall(java.lang.String catalog,
java.lang.String call)
Format the supplied procedure call as a valid JDBC call escape. |
boolean |
updatesAreDetected(int type)
JDBC 2.0 Indicates whether or not a visible row update can be detected by calling the method ResultSet.rowUpdated . |
private static void |
upperCaseColumnNames(JtdsResultSet results)
Uppercase all column names. |
boolean |
usesLocalFilePerTable()
Does the database use a file for each table? |
boolean |
usesLocalFiles()
Does the database store tables in a local file? |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
static final int sqlStateXOpen
private final int tdsVersion
private final int serverType
private final ConnectionJDBC2 connection
int sysnameLength
java.lang.Boolean caseSensitive
Boolean.TRUE if identifiers are case sensitive (the server
was installed that way). Initially null, set the first time
any of the methods that check this are called.
| Constructor Detail |
public JtdsDatabaseMetaData(ConnectionJDBC2 connection)
| Method Detail |
public boolean allProceduresAreCallable()
throws java.sql.SQLException
allProceduresAreCallable in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean allTablesAreSelectable()
throws java.sql.SQLException
allTablesAreSelectable in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean dataDefinitionCausesTransactionCommit()
throws java.sql.SQLException
dataDefinitionCausesTransactionCommit in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean dataDefinitionIgnoredInTransactions()
throws java.sql.SQLException
dataDefinitionIgnoredInTransactions in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean doesMaxRowSizeIncludeBlobs()
throws java.sql.SQLException
doesMaxRowSizeIncludeBlobs in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public java.sql.ResultSet getBestRowIdentifier(java.lang.String catalog,
java.lang.String schema,
java.lang.String table,
int scope,
boolean nullable)
throws java.sql.SQLException
Each column description has the following columns:
getBestRowIdentifier in interface java.sql.DatabaseMetaDatacatalog - a catalog name; "" retrieves those without a catalog;
null means drop catalog name from the selection criteriaschema - a schema name; "" retrieves those without a schematable - a table namescope - the scope of interest; use same values as SCOPEnullable - include columns that are nullable?
java.sql.SQLException - if a database-access error occurs.
public java.sql.ResultSet getCatalogs()
throws java.sql.SQLException
The catalog column is:
getCatalogs in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public java.lang.String getCatalogSeparator()
throws java.sql.SQLException
getCatalogSeparator in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public java.lang.String getCatalogTerm()
throws java.sql.SQLException
getCatalogTerm in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public java.sql.ResultSet getColumnPrivileges(java.lang.String catalog,
java.lang.String schema,
java.lang.String table,
java.lang.String columnNamePattern)
throws java.sql.SQLException
Only privileges matching the column name criteria are returned. They are ordered by COLUMN_NAME and PRIVILEGE.
Each privilige description has the following columns:
getColumnPrivileges in interface java.sql.DatabaseMetaDatacatalog - a catalog name; "" retrieves those without a catalog;
null means drop catalog name from the selection criteriaschema - a schema name; "" retrieves those without a schema
schematable - a table namecolumnNamePattern - a column name pattern
java.sql.SQLException - if a database-access error occurs.getSearchStringEscape()
public java.sql.ResultSet getColumns(java.lang.String catalog,
java.lang.String schemaPattern,
java.lang.String tableNamePattern,
java.lang.String columnNamePattern)
throws java.sql.SQLException
Only column descriptions matching the catalog, schema, table and column name criteria are returned. They are ordered by TABLE_SCHEM, TABLE_NAME and ORDINAL_POSITION.
Each column description has the following columns:
getColumns in interface java.sql.DatabaseMetaDatacatalog - a catalog name; "" retrieves those without a catalog;
null means drop catalog name from the selection criteriaschemaPattern - a schema name pattern; "" retrieves those without a schematableNamePattern - a table name patterncolumnNamePattern - a column name pattern
java.sql.SQLException - if a database-access error occurs.getSearchStringEscape()
public java.sql.ResultSet getCrossReference(java.lang.String primaryCatalog,
java.lang.String primarySchema,
java.lang.String primaryTable,
java.lang.String foreignCatalog,
java.lang.String foreignSchema,
java.lang.String foreignTable)
throws java.sql.SQLException
Each foreign key column description has the following columns:
getCrossReference in interface java.sql.DatabaseMetaDataprimaryCatalog - a catalog name; "" retrieves those without a
null means drop catalog name from the selection criteriaprimarySchema - a schema name pattern; "" retrieves those without a schemaprimaryTable - the table name that exports the keyforeignCatalog - a catalog name; "" retrieves those without a
null means drop catalog name from the selection criteriaforeignSchema - a schema name pattern; "" retrieves those without a schemaforeignTable - the table name that imports the key
java.sql.SQLException - if a database-access error occurs.getImportedKeys(java.lang.String, java.lang.String, java.lang.String)
public java.lang.String getDatabaseProductName()
throws java.sql.SQLException
getDatabaseProductName in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public java.lang.String getDatabaseProductVersion()
throws java.sql.SQLException
getDatabaseProductVersion in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public int getDefaultTransactionIsolation()
throws java.sql.SQLException
getDefaultTransactionIsolation in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.Connectionpublic int getDriverMajorVersion()
getDriverMajorVersion in interface java.sql.DatabaseMetaDatapublic int getDriverMinorVersion()
getDriverMinorVersion in interface java.sql.DatabaseMetaData
public java.lang.String getDriverName()
throws java.sql.SQLException
getDriverName in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public java.lang.String getDriverVersion()
throws java.sql.SQLException
getDriverVersion in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public java.sql.ResultSet getExportedKeys(java.lang.String catalog,
java.lang.String schema,
java.lang.String table)
throws java.sql.SQLException
Each foreign key column description has the following columns:
getExportedKeys in interface java.sql.DatabaseMetaDatacatalog - a catalog name; "" retrieves those without a
null means drop catalog name from the selection criteriaschema - a schema name; "" retrieves those without a schematable - a table name
java.sql.SQLException - if a database-access error occurs.getImportedKeys(java.lang.String, java.lang.String, java.lang.String)
public java.lang.String getExtraNameCharacters()
throws java.sql.SQLException
getExtraNameCharacters in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public java.lang.String getIdentifierQuoteString()
throws java.sql.SQLException
getIdentifierQuoteString in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public java.sql.ResultSet getImportedKeys(java.lang.String catalog,
java.lang.String schema,
java.lang.String table)
throws java.sql.SQLException
Each primary key column description has the following columns:
getImportedKeys in interface java.sql.DatabaseMetaDatacatalog - a catalog name; "" retrieves those without a
null means drop catalog name from the selection criteriaschema - a schema name; "" retrieves those without a schematable - a table name
java.sql.SQLException - if a database-access error occurs.getExportedKeys(java.lang.String, java.lang.String, java.lang.String)
public java.sql.ResultSet getIndexInfo(java.lang.String catalog,
java.lang.String schema,
java.lang.String table,
boolean unique,
boolean approximate)
throws java.sql.SQLException
Each index column description has the following columns:
getIndexInfo in interface java.sql.DatabaseMetaDatacatalog - a catalog name; "" retrieves those without a
null means drop catalog name from the selection criteriaschema - a schema name; "" retrieves those without a schematable - a table nameunique - when true, return only indices for unique
values; when false, return indices regardless of
whether unique or notapproximate - when true, result is allowed to reflect
approximate or out of data values; when false, results
are requested to be accurate
java.sql.SQLException - if a database-access error occurs.
public int getMaxBinaryLiteralLength()
throws java.sql.SQLException
getMaxBinaryLiteralLength in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public int getMaxCatalogNameLength()
throws java.sql.SQLException
getMaxCatalogNameLength in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public int getMaxCharLiteralLength()
throws java.sql.SQLException
getMaxCharLiteralLength in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public int getMaxColumnNameLength()
throws java.sql.SQLException
getMaxColumnNameLength in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public int getMaxColumnsInGroupBy()
throws java.sql.SQLException
getMaxColumnsInGroupBy in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public int getMaxColumnsInIndex()
throws java.sql.SQLException
getMaxColumnsInIndex in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public int getMaxColumnsInOrderBy()
throws java.sql.SQLException
getMaxColumnsInOrderBy in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public int getMaxColumnsInSelect()
throws java.sql.SQLException
getMaxColumnsInSelect in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public int getMaxColumnsInTable()
throws java.sql.SQLException
getMaxColumnsInTable in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public int getMaxConnections()
throws java.sql.SQLException
getMaxConnections in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public int getMaxCursorNameLength()
throws java.sql.SQLException
getMaxCursorNameLength in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public int getMaxIndexLength()
throws java.sql.SQLException
getMaxIndexLength in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public int getMaxProcedureNameLength()
throws java.sql.SQLException
getMaxProcedureNameLength in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public int getMaxRowSize()
throws java.sql.SQLException
getMaxRowSize in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public int getMaxSchemaNameLength()
throws java.sql.SQLException
getMaxSchemaNameLength in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public int getMaxStatementLength()
throws java.sql.SQLException
getMaxStatementLength in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public int getMaxStatements()
throws java.sql.SQLException
getMaxStatements in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public int getMaxTableNameLength()
throws java.sql.SQLException
getMaxTableNameLength in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public int getMaxTablesInSelect()
throws java.sql.SQLException
getMaxTablesInSelect in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public int getMaxUserNameLength()
throws java.sql.SQLException
getMaxUserNameLength in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public java.lang.String getNumericFunctions()
throws java.sql.SQLException
getNumericFunctions in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public java.sql.ResultSet getPrimaryKeys(java.lang.String catalog,
java.lang.String schema,
java.lang.String table)
throws java.sql.SQLException
Each primary key column description has the following columns:
getPrimaryKeys in interface java.sql.DatabaseMetaDatacatalog - a catalog name; "" retrieves those without a
null means drop catalog name from the selection criteriaschema - a schema name; "" retrieves those without a schematable - a table name
java.sql.SQLException - if a database-access error occurs.
public java.sql.ResultSet getProcedureColumns(java.lang.String catalog,
java.lang.String schemaPattern,
java.lang.String procedureNamePattern,
java.lang.String columnNamePattern)
throws java.sql.SQLException
Only descriptions matching the schema, procedure and parameter name criteria are returned. They are ordered by PROCEDURE_SCHEM and PROCEDURE_NAME. Within this, the return value, if any, is first. Next are the parameter descriptions in call order. The column descriptions follow in column number order.
Each row in the ResultSet is a parameter description or column description with the following fields:
Note: Some databases may not return the column descriptions for a procedure. Additional columns beyond REMARKS can be defined by the database.
getProcedureColumns in interface java.sql.DatabaseMetaDatacatalog - a catalog name; "" retrieves those without a
null means drop catalog name from the selection criteriaschemaPattern - a schema name pattern; "" retrieves those
without a schemaprocedureNamePattern - a procedure name patterncolumnNamePattern - a column name pattern
java.sql.SQLException - if a database-access error occurs.getSearchStringEscape()
public java.sql.ResultSet getProcedures(java.lang.String catalog,
java.lang.String schemaPattern,
java.lang.String procedureNamePattern)
throws java.sql.SQLException
Only procedure descriptions matching the schema and procedure name criteria are returned. They are ordered by PROCEDURE_SCHEM, and PROCEDURE_NAME.
Each procedure description has the the following columns:
getProcedures in interface java.sql.DatabaseMetaDatacatalog - a catalog name; "" retrieves those without a
null means drop catalog name from the selection criteriaschemaPattern - a schema name pattern; "" retrieves those
without a schemaprocedureNamePattern - a procedure name pattern
java.sql.SQLException - if a database-access error occurs.getSearchStringEscape()
public java.lang.String getProcedureTerm()
throws java.sql.SQLException
getProcedureTerm in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public java.sql.ResultSet getSchemas()
throws java.sql.SQLException
The schema column is:
null, JDBC 3.0)
getSchemas in interface java.sql.DatabaseMetaDataResultSet object in which each row is a schema description
java.sql.SQLException - if a database access error occurs
public java.lang.String getSchemaTerm()
throws java.sql.SQLException
getSchemaTerm in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public java.lang.String getSearchStringEscape()
throws java.sql.SQLException
The '_' character represents any single character.
The '%' character represents any sequence of zero or more characters.
getSearchStringEscape in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public java.lang.String getSQLKeywords()
throws java.sql.SQLException
getSQLKeywords in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public java.lang.String getStringFunctions()
throws java.sql.SQLException
getStringFunctions in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public java.lang.String getSystemFunctions()
throws java.sql.SQLException
getSystemFunctions in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public java.sql.ResultSet getTablePrivileges(java.lang.String catalog,
java.lang.String schemaPattern,
java.lang.String tableNamePattern)
throws java.sql.SQLException
Only privileges matching the schema and table name criteria are returned. They are ordered by TABLE_SCHEM, TABLE_NAME, and PRIVILEGE.
Each privilige description has the following columns:
getTablePrivileges in interface java.sql.DatabaseMetaDatacatalog - a catalog name; "" retrieves those without a
null means drop catalog name from the selection criteriaschemaPattern - a schema name pattern; "" retrieves those
without a schematableNamePattern - a table name pattern
java.sql.SQLException - if a database-access error occurs.getSearchStringEscape()
public java.sql.ResultSet getTables(java.lang.String catalog,
java.lang.String schemaPattern,
java.lang.String tableNamePattern,
java.lang.String[] types)
throws java.sql.SQLException
Only table descriptions matching the catalog, schema, table name and type criteria are returned. They are ordered by TABLE_TYPE, TABLE_SCHEM and TABLE_NAME.
Each table description has the following columns:
null)
null)
null)
null)
null)
Note: Some databases may not return information for all tables.
getTables in interface java.sql.DatabaseMetaDatacatalog - a catalog name; "" retrieves those without a
null means drop catalog name from the selection criteriaschemaPattern - a schema name pattern; "" retrieves those
without a schematableNamePattern - a table name patterntypes - a list of table types to include; null returns all types
java.sql.SQLException - if a database-access error occurs.getSearchStringEscape()
public java.sql.ResultSet getTableTypes()
throws java.sql.SQLException
The table type is:
getTableTypes in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public java.lang.String getTimeDateFunctions()
throws java.sql.SQLException
getTimeDateFunctions in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public java.sql.ResultSet getTypeInfo()
throws java.sql.SQLException
Each type description has the following columns:
getTypeInfo in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public java.sql.ResultSet getUDTs(java.lang.String catalog,
java.lang.String schemaPattern,
java.lang.String typeNamePattern,
int[] types)
throws java.sql.SQLException
Only types matching the catalog, schema, type name and type criteria are returned. They are ordered by DATA_TYPE, TYPE_SCHEM and TYPE_NAME. The type name parameter may be a fully-qualified name. In this case, the catalog and schemaPattern parameters are ignored.
Each type description has the following columns:
Note: If the driver does not support UDTs, an empty result set is returned.
getUDTs in interface java.sql.DatabaseMetaDatacatalog - a catalog name; "" retrieves those without a
null means drop catalog name from the selection criteriaschemaPattern - a schema name pattern; "" retrieves those
without a schematypeNamePattern - a type name pattern; may be a fully-qualified
nametypes - a list of user-named types to include
(JAVA_OBJECT, STRUCT, or DISTINCT); null returns all types
java.sql.SQLException - if a database access error occurs
public java.lang.String getURL()
throws java.sql.SQLException
getURL in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs
public java.lang.String getUserName()
throws java.sql.SQLException
getUserName in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public java.sql.ResultSet getVersionColumns(java.lang.String catalog,
java.lang.String schema,
java.lang.String table)
throws java.sql.SQLException
Each column description has the following columns:
getVersionColumns in interface java.sql.DatabaseMetaDatacatalog - a catalog name; "" retrieves those without a
null means drop catalog name from the selection criteriaschema - a schema name; "" retrieves those without a schematable - a table name
java.sql.SQLException - if a database-access error occurs.
public boolean isCatalogAtStart()
throws java.sql.SQLException
isCatalogAtStart in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public boolean isReadOnly()
throws java.sql.SQLException
isReadOnly in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public java.sql.Connection getConnection()
throws java.sql.SQLException
getConnection in interface java.sql.DatabaseMetaDatajava.sql.SQLException - if a database-access error occurs.
public boolean nullPlusNonNullIsNull()
throws java.sql.SQLException
NULL and non-NULL values being
NULL.
nullPlusNonNullIsNull in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean nullsAreSortedAtEnd()
throws java.sql.SQLException
nullsAreSortedAtEnd in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean nullsAreSortedAtStart()
throws java.sql.SQLException
nullsAreSortedAtStart in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean nullsAreSortedHigh()
throws java.sql.SQLException
nullsAreSortedHigh in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean nullsAreSortedLow()
throws java.sql.SQLException
nullsAreSortedLow in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean storesLowerCaseIdentifiers()
throws java.sql.SQLException
storesLowerCaseIdentifiers in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean storesLowerCaseQuotedIdentifiers()
throws java.sql.SQLException
storesLowerCaseQuotedIdentifiers in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean storesMixedCaseIdentifiers()
throws java.sql.SQLException
storesMixedCaseIdentifiers in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean storesMixedCaseQuotedIdentifiers()
throws java.sql.SQLException
storesMixedCaseQuotedIdentifiers in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean storesUpperCaseIdentifiers()
throws java.sql.SQLException
storesUpperCaseIdentifiers in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean storesUpperCaseQuotedIdentifiers()
throws java.sql.SQLException
storesUpperCaseQuotedIdentifiers in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsAlterTableWithAddColumn()
throws java.sql.SQLException
supportsAlterTableWithAddColumn in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsAlterTableWithDropColumn()
throws java.sql.SQLException
supportsAlterTableWithDropColumn in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsANSI92EntryLevelSQL()
throws java.sql.SQLException
supportsANSI92EntryLevelSQL in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsANSI92FullSQL()
throws java.sql.SQLException
supportsANSI92FullSQL in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsANSI92IntermediateSQL()
throws java.sql.SQLException
supportsANSI92IntermediateSQL in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsCatalogsInDataManipulation()
throws java.sql.SQLException
supportsCatalogsInDataManipulation in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsCatalogsInIndexDefinitions()
throws java.sql.SQLException
supportsCatalogsInIndexDefinitions in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsCatalogsInPrivilegeDefinitions()
throws java.sql.SQLException
supportsCatalogsInPrivilegeDefinitions in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsCatalogsInProcedureCalls()
throws java.sql.SQLException
supportsCatalogsInProcedureCalls in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsCatalogsInTableDefinitions()
throws java.sql.SQLException
supportsCatalogsInTableDefinitions in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsColumnAliasing()
throws java.sql.SQLException
If so, the SQL AS clause can be used to provide names for computed columns or to provide alias names for columns as required. A JDBC-Compliant driver always returns true.
supportsColumnAliasing in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsConvert()
throws java.sql.SQLException
supportsConvert in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsConvert(int fromType,
int toType)
throws java.sql.SQLException
supportsConvert in interface java.sql.DatabaseMetaDatafromType - the type to convert fromtoType - the type to convert to
true if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsCoreSQLGrammar()
throws java.sql.SQLException
supportsCoreSQLGrammar in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsCorrelatedSubqueries()
throws java.sql.SQLException
supportsCorrelatedSubqueries in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsDataDefinitionAndDataManipulationTransactions()
throws java.sql.SQLException
supportsDataDefinitionAndDataManipulationTransactions in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsDataManipulationTransactionsOnly()
throws java.sql.SQLException
supportsDataManipulationTransactionsOnly in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsDifferentTableCorrelationNames()
throws java.sql.SQLException
supportsDifferentTableCorrelationNames in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsExpressionsInOrderBy()
throws java.sql.SQLException
supportsExpressionsInOrderBy in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsExtendedSQLGrammar()
throws java.sql.SQLException
supportsExtendedSQLGrammar in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsFullOuterJoins()
throws java.sql.SQLException
supportsFullOuterJoins in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsGroupBy()
throws java.sql.SQLException
supportsGroupBy in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsGroupByBeyondSelect()
throws java.sql.SQLException
supportsGroupByBeyondSelect in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsGroupByUnrelated()
throws java.sql.SQLException
supportsGroupByUnrelated in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsIntegrityEnhancementFacility()
throws java.sql.SQLException
supportsIntegrityEnhancementFacility in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsLikeEscapeClause()
throws java.sql.SQLException
LIKE
escape clause.
supportsLikeEscapeClause in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsLimitedOuterJoins()
throws java.sql.SQLException
true if the method
supportsFullOuterJoins returns true).
supportsLimitedOuterJoins in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsMinimumSQLGrammar()
throws java.sql.SQLException
supportsMinimumSQLGrammar in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsMixedCaseIdentifiers()
throws java.sql.SQLException
supportsMixedCaseIdentifiers in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsMixedCaseQuotedIdentifiers()
throws java.sql.SQLException
supportsMixedCaseQuotedIdentifiers in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsMultipleResultSets()
throws java.sql.SQLException
supportsMultipleResultSets in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsMultipleTransactions()
throws java.sql.SQLException
supportsMultipleTransactions in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsNonNullableColumns()
throws java.sql.SQLException
supportsNonNullableColumns in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsOpenCursorsAcrossCommit()
throws java.sql.SQLException
supportsOpenCursorsAcrossCommit in interface java.sql.DatabaseMetaDatatrue if cursors always remain open;
false if they might not remain open
java.sql.SQLException - if a database-access error occurs.
public boolean supportsOpenCursorsAcrossRollback()
throws java.sql.SQLException
supportsOpenCursorsAcrossRollback in interface java.sql.DatabaseMetaDatatrue if cursors always remain open;
false if they might not remain open
java.sql.SQLException - if a database-access error occurs.
public boolean supportsOpenStatementsAcrossCommit()
throws java.sql.SQLException
supportsOpenStatementsAcrossCommit in interface java.sql.DatabaseMetaDatatrue if statements always remain open;
false if they might not remain open
java.sql.SQLException - if a database-access error occurs.
public boolean supportsOpenStatementsAcrossRollback()
throws java.sql.SQLException
supportsOpenStatementsAcrossRollback in interface java.sql.DatabaseMetaDatatrue if statements always remain open;
false if they might not remain open
java.sql.SQLException - if a database-access error occurs.
public boolean supportsOrderByUnrelated()
throws java.sql.SQLException
supportsOrderByUnrelated in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsOuterJoins()
throws java.sql.SQLException
supportsOuterJoins in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsPositionedDelete()
throws java.sql.SQLException
supportsPositionedDelete in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsPositionedUpdate()
throws java.sql.SQLException
supportsPositionedUpdate in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsSchemasInDataManipulation()
throws java.sql.SQLException
supportsSchemasInDataManipulation in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsSchemasInIndexDefinitions()
throws java.sql.SQLException
supportsSchemasInIndexDefinitions in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsSchemasInPrivilegeDefinitions()
throws java.sql.SQLException
supportsSchemasInPrivilegeDefinitions in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsSchemasInProcedureCalls()
throws java.sql.SQLException
supportsSchemasInProcedureCalls in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsSchemasInTableDefinitions()
throws java.sql.SQLException
supportsSchemasInTableDefinitions in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsSelectForUpdate()
throws java.sql.SQLException
supportsSelectForUpdate in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsStoredProcedures()
throws java.sql.SQLException
supportsStoredProcedures in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsSubqueriesInComparisons()
throws java.sql.SQLException
supportsSubqueriesInComparisons in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsSubqueriesInExists()
throws java.sql.SQLException
EXISTS expressions.
supportsSubqueriesInExists in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsSubqueriesInIns()
throws java.sql.SQLException
IN statements.
supportsSubqueriesInIns in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsSubqueriesInQuantifieds()
throws java.sql.SQLException
supportsSubqueriesInQuantifieds in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsTableCorrelationNames()
throws java.sql.SQLException
supportsTableCorrelationNames in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsTransactionIsolationLevel(int level)
throws java.sql.SQLException
supportsTransactionIsolationLevel in interface java.sql.DatabaseMetaDatalevel - the values are defined in java.sql.Connection
true if so
java.sql.SQLException - if a database-access error occurs.Connection
public boolean supportsTransactions()
throws java.sql.SQLException
commit is a noop, and the isolation level is
TRANSACTION_NONE.
supportsTransactions in interface java.sql.DatabaseMetaDatatrue if transactions are supported
java.sql.SQLException - if a database-access error occurs.
public boolean supportsUnion()
throws java.sql.SQLException
supportsUnion in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsUnionAll()
throws java.sql.SQLException
supportsUnionAll in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean usesLocalFilePerTable()
throws java.sql.SQLException
usesLocalFilePerTable in interface java.sql.DatabaseMetaDatatrue if the database uses a local file for each
table
java.sql.SQLException - if a database-access error occurs.
public boolean usesLocalFiles()
throws java.sql.SQLException
usesLocalFiles in interface java.sql.DatabaseMetaDatatrue if so
java.sql.SQLException - if a database-access error occurs.
public boolean supportsResultSetType(int type)
throws java.sql.SQLException
| JDBC type | SQL Server cursor type | Server load | Description |
| TYPE_FORWARD_ONLY | Forward-only, dynamic (fast forward-only, static with useCursors=true) |
Light | Fast, will read all data (less fast, doesn't read all data with useCursors=true). Forward only. |
| TYPE_SCROLL_INSENSITIVE | Static cursor | Heavy | Only use with CONCUR_READ_ONLY. SQL Server generates a temporary table, so changes made by others are not visible. Scrollable. |
| TYPE_SCROLL_SENSITIVE | Keyset cursor | Medium | Others' updates or deletes visible, but not others' inserts. Scrollable. |
| TYPE_SCROLL_SENSITIVE + 1 | Dynamic cursor | Heavy | Others' updates, deletes and inserts visible. Scrollable. |
supportsResultSetType in interface java.sql.DatabaseMetaDatatype - defined in java.sql.ResultSet
true if so; false otherwise
java.sql.SQLException - if a database access error occursConnection,
supportsResultSetConcurrency(int, int)
public boolean supportsResultSetConcurrency(int type,
int concurrency)
throws java.sql.SQLException
| JDBC concurrency | SQL Server concurrency | Row locks | Description |
| CONCUR_READ_ONLY | Read only | No | Read-only. |
| CONCUR_UPDATABLE | Optimistic concurrency, updatable | No | Row integrity checked with timestamp comparison or, when not available, value comparison (except text and image fields). |
| CONCUR_UPDATABLE+1 | Pessimistic concurrency, updatable | Yes | Row integrity is ensured by locking rows. |
| CONCUR_UPDATABLE+2 | Optimistic concurrency, updatable | No | Row integrity checked with value comparison (except text and image fields). |
supportsResultSetConcurrency in interface java.sql.DatabaseMetaDatatype - defined in java.sql.ResultSetconcurrency - type defined in java.sql.ResultSet
true if so; false otherwise
java.sql.SQLException - if a database access error occursConnection,
supportsResultSetType(int)
public boolean ownUpdatesAreVisible(int type)
throws java.sql.SQLException
ownUpdatesAreVisible in interface java.sql.DatabaseMetaDatatype - ResultSet type
true if updates are visible for the
result set type; false otherwise
java.sql.SQLException - if a database access error occurs
public boolean ownDeletesAreVisible(int type)
throws java.sql.SQLException
ownDeletesAreVisible in interface java.sql.DatabaseMetaDatatype - ResultSet type
true if deletes are visible for the
result set type; false otherwise
java.sql.SQLException - if a database access error occurs
public boolean ownInsertsAreVisible(int type)
throws java.sql.SQLException
ownInsertsAreVisible in interface java.sql.DatabaseMetaDatatype - ResultSet type
true if inserts are visible for the
result set type; false otherwise
java.sql.SQLException - if a database access error occurs
public boolean othersUpdatesAreVisible(int type)
throws java.sql.SQLException
othersUpdatesAreVisible in interface java.sql.DatabaseMetaDatatype - ResultSet type
true if updates made by others are
visible for the result set type; false otherwise
java.sql.SQLException - if a database access error occurs
public boolean othersDeletesAreVisible(int type)
throws java.sql.SQLException
othersDeletesAreVisible in interface java.sql.DatabaseMetaDatatype - ResultSet type
true if deletes made by others are
visible for the result set type; false otherwise
java.sql.SQLException - if a database access error occurs
public boolean othersInsertsAreVisible(int type)
throws java.sql.SQLException
othersInsertsAreVisible in interface java.sql.DatabaseMetaDatatype - ResultSet type
true if inserts made by others are visible
for the result set type; false otherwise
java.sql.SQLException - if a database access error occurs
public boolean updatesAreDetected(int type)
throws java.sql.SQLException
ResultSet.rowUpdated .
updatesAreDetected in interface java.sql.DatabaseMetaDatatype - ResultSet type
true if changes are detected by the
result set type; false otherwise
java.sql.SQLException - if a database access error occurs
public boolean deletesAreDetected(int type)
throws java.sql.SQLException
deletesAreDetected in interface java.sql.DatabaseMetaDatatype - ResultSet type
true if changes are detected by the result set type
java.sql.SQLException - if a database access error occurs
public boolean insertsAreDetected(int type)
throws java.sql.SQLException
insertsAreDetected in interface java.sql.DatabaseMetaDatatype - ResultSet type
true if changes are detected by the result set type
java.sql.SQLException - if a database access error occurs
public boolean supportsBatchUpdates()
throws java.sql.SQLException
supportsBatchUpdates in interface java.sql.DatabaseMetaDatatrue if the driver supports batch updates;
false otherwise
java.sql.SQLException - if a database access error occurs
private void setCaseSensitiveFlag()
throws java.sql.SQLException
java.sql.SQLException
public java.sql.ResultSet getAttributes(java.lang.String catalog,
java.lang.String schemaPattern,
java.lang.String typeNamePattern,
java.lang.String attributeNamePattern)
throws java.sql.SQLException
getAttributes in interface java.sql.DatabaseMetaDatajava.sql.SQLException
public int getDatabaseMajorVersion()
throws java.sql.SQLException
getDatabaseMajorVersion in interface java.sql.DatabaseMetaDatajava.sql.SQLException
public int getDatabaseMinorVersion()
throws java.sql.SQLException
getDatabaseMinorVersion in interface java.sql.DatabaseMetaDatajava.sql.SQLException
public int getJDBCMajorVersion()
throws java.sql.SQLException
getJDBCMajorVersion in interface java.sql.DatabaseMetaDatajava.sql.SQLException
public int getJDBCMinorVersion()
throws java.sql.SQLException
getJDBCMinorVersion in interface java.sql.DatabaseMetaDatajava.sql.SQLException
public int getResultSetHoldability()
throws java.sql.SQLException
getResultSetHoldability in interface java.sql.DatabaseMetaDatajava.sql.SQLException
public int getSQLStateType()
throws java.sql.SQLException
getSQLStateType in interface java.sql.DatabaseMetaDatajava.sql.SQLException
public java.sql.ResultSet getSuperTables(java.lang.String catalog,
java.lang.String schemaPattern,
java.lang.String tableNamePattern)
throws java.sql.SQLException
getSuperTables in interface java.sql.DatabaseMetaDatajava.sql.SQLException
public java.sql.ResultSet getSuperTypes(java.lang.String catalog,
java.lang.String schemaPattern,
java.lang.String typeNamePattern)
throws java.sql.SQLException
getSuperTypes in interface java.sql.DatabaseMetaDatajava.sql.SQLException
public boolean locatorsUpdateCopy()
throws java.sql.SQLException
true if updates are made to a copy of the LOB; returns
false if LOB updates are made directly to the database.
NOTE: Since SQL Server / Sybase do not support LOB locators as Oracle does (AFAIK);
this method always returns true.
locatorsUpdateCopy in interface java.sql.DatabaseMetaDatajava.sql.SQLException
public boolean supportsGetGeneratedKeys()
throws java.sql.SQLException
true if getting auto-generated keys is supported after a
statment is executed; returns false otherwise
supportsGetGeneratedKeys in interface java.sql.DatabaseMetaDatajava.sql.SQLException
public boolean supportsMultipleOpenResults()
throws java.sql.SQLException
true if Callable statements can return multiple result sets;
returns false if they can only return one result set.
supportsMultipleOpenResults in interface java.sql.DatabaseMetaDatajava.sql.SQLException
public boolean supportsNamedParameters()
throws java.sql.SQLException
true if the database supports named parameters;
returns false if the database does not support named parameters.
supportsNamedParameters in interface java.sql.DatabaseMetaDatajava.sql.SQLException
public boolean supportsResultSetHoldability(int param)
throws java.sql.SQLException
supportsResultSetHoldability in interface java.sql.DatabaseMetaDatajava.sql.SQLException
public boolean supportsSavepoints()
throws java.sql.SQLException
true if savepoints are supported; returns
false otherwise
supportsSavepoints in interface java.sql.DatabaseMetaDatajava.sql.SQLException
public boolean supportsStatementPooling()
throws java.sql.SQLException
true if the database supports statement pooling;
returns false otherwise.
supportsStatementPooling in interface java.sql.DatabaseMetaDatajava.sql.SQLExceptionprivate static java.lang.String processEscapes(java.lang.String pattern)
pattern - the pattern to tranform
String
private java.lang.String syscall(java.lang.String catalog,
java.lang.String call)
catalog - the database name or nullcall - the stored procedure call to format
Stringprivate static void upperCaseColumnNames(JtdsResultSet results) throws java.sql.SQLException
Sybase returns column names in lowecase while the JDBC standard suggests they should be uppercase.
results - the result set to modify
java.sql.SQLExceptionprivate static CachedResultSet createTypeInfoResultSet(JtdsResultSet rs, boolean useLOBs) throws java.sql.SQLException
java.sql.SQLException
private static java.util.Collection getSortedTypes(java.sql.ResultSet rs,
boolean useLOBs)
throws java.sql.SQLException
java.sql.SQLException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.Support
This class contains static utility methods designed to support the main driver classes.
Implementation notes:
| Field Summary | |
private static java.math.BigDecimal |
BIG_DECIMAL_ONE
|
private static java.math.BigDecimal |
BIG_DECIMAL_ZERO
|
private static java.lang.ThreadLocal |
calendar
Thread-bound utility Calendar object. |
private static java.sql.Date |
DATE_ZERO
|
private static java.lang.Double |
DOUBLE_ONE
|
private static java.lang.Double |
DOUBLE_ZERO
|
private static java.lang.Float |
FLOAT_ONE
|
private static java.lang.Float |
FLOAT_ZERO
|
private static char[] |
hex
Hex constants to use in conversion routines. |
private static java.lang.Integer |
INTEGER_ONE
|
private static java.lang.Integer |
INTEGER_ZERO
|
private static java.lang.Long |
LONG_ONE
|
private static java.lang.Long |
LONG_ZERO
|
private static java.math.BigInteger |
MAX_VALUE_28
|
private static java.math.BigInteger |
MAX_VALUE_38
|
private static java.math.BigDecimal |
MAX_VALUE_LONG_BD
|
private static java.math.BigInteger |
MAX_VALUE_LONG_BI
|
private static java.math.BigDecimal |
MIN_VALUE_LONG_BD
|
private static java.math.BigInteger |
MIN_VALUE_LONG_BI
|
private static java.sql.Time |
TIME_ZERO
|
private static java.util.HashMap |
typeMap
Convert java clases to java.sql.Type constant. |
| Constructor Summary | |
private |
Support()
|
| Method Summary | |
(package private) static int |
calculateNamedPipeBufferSize(int tdsVersion,
int packetSize)
Calculate the buffer size to use when buffering the InputStream
for named pipes.
|
(package private) static java.lang.Object |
castNumeric(java.lang.Object orig,
int sourceType,
int targetType)
|
(package private) static java.lang.Object |
convert(java.lang.Object callerReference,
java.lang.Object x,
int jdbcType,
java.lang.String charSet)
Convert an existing data object to the specified JDBC type. |
static java.lang.Object |
convertLOB(java.lang.Object value)
Converts a LOB to the equivalent Java type, i.e. |
static int |
convertLOBType(int type)
Converts a LOB type constant to the equivalent Java type constant, i.e. |
(package private) static void |
embedData(java.lang.StringBuffer buf,
java.lang.Object value,
boolean isUnicode,
ConnectionJDBC2 connection)
Embed the data object as a string literal in the buffer supplied. |
(package private) static byte[] |
encodeString(java.lang.String cs,
java.lang.String value)
Encode a string into a byte array using the specified character set. |
(package private) static java.lang.String |
getClassName(int jdbcType)
Retrieve the fully qualified java class name for the supplied JDBC Types constant. |
private static ConnectionJDBC2 |
getConnection(java.lang.Object callerReference)
Returns the connection for a given ResultSet,
Statement or Connection object. |
(package private) static int |
getJdbcType(java.lang.Class typeClass)
Get the JDBC type constant which matches the supplied Class. |
(package private) static int |
getJdbcType(java.lang.Object value)
Get the JDBC type constant which matches the supplied Object type. |
(package private) static java.lang.String |
getJdbcTypeName(int jdbcType)
Get a String describing the supplied JDBC type constant. |
(package private) static java.lang.String |
getParameterDefinitions(ParamInfo[] parameters)
Constructs a parameter definition string for use with sp_executesql, sp_prepare, sp_prepexec, sp_cursoropen, sp_cursorprepare and sp_cursorprepexec. |
(package private) static java.lang.String |
getStatementKey(java.lang.String sql,
ParamInfo[] params,
int serverType,
java.lang.String catalog,
boolean autoCommit,
boolean cursor)
Generates a unique statement key for a given SQL statement. |
static boolean |
isWindowsOS()
Checks the os.name system property to see if it starts
with "windows". |
static java.lang.Throwable |
linkException(java.lang.Exception exception,
java.lang.Throwable cause)
Link the original cause to an Exception.
|
static java.sql.SQLException |
linkException(java.sql.SQLException sqle,
java.lang.Throwable cause)
Link the original cause to an SQLException.
|
static java.sql.SQLWarning |
linkException(java.sql.SQLWarning sqle,
java.lang.Throwable cause)
Link the original cause to an SQLWarning.
|
(package private) static java.math.BigDecimal |
normalizeBigDecimal(java.math.BigDecimal value,
int maxPrecision)
Normalize a BigDecimal value so that it fits within the available precision. |
(package private) static java.lang.String |
substituteParameters(java.lang.String sql,
ParamInfo[] list,
ConnectionJDBC2 connection)
Substitute actual data for the parameter markers to simulate parameter substitution in a PreparedStatement. |
(package private) static java.lang.String |
substituteParamMarkers(java.lang.String sql,
ParamInfo[] list)
Update the SQL string and replace the ? |
static long |
timeFromZone(java.util.Date value,
java.util.Calendar target)
Convert a timestamp from a different Timezone. |
static long |
timeToZone(java.util.Date value,
java.util.Calendar target)
Convert a timestamp to a different Timezone. |
static java.lang.String |
toHex(byte[] bytes)
Convert a byte[] object to a hex string. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private static final java.lang.Integer INTEGER_ZERO
private static final java.lang.Integer INTEGER_ONE
private static final java.lang.Long LONG_ZERO
private static final java.lang.Long LONG_ONE
private static final java.lang.Float FLOAT_ZERO
private static final java.lang.Float FLOAT_ONE
private static final java.lang.Double DOUBLE_ZERO
private static final java.lang.Double DOUBLE_ONE
private static final java.math.BigDecimal BIG_DECIMAL_ZERO
private static final java.math.BigDecimal BIG_DECIMAL_ONE
private static final java.sql.Date DATE_ZERO
private static final java.sql.Time TIME_ZERO
private static final java.math.BigInteger MIN_VALUE_LONG_BI
private static final java.math.BigInteger MAX_VALUE_LONG_BI
private static final java.math.BigDecimal MIN_VALUE_LONG_BD
private static final java.math.BigDecimal MAX_VALUE_LONG_BD
private static final java.math.BigInteger MAX_VALUE_28
private static final java.math.BigInteger MAX_VALUE_38
private static final java.util.HashMap typeMap
private static final char[] hex
private static final java.lang.ThreadLocal calendar
| Constructor Detail |
private Support()
| Method Detail |
public static java.lang.String toHex(byte[] bytes)
bytes - The byte array to convert.
String.
static java.math.BigDecimal normalizeBigDecimal(java.math.BigDecimal value,
int maxPrecision)
throws java.sql.SQLException
value - The decimal value to normalize.maxPrecision - The decimal precision supported by the server
(assumed to be a value of either 28 or 38).
BigDecimal.
java.sql.SQLException - If the number is too big.
static java.lang.Object castNumeric(java.lang.Object orig,
int sourceType,
int targetType)
static java.lang.Object convert(java.lang.Object callerReference,
java.lang.Object x,
int jdbcType,
java.lang.String charSet)
throws java.sql.SQLException
callerReference - an object reference to the caller of this method;
must be a Connection,
Statement or ResultSetx - the data object to convertjdbcType - the required type constant from
java.sql.Types
java.sql.SQLException - if the conversion is not supported or failsstatic int getJdbcType(java.lang.Object value)
value - The object to analyse.
int.static int getJdbcType(java.lang.Class typeClass)
Class.
typeClass - the Class to analyse
intstatic java.lang.String getJdbcTypeName(int jdbcType)
jdbcType - The constant to be decoded.
String.static java.lang.String getClassName(int jdbcType)
jdbcType - The JDBC Types constant.
String.
static void embedData(java.lang.StringBuffer buf,
java.lang.Object value,
boolean isUnicode,
ConnectionJDBC2 connection)
throws java.sql.SQLException
buf - The buffer in which the data will be embedded.value - The data object.isUnicode - Set to true if Unicode strings should be used, else false.connection - The ConnectionJDBC2 object.
java.sql.SQLException
static java.lang.String getStatementKey(java.lang.String sql,
ParamInfo[] params,
int serverType,
java.lang.String catalog,
boolean autoCommit,
boolean cursor)
sql - the sql statement to generate the key forparams - the statement parametersserverType - the type of server to generate the key forcatalog - the catalog is required for uniqueness on Microsoft
SQL ServerautoCommit - true if in auto commit modecursor - true if this is a prepared cursor
static java.lang.String getParameterDefinitions(ParamInfo[] parameters)
parameters - Parameters to construct the definition for
static java.lang.String substituteParamMarkers(java.lang.String sql,
ParamInfo[] list)
sql - the SQL containing markers to substitutelist - the parameter list
String
static java.lang.String substituteParameters(java.lang.String sql,
ParamInfo[] list,
ConnectionJDBC2 connection)
throws java.sql.SQLException
sql - The SQL containing parameter markers to substitute.list - The parameter descriptors.connection - The current connection.
java.sql.SQLException
static byte[] encodeString(java.lang.String cs,
java.lang.String value)
cs - The Charset name.value - The value to encode.
byte[].
public static java.sql.SQLWarning linkException(java.sql.SQLWarning sqle,
java.lang.Throwable cause)
SQLWarning.
This convenience method calls linkException(Exception, Throwable)
and casts the result for cleaner code elsewhere.
sqle - The SQLWarning to enhance.cause - The Throwable to link.
SQLWarning object.
public static java.sql.SQLException linkException(java.sql.SQLException sqle,
java.lang.Throwable cause)
SQLException.
This convenience method calls linkException(Exception, Throwable)
and casts the result for cleaner code elsewhere.
sqle - The SQLException to enhance.cause - The Throwable to link.
SQLException object.
public static java.lang.Throwable linkException(java.lang.Exception exception,
java.lang.Throwable cause)
Exception.
If running under JVM 1.4+ the Throwable.initCause(Throwable)
method will be invoked to chain the exception, else the exception is
logged via the Logger class.
Modeled after the code written by Brian Heineman.
exception - The Exception to enhance.cause - The Throwable to link.
Exception object.
public static long timeToZone(java.util.Date value,
java.util.Calendar target)
value - the timestamp valuetarget - the Calendar containing the TimeZone
long
public static long timeFromZone(java.util.Date value,
java.util.Calendar target)
value - the timestamp value.target - the Calendar containing the TimeZone.
long.
public static java.lang.Object convertLOB(java.lang.Object value)
throws java.sql.SQLException
Clob to
String and Blob to byte[]. If the
value passed is not a LOB object, it is left unchanged and no exception
is thrown; the idea is to transparently convert only LOBs.
value - an object that may be a LOB
java.sql.SQLException - if an error occurs while reading the LOB contentspublic static int convertLOBType(int type)
Types.CLOB to Types.LONGVARCHAR and
Types.BLOB to Types.LONGVARBINARY. If the
type passed is not that of a LOB, it is left unchanged and no exception
is thrown; the idea is to transparently convert only LOB types.
type - a Types constant defining a JDBC type, possibly a
LOB
public static boolean isWindowsOS()
os.name system property to see if it starts
with "windows".
true if os.name starts with "windows",
else false.private static ConnectionJDBC2 getConnection(java.lang.Object callerReference)
ResultSet,
Statement or Connection object.
callerReference - an object reference to the caller of this method;
must be a Connection, Statement or
ResultSet
static int calculateNamedPipeBufferSize(int tdsVersion,
int packetSize)
InputStream
for named pipes.
The buffer size is tied directly to the packet size because each request
to the SmbNamedPipe will send a request for a particular
size of packet. In other words, if you only request 1 byte, the
SmbNamedPipe will send a request out and only ask for 1 byte
back. Buffering the expected packet size ensures that all of the data
will be returned in the buffer without wasting any space.
tdsVersion - the TDS version for the connectionpacketSize - requested packet size for the connection
packetSize == 0,
else packetSize
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.JtdsResultSet
jTDS Implementation of the java.sql.ResultSet interface supporting forward read only result sets.
Implementation notes:
| Field Summary | |
protected boolean |
cancelled
True if the query has been cancelled by another thread. |
(package private) static int |
CLOSE_CURSORS_AT_COMMIT
|
protected boolean |
closed
True if this result set is closed. |
protected int |
columnCount
Number of visible columns in row. |
private java.util.HashMap |
columnMap
Cache to optimize findColumn(String) lookups |
protected ColInfo[] |
columns
The array of column descriptors. |
protected int |
concurrency
The result set concurrency. |
protected java.lang.Object[] |
currentRow
The current result set row. |
protected java.lang.String |
cursorName
The cursor name to be used for positioned updates. |
protected int |
direction
The fetch direction. |
private static java.text.NumberFormat |
f
Used to format numeric values when scale is specified. |
protected int |
fetchDirection
The fetch direction. |
protected int |
fetchSize
The fetch size (only applies to cursor ResultSets). |
(package private) static int |
HOLD_CURSORS_OVER_COMMIT
|
protected static int |
INITIAL_ROW_COUNT
Initial size for row array. |
protected int |
pos
The current row number. |
protected static int |
POS_AFTER_LAST
|
protected static int |
POS_BEFORE_FIRST
|
protected int |
resultSetType
The result set type. |
protected java.util.ArrayList |
rowData
Cached row data for forward only result set. |
protected int |
rowPtr
Index of current row in rowData. |
protected int |
rowsInResult
The number of rows in the result. |
protected JtdsStatement |
statement
The parent statement. |
protected boolean |
wasNull
True if last column retrieved was null. |
| Fields inherited from interface java.sql.ResultSet |
CONCUR_READ_ONLY, CONCUR_UPDATABLE, FETCH_FORWARD, FETCH_REVERSE, FETCH_UNKNOWN, TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, TYPE_SCROLL_SENSITIVE |
| Constructor Summary | |
(package private) |
JtdsResultSet(JtdsStatement statement,
int resultSetType,
int concurrency,
ColInfo[] columns)
Construct a simple result set from a statement, metadata or generated keys. |
| Method Summary | |
boolean |
absolute(int row)
|
void |
afterLast()
|
void |
beforeFirst()
|
protected void |
cacheResultSetRows()
Cache the remaining results to free up connection. |
void |
cancelRowUpdates()
|
protected void |
checkOpen()
Check that this connection is still open. |
protected void |
checkScrollable()
Check that this resultset is scrollable. |
protected void |
checkUpdateable()
Check that this resultset is updateable. |
void |
clearWarnings()
|
void |
close()
|
protected ColInfo[] |
copyInfo(ColInfo[] info)
Copy an existing result set column descriptor array. |
protected java.lang.Object[] |
copyRow(java.lang.Object[] row)
Copy an existing result set row. |
void |
deleteRow()
|
int |
findColumn(java.lang.String columnName)
|
boolean |
first()
|
java.sql.Array |
getArray(int columnIndex)
|
java.sql.Array |
getArray(java.lang.String columnName)
|
java.io.InputStream |
getAsciiStream(int columnIndex)
|
java.io.InputStream |
getAsciiStream(java.lang.String columnName)
|
java.math.BigDecimal |
getBigDecimal(int columnIndex)
|
java.math.BigDecimal |
getBigDecimal(int columnIndex,
int scale)
|
java.math.BigDecimal |
getBigDecimal(java.lang.String columnName)
|
java.math.BigDecimal |
getBigDecimal(java.lang.String columnName,
int scale)
|
java.io.InputStream |
getBinaryStream(int columnIndex)
|
java.io.InputStream |
getBinaryStream(java.lang.String columnName)
|
java.sql.Blob |
getBlob(int columnIndex)
|
java.sql.Blob |
getBlob(java.lang.String columnName)
|
boolean |
getBoolean(int columnIndex)
|
boolean |
getBoolean(java.lang.String columnName)
|
byte |
getByte(int columnIndex)
|
byte |
getByte(java.lang.String columnName)
|
byte[] |
getBytes(int columnIndex)
|
byte[] |
getBytes(java.lang.String columnName)
|
java.io.Reader |
getCharacterStream(int columnIndex)
|
java.io.Reader |
getCharacterStream(java.lang.String columnName)
|
java.sql.Clob |
getClob(int columnIndex)
|
java.sql.Clob |
getClob(java.lang.String columnName)
|
protected java.lang.Object |
getColumn(int index)
Get the specified column's data item. |
protected static int |
getColumnCount(ColInfo[] columns)
Retrieve the column count excluding hidden columns |
protected ColInfo[] |
getColumns()
Retrieve the column descriptor array. |
int |
getConcurrency()
|
private ConnectionJDBC2 |
getConnection()
Returns the ConnectionJDBC2 object referenced by the
statement instance variable. |
protected java.lang.Object[] |
getCurrentRow()
Retrieve the current row data. |
java.lang.String |
getCursorName()
|
java.sql.Date |
getDate(int columnIndex)
|
java.sql.Date |
getDate(int columnIndex,
java.util.Calendar cal)
|
java.sql.Date |
getDate(java.lang.String columnName)
|
java.sql.Date |
getDate(java.lang.String columnName,
java.util.Calendar cal)
|
double |
getDouble(int columnIndex)
|
double |
getDouble(java.lang.String columnName)
|
int |
getFetchDirection()
|
int |
getFetchSize()
|
float |
getFloat(int columnIndex)
|
float |
getFloat(java.lang.String columnName)
|
int |
getInt(int columnIndex)
|
int |
getInt(java.lang.String columnName)
|
long |
getLong(int columnIndex)
|
long |
getLong(java.lang.String columnName)
|
java.sql.ResultSetMetaData |
getMetaData()
|
java.lang.Object |
getObject(int columnIndex)
|
java.lang.Object |
getObject(int columnIndex,
java.util.Map map)
|
java.lang.Object |
getObject(java.lang.String columnName)
|
java.lang.Object |
getObject(java.lang.String columnName,
java.util.Map map)
|
java.sql.Ref |
getRef(int columnIndex)
|
java.sql.Ref |
getRef(java.lang.String columnName)
|
int |
getRow()
|
short |
getShort(int columnIndex)
|
short |
getShort(java.lang.String columnName)
|
java.sql.Statement |
getStatement()
|
java.lang.String |
getString(int columnIndex)
|
java.lang.String |
getString(java.lang.String columnName)
|
java.sql.Time |
getTime(int columnIndex)
|
java.sql.Time |
getTime(int columnIndex,
java.util.Calendar cal)
|
java.sql.Time |
getTime(java.lang.String columnName)
|
java.sql.Time |
getTime(java.lang.String columnName,
java.util.Calendar cal)
|
java.sql.Timestamp |
getTimestamp(int columnIndex)
|
java.sql.Timestamp |
getTimestamp(int columnIndex,
java.util.Calendar cal)
|
java.sql.Timestamp |
getTimestamp(java.lang.String columnName)
|
java.sql.Timestamp |
getTimestamp(java.lang.String columnName,
java.util.Calendar cal)
|
int |
getType()
|
java.io.InputStream |
getUnicodeStream(int columnIndex)
|
java.io.InputStream |
getUnicodeStream(java.lang.String columnName)
|
java.net.URL |
getURL(int columnIndex)
|
java.net.URL |
getURL(java.lang.String columnName)
|
java.sql.SQLWarning |
getWarnings()
|
void |
insertRow()
|
boolean |
isAfterLast()
|
boolean |
isBeforeFirst()
|
boolean |
isFirst()
|
boolean |
isLast()
|
boolean |
last()
|
void |
moveToCurrentRow()
|
void |
moveToInsertRow()
|
protected java.lang.Object[] |
newRow()
Create a new row containing empty data items. |
boolean |
next()
|
protected static void |
notImplemented(java.lang.String method)
Report that user tried to call a method which has not been implemented. |
boolean |
previous()
|
void |
refreshRow()
|
boolean |
relative(int row)
|
boolean |
rowDeleted()
|
boolean |
rowInserted()
|
boolean |
rowUpdated()
|
protected void |
setColLabel(int colIndex,
java.lang.String name)
Set the specified column's label. |
protected void |
setColName(int colIndex,
java.lang.String name)
Set the specified column's name. |
protected void |
setColType(int colIndex,
int jdbcType)
Set the specified column's JDBC type. |
protected void |
setColumnCount(int columnCount)
Set the current row's column count. |
protected java.lang.Object |
setColValue(int colIndex,
int jdbcType,
java.lang.Object value,
int length)
Set the specified column's data value. |
void |
setFetchDirection(int direction)
|
void |
setFetchSize(int rows)
|
void |
updateArray(int columnIndex,
java.sql.Array x)
|
void |
updateArray(java.lang.String columnName,
java.sql.Array x)
|
void |
updateAsciiStream(int columnIndex,
java.io.InputStream inputStream,
int length)
|
void |
updateAsciiStream(java.lang.String columnName,
java.io.InputStream x,
int length)
|
void |
updateBigDecimal(int columnIndex,
java.math.BigDecimal x)
|
void |
updateBigDecimal(java.lang.String columnName,
java.math.BigDecimal x)
|
void |
updateBinaryStream(int columnIndex,
java.io.InputStream inputStream,
int length)
|
void |
updateBinaryStream(java.lang.String columnName,
java.io.InputStream x,
int length)
|
void |
updateBlob(int columnIndex,
java.sql.Blob x)
|
void |
updateBlob(java.lang.String columnName,
java.sql.Blob x)
|
void |
updateBoolean(int columnIndex,
boolean x)
|
void |
updateBoolean(java.lang.String columnName,
boolean x)
|
void |
updateByte(int columnIndex,
byte x)
|
void |
updateByte(java.lang.String columnName,
byte x)
|
void |
updateBytes(int columnIndex,
byte[] x)
|
void |
updateBytes(java.lang.String columnName,
byte[] x)
|
void |
updateCharacterStream(int columnIndex,
java.io.Reader reader,
int length)
|
void |
updateCharacterStream(java.lang.String columnName,
java.io.Reader x,
int length)
|
void |
updateClob(int columnIndex,
java.sql.Clob x)
|
void |
updateClob(java.lang.String columnName,
java.sql.Clob x)
|
void |
updateDate(int columnIndex,
java.sql.Date x)
|
void |
updateDate(java.lang.String columnName,
java.sql.Date x)
|
void |
updateDouble(int columnIndex,
double x)
|
void |
updateDouble(java.lang.String columnName,
double x)
|
void |
updateFloat(int columnIndex,
float x)
|
void |
updateFloat(java.lang.String columnName,
float x)
|
void |
updateInt(int columnIndex,
int x)
|
void |
updateInt(java.lang.String columnName,
int x)
|
void |
updateLong(int columnIndex,
long x)
|
void |
updateLong(java.lang.String columnName,
long x)
|
void |
updateNull(int columnIndex)
|
void |
updateNull(java.lang.String columnName)
|
void |
updateObject(int columnIndex,
java.lang.Object x)
|
void |
updateObject(int columnIndex,
java.lang.Object x,
int scale)
|
void |
updateObject(java.lang.String columnName,
java.lang.Object x)
|
void |
updateObject(java.lang.String columnName,
java.lang.Object x,
int scale)
|
void |
updateRef(int columnIndex,
java.sql.Ref x)
|
void |
updateRef(java.lang.String columnName,
java.sql.Ref x)
|
void |
updateRow()
|
void |
updateShort(int columnIndex,
short x)
|
void |
updateShort(java.lang.String columnName,
short x)
|
void |
updateString(int columnIndex,
java.lang.String x)
|
void |
updateString(java.lang.String columnName,
java.lang.String x)
|
void |
updateTime(int columnIndex,
java.sql.Time x)
|
void |
updateTime(java.lang.String columnName,
java.sql.Time x)
|
void |
updateTimestamp(int columnIndex,
java.sql.Timestamp x)
|
void |
updateTimestamp(java.lang.String columnName,
java.sql.Timestamp x)
|
boolean |
wasNull()
|
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
static final int HOLD_CURSORS_OVER_COMMIT
static final int CLOSE_CURSORS_AT_COMMIT
protected static final int POS_BEFORE_FIRST
protected static final int POS_AFTER_LAST
protected static final int INITIAL_ROW_COUNT
protected int pos
protected int rowsInResult
protected int direction
protected int resultSetType
protected int concurrency
protected int columnCount
protected ColInfo[] columns
protected java.lang.Object[] currentRow
protected java.util.ArrayList rowData
protected int rowPtr
protected boolean wasNull
protected JtdsStatement statement
protected boolean closed
protected boolean cancelled
protected int fetchDirection
protected int fetchSize
ResultSets).
protected java.lang.String cursorName
private java.util.HashMap columnMap
private static java.text.NumberFormat f
| Constructor Detail |
JtdsResultSet(JtdsStatement statement, int resultSetType, int concurrency, ColInfo[] columns) throws java.sql.SQLException
statement - The parent statement object or null.resultSetType - one of FORWARD_ONLY, SCROLL_INSENSITIVE, SCROLL_SENSITIVE.concurrency - One of CONCUR_READ_ONLY, CONCUR_UPDATE.columns - The array of column descriptors for the result set row.
java.sql.SQLException| Method Detail |
protected static int getColumnCount(ColInfo[] columns)
columns - The columns array
int.protected ColInfo[] getColumns()
ColInfo[].
protected void setColName(int colIndex,
java.lang.String name)
colIndex - The index of the column in the row.name - The new name.
protected void setColLabel(int colIndex,
java.lang.String name)
colIndex - The index of the column in the row.name - The new label.
protected void setColType(int colIndex,
int jdbcType)
colIndex - The index of the column in the row.jdbcType - The new type value.
protected java.lang.Object setColValue(int colIndex,
int jdbcType,
java.lang.Object value,
int length)
throws java.sql.SQLException
colIndex - index of the columnvalue - new column valuelength - the length of a stream parameter
java.sql.SQLExceptionprotected void setColumnCount(int columnCount)
columnCount - The number of visible columns in the row.
protected java.lang.Object getColumn(int index)
throws java.sql.SQLException
index - the column index in the row
Object
java.sql.SQLException - if the connection is closed;
if index is less than 1;
if index is greater that the number of columns;
if there is no current row
protected void checkOpen()
throws java.sql.SQLException
java.sql.SQLException - if connection closed.
protected void checkScrollable()
throws java.sql.SQLException
java.sql.SQLException - if connection closed.
protected void checkUpdateable()
throws java.sql.SQLException
java.sql.SQLException - if connection closed.
protected static void notImplemented(java.lang.String method)
throws java.sql.SQLException
method - The method name to report in the error message.
java.sql.SQLExceptionprotected java.lang.Object[] newRow()
Object arrayprotected java.lang.Object[] copyRow(java.lang.Object[] row)
row - the result set row to copy
Object arrayprotected ColInfo[] copyInfo(ColInfo[] info)
info - The result set column descriptors to copy.
ColInfo[].protected java.lang.Object[] getCurrentRow()
Object[].
protected void cacheResultSetRows()
throws java.sql.SQLException
java.sql.SQLExceptionprivate ConnectionJDBC2 getConnection() throws java.sql.SQLException
ConnectionJDBC2 object referenced by the
statement instance variable.
ConnectionJDBC2 object.
java.sql.SQLException - on error.
public int getConcurrency()
throws java.sql.SQLException
getConcurrency in interface java.sql.ResultSetjava.sql.SQLException
public int getFetchDirection()
throws java.sql.SQLException
getFetchDirection in interface java.sql.ResultSetjava.sql.SQLException
public int getFetchSize()
throws java.sql.SQLException
getFetchSize in interface java.sql.ResultSetjava.sql.SQLException
public int getRow()
throws java.sql.SQLException
getRow in interface java.sql.ResultSetjava.sql.SQLException
public int getType()
throws java.sql.SQLException
getType in interface java.sql.ResultSetjava.sql.SQLException
public void afterLast()
throws java.sql.SQLException
afterLast in interface java.sql.ResultSetjava.sql.SQLException
public void beforeFirst()
throws java.sql.SQLException
beforeFirst in interface java.sql.ResultSetjava.sql.SQLException
public void cancelRowUpdates()
throws java.sql.SQLException
cancelRowUpdates in interface java.sql.ResultSetjava.sql.SQLException
public void clearWarnings()
throws java.sql.SQLException
clearWarnings in interface java.sql.ResultSetjava.sql.SQLException
public void close()
throws java.sql.SQLException
close in interface java.sql.ResultSetjava.sql.SQLException
public void deleteRow()
throws java.sql.SQLException
deleteRow in interface java.sql.ResultSetjava.sql.SQLException
public void insertRow()
throws java.sql.SQLException
insertRow in interface java.sql.ResultSetjava.sql.SQLException
public void moveToCurrentRow()
throws java.sql.SQLException
moveToCurrentRow in interface java.sql.ResultSetjava.sql.SQLException
public void moveToInsertRow()
throws java.sql.SQLException
moveToInsertRow in interface java.sql.ResultSetjava.sql.SQLException
public void refreshRow()
throws java.sql.SQLException
refreshRow in interface java.sql.ResultSetjava.sql.SQLException
public void updateRow()
throws java.sql.SQLException
updateRow in interface java.sql.ResultSetjava.sql.SQLException
public boolean first()
throws java.sql.SQLException
first in interface java.sql.ResultSetjava.sql.SQLException
public boolean isAfterLast()
throws java.sql.SQLException
isAfterLast in interface java.sql.ResultSetjava.sql.SQLException
public boolean isBeforeFirst()
throws java.sql.SQLException
isBeforeFirst in interface java.sql.ResultSetjava.sql.SQLException
public boolean isFirst()
throws java.sql.SQLException
isFirst in interface java.sql.ResultSetjava.sql.SQLException
public boolean isLast()
throws java.sql.SQLException
isLast in interface java.sql.ResultSetjava.sql.SQLException
public boolean last()
throws java.sql.SQLException
last in interface java.sql.ResultSetjava.sql.SQLException
public boolean next()
throws java.sql.SQLException
next in interface java.sql.ResultSetjava.sql.SQLException
public boolean previous()
throws java.sql.SQLException
previous in interface java.sql.ResultSetjava.sql.SQLException
public boolean rowDeleted()
throws java.sql.SQLException
rowDeleted in interface java.sql.ResultSetjava.sql.SQLException
public boolean rowInserted()
throws java.sql.SQLException
rowInserted in interface java.sql.ResultSetjava.sql.SQLException
public boolean rowUpdated()
throws java.sql.SQLException
rowUpdated in interface java.sql.ResultSetjava.sql.SQLException
public boolean wasNull()
throws java.sql.SQLException
wasNull in interface java.sql.ResultSetjava.sql.SQLException
public byte getByte(int columnIndex)
throws java.sql.SQLException
getByte in interface java.sql.ResultSetjava.sql.SQLException
public short getShort(int columnIndex)
throws java.sql.SQLException
getShort in interface java.sql.ResultSetjava.sql.SQLException
public int getInt(int columnIndex)
throws java.sql.SQLException
getInt in interface java.sql.ResultSetjava.sql.SQLException
public long getLong(int columnIndex)
throws java.sql.SQLException
getLong in interface java.sql.ResultSetjava.sql.SQLException
public float getFloat(int columnIndex)
throws java.sql.SQLException
getFloat in interface java.sql.ResultSetjava.sql.SQLException
public double getDouble(int columnIndex)
throws java.sql.SQLException
getDouble in interface java.sql.ResultSetjava.sql.SQLException
public void setFetchDirection(int direction)
throws java.sql.SQLException
setFetchDirection in interface java.sql.ResultSetjava.sql.SQLException
public void setFetchSize(int rows)
throws java.sql.SQLException
setFetchSize in interface java.sql.ResultSetjava.sql.SQLException
public void updateNull(int columnIndex)
throws java.sql.SQLException
updateNull in interface java.sql.ResultSetjava.sql.SQLException
public boolean absolute(int row)
throws java.sql.SQLException
absolute in interface java.sql.ResultSetjava.sql.SQLException
public boolean getBoolean(int columnIndex)
throws java.sql.SQLException
getBoolean in interface java.sql.ResultSetjava.sql.SQLException
public boolean relative(int row)
throws java.sql.SQLException
relative in interface java.sql.ResultSetjava.sql.SQLException
public byte[] getBytes(int columnIndex)
throws java.sql.SQLException
getBytes in interface java.sql.ResultSetjava.sql.SQLException
public void updateByte(int columnIndex,
byte x)
throws java.sql.SQLException
updateByte in interface java.sql.ResultSetjava.sql.SQLException
public void updateDouble(int columnIndex,
double x)
throws java.sql.SQLException
updateDouble in interface java.sql.ResultSetjava.sql.SQLException
public void updateFloat(int columnIndex,
float x)
throws java.sql.SQLException
updateFloat in interface java.sql.ResultSetjava.sql.SQLException
public void updateInt(int columnIndex,
int x)
throws java.sql.SQLException
updateInt in interface java.sql.ResultSetjava.sql.SQLException
public void updateLong(int columnIndex,
long x)
throws java.sql.SQLException
updateLong in interface java.sql.ResultSetjava.sql.SQLException
public void updateShort(int columnIndex,
short x)
throws java.sql.SQLException
updateShort in interface java.sql.ResultSetjava.sql.SQLException
public void updateBoolean(int columnIndex,
boolean x)
throws java.sql.SQLException
updateBoolean in interface java.sql.ResultSetjava.sql.SQLException
public void updateBytes(int columnIndex,
byte[] x)
throws java.sql.SQLException
updateBytes in interface java.sql.ResultSetjava.sql.SQLException
public java.io.InputStream getAsciiStream(int columnIndex)
throws java.sql.SQLException
getAsciiStream in interface java.sql.ResultSetjava.sql.SQLException
public java.io.InputStream getBinaryStream(int columnIndex)
throws java.sql.SQLException
getBinaryStream in interface java.sql.ResultSetjava.sql.SQLException
public java.io.InputStream getUnicodeStream(int columnIndex)
throws java.sql.SQLException
getUnicodeStream in interface java.sql.ResultSetjava.sql.SQLException
public void updateAsciiStream(int columnIndex,
java.io.InputStream inputStream,
int length)
throws java.sql.SQLException
updateAsciiStream in interface java.sql.ResultSetjava.sql.SQLException
public void updateBinaryStream(int columnIndex,
java.io.InputStream inputStream,
int length)
throws java.sql.SQLException
updateBinaryStream in interface java.sql.ResultSetjava.sql.SQLException
public java.io.Reader getCharacterStream(int columnIndex)
throws java.sql.SQLException
getCharacterStream in interface java.sql.ResultSetjava.sql.SQLException
public void updateCharacterStream(int columnIndex,
java.io.Reader reader,
int length)
throws java.sql.SQLException
updateCharacterStream in interface java.sql.ResultSetjava.sql.SQLException
public java.lang.Object getObject(int columnIndex)
throws java.sql.SQLException
getObject in interface java.sql.ResultSetjava.sql.SQLException
public void updateObject(int columnIndex,
java.lang.Object x)
throws java.sql.SQLException
updateObject in interface java.sql.ResultSetjava.sql.SQLException
public void updateObject(int columnIndex,
java.lang.Object x,
int scale)
throws java.sql.SQLException
updateObject in interface java.sql.ResultSetjava.sql.SQLException
public java.lang.String getCursorName()
throws java.sql.SQLException
getCursorName in interface java.sql.ResultSetjava.sql.SQLException
public java.lang.String getString(int columnIndex)
throws java.sql.SQLException
getString in interface java.sql.ResultSetjava.sql.SQLException
public void updateString(int columnIndex,
java.lang.String x)
throws java.sql.SQLException
updateString in interface java.sql.ResultSetjava.sql.SQLException
public byte getByte(java.lang.String columnName)
throws java.sql.SQLException
getByte in interface java.sql.ResultSetjava.sql.SQLException
public double getDouble(java.lang.String columnName)
throws java.sql.SQLException
getDouble in interface java.sql.ResultSetjava.sql.SQLException
public float getFloat(java.lang.String columnName)
throws java.sql.SQLException
getFloat in interface java.sql.ResultSetjava.sql.SQLException
public int findColumn(java.lang.String columnName)
throws java.sql.SQLException
findColumn in interface java.sql.ResultSetjava.sql.SQLException
public int getInt(java.lang.String columnName)
throws java.sql.SQLException
getInt in interface java.sql.ResultSetjava.sql.SQLException
public long getLong(java.lang.String columnName)
throws java.sql.SQLException
getLong in interface java.sql.ResultSetjava.sql.SQLException
public short getShort(java.lang.String columnName)
throws java.sql.SQLException
getShort in interface java.sql.ResultSetjava.sql.SQLException
public void updateNull(java.lang.String columnName)
throws java.sql.SQLException
updateNull in interface java.sql.ResultSetjava.sql.SQLException
public boolean getBoolean(java.lang.String columnName)
throws java.sql.SQLException
getBoolean in interface java.sql.ResultSetjava.sql.SQLException
public byte[] getBytes(java.lang.String columnName)
throws java.sql.SQLException
getBytes in interface java.sql.ResultSetjava.sql.SQLException
public void updateByte(java.lang.String columnName,
byte x)
throws java.sql.SQLException
updateByte in interface java.sql.ResultSetjava.sql.SQLException
public void updateDouble(java.lang.String columnName,
double x)
throws java.sql.SQLException
updateDouble in interface java.sql.ResultSetjava.sql.SQLException
public void updateFloat(java.lang.String columnName,
float x)
throws java.sql.SQLException
updateFloat in interface java.sql.ResultSetjava.sql.SQLException
public void updateInt(java.lang.String columnName,
int x)
throws java.sql.SQLException
updateInt in interface java.sql.ResultSetjava.sql.SQLException
public void updateLong(java.lang.String columnName,
long x)
throws java.sql.SQLException
updateLong in interface java.sql.ResultSetjava.sql.SQLException
public void updateShort(java.lang.String columnName,
short x)
throws java.sql.SQLException
updateShort in interface java.sql.ResultSetjava.sql.SQLException
public void updateBoolean(java.lang.String columnName,
boolean x)
throws java.sql.SQLException
updateBoolean in interface java.sql.ResultSetjava.sql.SQLException
public void updateBytes(java.lang.String columnName,
byte[] x)
throws java.sql.SQLException
updateBytes in interface java.sql.ResultSetjava.sql.SQLException
public java.math.BigDecimal getBigDecimal(int columnIndex)
throws java.sql.SQLException
getBigDecimal in interface java.sql.ResultSetjava.sql.SQLException
public java.math.BigDecimal getBigDecimal(int columnIndex,
int scale)
throws java.sql.SQLException
getBigDecimal in interface java.sql.ResultSetjava.sql.SQLException
public void updateBigDecimal(int columnIndex,
java.math.BigDecimal x)
throws java.sql.SQLException
updateBigDecimal in interface java.sql.ResultSetjava.sql.SQLException
public java.net.URL getURL(int columnIndex)
throws java.sql.SQLException
getURL in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.Array getArray(int columnIndex)
throws java.sql.SQLException
getArray in interface java.sql.ResultSetjava.sql.SQLException
public void updateArray(int columnIndex,
java.sql.Array x)
throws java.sql.SQLException
updateArray in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.Blob getBlob(int columnIndex)
throws java.sql.SQLException
getBlob in interface java.sql.ResultSetjava.sql.SQLException
public void updateBlob(int columnIndex,
java.sql.Blob x)
throws java.sql.SQLException
updateBlob in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.Clob getClob(int columnIndex)
throws java.sql.SQLException
getClob in interface java.sql.ResultSetjava.sql.SQLException
public void updateClob(int columnIndex,
java.sql.Clob x)
throws java.sql.SQLException
updateClob in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.Date getDate(int columnIndex)
throws java.sql.SQLException
getDate in interface java.sql.ResultSetjava.sql.SQLException
public void updateDate(int columnIndex,
java.sql.Date x)
throws java.sql.SQLException
updateDate in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.Ref getRef(int columnIndex)
throws java.sql.SQLException
getRef in interface java.sql.ResultSetjava.sql.SQLException
public void updateRef(int columnIndex,
java.sql.Ref x)
throws java.sql.SQLException
updateRef in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.ResultSetMetaData getMetaData()
throws java.sql.SQLException
getMetaData in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.SQLWarning getWarnings()
throws java.sql.SQLException
getWarnings in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.Statement getStatement()
throws java.sql.SQLException
getStatement in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.Time getTime(int columnIndex)
throws java.sql.SQLException
getTime in interface java.sql.ResultSetjava.sql.SQLException
public void updateTime(int columnIndex,
java.sql.Time x)
throws java.sql.SQLException
updateTime in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.Timestamp getTimestamp(int columnIndex)
throws java.sql.SQLException
getTimestamp in interface java.sql.ResultSetjava.sql.SQLException
public void updateTimestamp(int columnIndex,
java.sql.Timestamp x)
throws java.sql.SQLException
updateTimestamp in interface java.sql.ResultSetjava.sql.SQLException
public java.io.InputStream getAsciiStream(java.lang.String columnName)
throws java.sql.SQLException
getAsciiStream in interface java.sql.ResultSetjava.sql.SQLException
public java.io.InputStream getBinaryStream(java.lang.String columnName)
throws java.sql.SQLException
getBinaryStream in interface java.sql.ResultSetjava.sql.SQLException
public java.io.InputStream getUnicodeStream(java.lang.String columnName)
throws java.sql.SQLException
getUnicodeStream in interface java.sql.ResultSetjava.sql.SQLException
public void updateAsciiStream(java.lang.String columnName,
java.io.InputStream x,
int length)
throws java.sql.SQLException
updateAsciiStream in interface java.sql.ResultSetjava.sql.SQLException
public void updateBinaryStream(java.lang.String columnName,
java.io.InputStream x,
int length)
throws java.sql.SQLException
updateBinaryStream in interface java.sql.ResultSetjava.sql.SQLException
public java.io.Reader getCharacterStream(java.lang.String columnName)
throws java.sql.SQLException
getCharacterStream in interface java.sql.ResultSetjava.sql.SQLException
public void updateCharacterStream(java.lang.String columnName,
java.io.Reader x,
int length)
throws java.sql.SQLException
updateCharacterStream in interface java.sql.ResultSetjava.sql.SQLException
public java.lang.Object getObject(java.lang.String columnName)
throws java.sql.SQLException
getObject in interface java.sql.ResultSetjava.sql.SQLException
public void updateObject(java.lang.String columnName,
java.lang.Object x)
throws java.sql.SQLException
updateObject in interface java.sql.ResultSetjava.sql.SQLException
public void updateObject(java.lang.String columnName,
java.lang.Object x,
int scale)
throws java.sql.SQLException
updateObject in interface java.sql.ResultSetjava.sql.SQLException
public java.lang.Object getObject(int columnIndex,
java.util.Map map)
throws java.sql.SQLException
getObject in interface java.sql.ResultSetjava.sql.SQLException
public java.lang.String getString(java.lang.String columnName)
throws java.sql.SQLException
getString in interface java.sql.ResultSetjava.sql.SQLException
public void updateString(java.lang.String columnName,
java.lang.String x)
throws java.sql.SQLException
updateString in interface java.sql.ResultSetjava.sql.SQLException
public java.math.BigDecimal getBigDecimal(java.lang.String columnName)
throws java.sql.SQLException
getBigDecimal in interface java.sql.ResultSetjava.sql.SQLException
public java.math.BigDecimal getBigDecimal(java.lang.String columnName,
int scale)
throws java.sql.SQLException
getBigDecimal in interface java.sql.ResultSetjava.sql.SQLException
public void updateBigDecimal(java.lang.String columnName,
java.math.BigDecimal x)
throws java.sql.SQLException
updateBigDecimal in interface java.sql.ResultSetjava.sql.SQLException
public java.net.URL getURL(java.lang.String columnName)
throws java.sql.SQLException
getURL in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.Array getArray(java.lang.String columnName)
throws java.sql.SQLException
getArray in interface java.sql.ResultSetjava.sql.SQLException
public void updateArray(java.lang.String columnName,
java.sql.Array x)
throws java.sql.SQLException
updateArray in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.Blob getBlob(java.lang.String columnName)
throws java.sql.SQLException
getBlob in interface java.sql.ResultSetjava.sql.SQLException
public void updateBlob(java.lang.String columnName,
java.sql.Blob x)
throws java.sql.SQLException
updateBlob in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.Clob getClob(java.lang.String columnName)
throws java.sql.SQLException
getClob in interface java.sql.ResultSetjava.sql.SQLException
public void updateClob(java.lang.String columnName,
java.sql.Clob x)
throws java.sql.SQLException
updateClob in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.Date getDate(java.lang.String columnName)
throws java.sql.SQLException
getDate in interface java.sql.ResultSetjava.sql.SQLException
public void updateDate(java.lang.String columnName,
java.sql.Date x)
throws java.sql.SQLException
updateDate in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.Date getDate(int columnIndex,
java.util.Calendar cal)
throws java.sql.SQLException
getDate in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.Ref getRef(java.lang.String columnName)
throws java.sql.SQLException
getRef in interface java.sql.ResultSetjava.sql.SQLException
public void updateRef(java.lang.String columnName,
java.sql.Ref x)
throws java.sql.SQLException
updateRef in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.Time getTime(java.lang.String columnName)
throws java.sql.SQLException
getTime in interface java.sql.ResultSetjava.sql.SQLException
public void updateTime(java.lang.String columnName,
java.sql.Time x)
throws java.sql.SQLException
updateTime in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.Time getTime(int columnIndex,
java.util.Calendar cal)
throws java.sql.SQLException
getTime in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.Timestamp getTimestamp(java.lang.String columnName)
throws java.sql.SQLException
getTimestamp in interface java.sql.ResultSetjava.sql.SQLException
public void updateTimestamp(java.lang.String columnName,
java.sql.Timestamp x)
throws java.sql.SQLException
updateTimestamp in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.Timestamp getTimestamp(int columnIndex,
java.util.Calendar cal)
throws java.sql.SQLException
getTimestamp in interface java.sql.ResultSetjava.sql.SQLException
public java.lang.Object getObject(java.lang.String columnName,
java.util.Map map)
throws java.sql.SQLException
getObject in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.Date getDate(java.lang.String columnName,
java.util.Calendar cal)
throws java.sql.SQLException
getDate in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.Time getTime(java.lang.String columnName,
java.util.Calendar cal)
throws java.sql.SQLException
getTime in interface java.sql.ResultSetjava.sql.SQLException
public java.sql.Timestamp getTimestamp(java.lang.String columnName,
java.util.Calendar cal)
throws java.sql.SQLException
getTimestamp in interface java.sql.ResultSetjava.sql.SQLException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.ParamInfo
This class is a descriptor for procedure and prepared statement parameters.
| Field Summary | |
(package private) CharsetInfo |
charsetInfo
Character set descriptor (if different from default) |
(package private) byte[] |
collation
TDS 8 Collation string. |
(package private) static int |
INPUT
Flag as an input parameter. |
(package private) boolean |
isOutput
Parameter is an output parameter |
(package private) boolean |
isRetVal
Parameter is used as SP return value |
(package private) boolean |
isSet
IN parameter has been set |
(package private) boolean |
isSetOut
OUT parameter value is set. |
(package private) boolean |
isUnicode
Parameter should be sent as unicode |
(package private) int |
jdbcType
JDBC type constant from java.sql.Types |
(package private) int |
length
Length of InputStream |
(package private) int |
markerPos
Parameter offset in target SQL statement |
(package private) java.lang.String |
name
Formal parameter name eg @P1 |
(package private) static int |
OUTPUT
Flag as an output parameter. |
(package private) java.lang.Object |
outValue
OUT Parameter value. |
(package private) int |
precision
Parameter decimal precision |
(package private) static int |
RETVAL
Flag as an return value parameter. |
(package private) int |
scale
Parameter decimal scale |
(package private) java.lang.String |
sqlType
SQL type name eg varchar(10) |
(package private) int |
tdsType
Internal TDS data type |
(package private) static int |
UNICODE
Flag as a unicode parameter. |
(package private) java.lang.Object |
value
Current parameter value |
| Constructor Summary | |
(package private) |
ParamInfo(ColInfo ci,
java.lang.String name,
java.lang.Object value,
int length)
Construct a parameter based on a result set column. |
(package private) |
ParamInfo(int pos,
boolean isUnicode)
Construct a parameter with parameter marker offset. |
(package private) |
ParamInfo(int jdbcType,
java.lang.Object value,
int flags)
Construct an initialised parameter with extra attributes. |
(package private) |
ParamInfo(java.lang.String name,
int pos,
boolean isRetVal,
boolean isUnicode)
Construct a parameter for statement caching. |
| Method Summary | |
(package private) void |
clearInValue()
Clear the IN parameter value and status. |
(package private) void |
clearOutValue()
Clear the OUT parameter value and status. |
java.lang.Object |
clone()
Creates a shallow copy of this ParamInfo instance. |
(package private) byte[] |
getBytes(java.lang.String charset)
Get the byte array value of the parameter. |
(package private) java.lang.Object |
getOutValue()
Get the output parameter value. |
(package private) java.lang.String |
getString(java.lang.String charset)
Get the string value of the parameter. |
private static java.lang.String |
loadFromReader(java.io.Reader in,
int length)
Create a String from a Reader stream. |
private static byte[] |
loadFromStream(java.io.InputStream in,
int length)
Load a byte array from an InputStream |
(package private) void |
setOutValue(java.lang.Object value)
Set the OUT parameter value. |
| Methods inherited from class java.lang.Object |
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
static final int INPUT
static final int OUTPUT
static final int RETVAL
static final int UNICODE
int tdsType
int jdbcType
java.lang.String name
java.lang.String sqlType
int markerPos
java.lang.Object value
int precision
int scale
int length
boolean isOutput
boolean isRetVal
boolean isSet
boolean isUnicode
byte[] collation
CharsetInfo charsetInfo
boolean isSetOut
java.lang.Object outValue
| Constructor Detail |
ParamInfo(int pos,
boolean isUnicode)
pos - the offset of the ? symbol in the target SQL stringisUnicode - true if the parameter is Unicode encoded
ParamInfo(java.lang.String name,
int pos,
boolean isRetVal,
boolean isUnicode)
name - the formal name of the parameterpos - the offset of the ? symbol in the parsed SQL stringisRetVal - true if the parameter is a return valueisUnicode - true if the parameter is Unicode encoded
ParamInfo(int jdbcType,
java.lang.Object value,
int flags)
jdbcType - the java.sql.Type constant describing this typevalue - the initial parameter valueflags - the additional attributes eg OUTPUT, RETVAL, UNICODE etc.ParamInfo(ColInfo ci, java.lang.String name, java.lang.Object value, int length)
ci - the column descriptorname - the name for this parameter or nullvalue - the column data valuelength - the column data length| Method Detail |
java.lang.Object getOutValue()
throws java.sql.SQLException
Object
java.sql.SQLException - if the parameter has not been setvoid setOutValue(java.lang.Object value)
value - The data value.void clearOutValue()
void clearInValue()
java.lang.String getString(java.lang.String charset)
throws java.io.IOException
String or null.
java.io.IOException
byte[] getBytes(java.lang.String charset)
throws java.io.IOException
byte[] or null.
java.io.IOException
private static byte[] loadFromStream(java.io.InputStream in,
int length)
throws java.io.IOException
in - The InputStream to read from.length - The length of the stream.
byte[].
java.io.IOException
private static java.lang.String loadFromReader(java.io.Reader in,
int length)
throws java.io.IOException
in - The Reader object with the data.length - Number of characters to read.
String.
java.io.IOExceptionpublic java.lang.Object clone()
ParamInfo instance. Used by
the PreparedStatement batching implementation to duplicate
parameters.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.ConnectionJDBC2
jTDS implementation of the java.sql.Connection interface.
Implementation notes:
| Field Summary | |
private java.lang.String |
appName
The application name. |
private boolean |
autoCommit
Default auto commit state. |
private TdsCore |
baseTds
The cored TDS protocol object. |
private int |
batchSize
The maximum size of a batch. |
private java.lang.String |
bindAddress
The local address to bind to when connecting to a database via TCP/IP. |
private java.io.File |
bufferDir
The directory to buffer data to |
private int |
bufferMaxMemory
The global buffer memory limit for all connections (in kilobytes). |
private int |
bufferMinPackets
The minimum number of packets per statement to buffer to memory. |
private TdsCore |
cachedTds
A cached TdsCore instance to reuse on new statements. |
private CharsetInfo |
charsetInfo
Java charset for encoding. |
private boolean |
charsetSpecified
True if user specifies an explicit charset. |
private boolean |
closed
True if this connection is closed. |
private byte[] |
collation
SQL Server 2000 collation. |
private static int |
connections
the number of currently open connections |
private java.lang.String |
currentDatabase
The current database name. |
private int |
cursorSequenceNo
Cursor unique ID number. |
private int |
databaseMajorVersion
The major version number eg 11. |
private int |
databaseMinorVersion
The minor version number eg 92. |
private java.lang.String |
databaseName
The requested database name. |
private java.lang.String |
databaseProductName
The database product name eg SQL SERVER. |
private java.lang.String |
databaseProductVersion
The product version eg 11.92. |
private java.lang.String |
domainName
The Windows Domain name. |
private java.lang.String |
instanceName
The SQL Server instance. |
private java.lang.String |
language
The server message language. |
private boolean |
lastUpdateCount
Only return the last update count. |
private long |
lobBuffer
The amount of LOB data to buffer in memory. |
private int |
loginTimeout
Login timeout value in seconds or 0. |
private java.lang.String |
macAddress
The client MAC Address. |
private int |
maxPrecision
Maximum decimal precision. |
private int |
maxStatements
The maximum number of statements to keep open. |
private SQLDiagnostic |
messages
Diagnostc messages for this connection. |
private Semaphore |
mutex
Mutual exclusion lock to control access to connection. |
private boolean |
namedPipe
Use named pipe IPC instead of TCP/IP sockets. |
private int |
netPacketSize
The initial network packet size. |
private int |
packetSize
User requested packet size. |
private java.lang.String |
password
The user password. |
private int |
portNumber
The server port number. |
private int |
prepareSql
Method for preparing SQL used in Prepared Statements. |
private static java.lang.Integer |
processId
The process ID to report to a server when connecting. |
private java.util.ArrayList |
procInTran
Procedures in this transaction. |
private java.lang.String |
progName
The program name. |
private boolean |
readOnly
True if this connection is read only. |
private int |
rowCount
Connection's current rowcount limit. |
private java.lang.String |
serverCharset
The server character set. |
private java.lang.String |
serverName
The server host name. |
private int |
serverType
The make of SQL Server (sybase/microsoft). |
private SharedSocket |
socket
The network TCP/IP socket. |
private boolean |
socketKeepAlive
True to enable socket keep alive. |
private int |
socketTimeout
Socket timeout value in seconds or 0. |
private int |
spSequenceNo
Stored procedure unique ID number. |
private static java.lang.String |
SQL_SERVER_65_CHARSET_QUERY
SQL query to determine the server charset on MS SQL Server 6.5. |
private static java.lang.String |
SQL_SERVER_INITIAL_SQL
SQL Server initial connection string. |
private java.lang.String |
ssl
SSL setting. |
private StatementCache |
statementCache
Statement cache. |
private java.util.ArrayList |
statements
List of statements associated with this connection. |
private static java.lang.String |
SYBASE_INITIAL_SQL
Sybase initial connection string. |
private static java.lang.String |
SYBASE_SERVER_CHARSET_QUERY
SQL query to determine the server charset on Sybase. |
private int |
sybaseInfo
Sybase capability mask. |
private boolean |
tcpNoDelay
TCP_NODELAY |
private int |
tdsVersion
The server protocol version. |
private int |
textSize
Connection's current maximum field size limit. |
static int |
TRANSACTION_SNAPSHOT
SQL Server custom transaction isolation level. |
private int |
transactionIsolation
Default transaction isolation level. |
private java.lang.String |
url
The orginal connection URL. |
private boolean |
useCursors
Use fast forward cursors for forward only result sets. |
private boolean |
useJCIFS
Force use of jCIFS library on Windows when connecting via named pipes. |
private boolean |
useLOBs
Map large types (IMAGE and TEXT/NTEXT) to LOBs by default. |
private boolean |
useMetadataCache
Use metadata cache for prepared statements. |
private boolean |
useNTLMv2
When doing NTLM authentication, send NTLMv2 response rather than regular response |
private java.lang.String |
user
The database user ID. |
private boolean |
useUnicode
Send parameters as unicode. |
private java.lang.String |
wsid
Workstation ID. |
private boolean |
xaEmulation
True if driver should emulate distributed transactions. |
private int |
xaState
Current emulated XA State eg start/end/prepare etc. |
private boolean |
xaTransaction
True if running distributed transaction. |
private java.lang.Object |
xid
Current XA Transaction ID. |
| Fields inherited from interface java.sql.Connection |
TRANSACTION_NONE, TRANSACTION_READ_COMMITTED, TRANSACTION_READ_UNCOMMITTED, TRANSACTION_REPEATABLE_READ, TRANSACTION_SERIALIZABLE |
| Constructor Summary | |
private |
ConnectionJDBC2()
Default constructor. |
(package private) |
ConnectionJDBC2(java.lang.String url,
java.util.Properties info)
Create a new database connection. |
| Method Summary | |
(package private) void |
addCachedProcedure(java.lang.String key,
ProcEntry proc)
Add a stored procedure to the cache. |
(package private) void |
addStatement(JtdsStatement statement)
Adds a statement object to the list maintained by the connection. |
(package private) void |
checkLocal(java.lang.String method)
Checks that this connection is in local transaction mode. |
(package private) void |
checkOpen()
Checks that the connection is still open. |
(package private) void |
clearSavepoints()
Releases all savepoints. |
void |
clearWarnings()
|
void |
close()
Releases this Connection object's database and JDBC
resources immediately instead of waiting for them to be automatically
released.
|
void |
commit()
|
private SharedSocket |
createNamedPipe(ConnectionJDBC2 connection)
Creates a SharedSocket object representing a connection to a named
pipe. |
java.sql.Statement |
createStatement()
|
java.sql.Statement |
createStatement(int type,
int concurrency)
|
java.sql.Statement |
createStatement(int type,
int concurrency,
int holdability)
|
private java.lang.String |
determineServerCharset()
Discovers the server charset for server versions that do not send ENVCHANGE packets on login ack, by executing a DB
vendor/version specific query.
|
(package private) void |
enlistConnection(byte[] oleTranID)
Enlists the current connection in a distributed transaction. |
protected void |
finalize()
Ensure all resources are released. |
(package private) java.lang.String |
getAppName()
Retrieves the application name for this connection. |
boolean |
getAutoCommit()
|
(package private) int |
getBatchSize()
Retrieves the batch size to be used internally. |
(package private) java.lang.String |
getBindAddress()
Retrieves the bind address for this connection. |
(package private) java.io.File |
getBufferDir()
Returns the directory where data should be buffered to. |
(package private) int |
getBufferMaxMemory()
Retrieves the maximum amount of memory in Kb to buffer for all connections. |
(package private) int |
getBufferMinPackets()
Retrieves the minimum number of packets to buffer per Statement for this connection. |
(package private) TdsCore |
getCachedTds()
Retrieves the cached TdsCore or null if
nothing is cached and resets the cache (sets it to null). |
java.lang.String |
getCatalog()
|
protected java.lang.String |
getCharset()
Retrieve the Java charset to use for encoding. |
protected CharsetInfo |
getCharsetInfo()
Retrieve the CharsetInfo instance used by this connection. |
(package private) byte[] |
getCollation()
Retrieve the SQL Server 2000 default collation. |
(package private) java.lang.String |
getCursorName()
Retrieves the next unique cursor name. |
int |
getDatabaseMajorVersion()
Retrieves the DBMS major version. |
int |
getDatabaseMinorVersion()
Retrieves the DBMS minor version. |
(package private) java.lang.String |
getDatabaseName()
Retrieves the database name for this connection. |
(package private) java.lang.String |
getDatabaseProductName()
Retrieves the DBMS product name. |
(package private) java.lang.String |
getDatabaseProductVersion()
Retrieves the DBMS product version. |
(package private) java.lang.String |
getDomainName()
Retrieves the domain name for this connection. |
int |
getHoldability()
|
(package private) java.lang.String |
getInstanceName()
Retrieves the instance name for this connection. |
(package private) boolean |
getLastUpdateCount()
Retrieves the status of the lastUpdateCount flag. |
(package private) long |
getLobBuffer()
Retrieves the LOB buffer size. |
(package private) int |
getLoginTimeout()
Retrieves the login timeout for this connection. |
(package private) java.lang.String |
getMacAddress()
Retrieves the MAC (ethernet) address for this connection. |
(package private) int |
getMaxPrecision()
Retrieves the maximum decimal precision. |
(package private) int |
getMaxStatements()
Retrieves the maximum statement cache size. |
java.sql.DatabaseMetaData |
getMetaData()
|
(package private) Semaphore |
getMutex()
Retrieves the connection mutex and acquires an exclusive lock on the network connection. |
(package private) boolean |
getNamedPipe()
Retrieves the named pipe setting for this connection. |
(package private) int |
getNetPacketSize()
Retrieves the network packet size. |
(package private) int |
getPacketSize()
Retrieves the packet size for this connection. |
(package private) java.lang.String |
getPassword()
Retrieves the password for this connection. |
(package private) int |
getPortNumber()
Retrieves the port number for this connection. |
(package private) int |
getPrepareSql()
Retrieves the Prepared SQL method. |
(package private) int |
getProcessId()
Retrieves the process ID to send to a server when a connection is established. |
(package private) java.lang.String |
getProcName()
Retrieves the next unique stored procedure name. |
(package private) java.lang.String |
getProgName()
Retrieves the program name for this connection. |
java.lang.String |
getRmHost()
Retrieves the host and port for this connection. |
(package private) int |
getRowCount()
Retrieves the current row count on this connection. |
(package private) java.lang.String |
getServerName()
Retrieves the server name for this connection. |
int |
getServerType()
Retrieves the server type. |
(package private) SharedSocket |
getSocket()
Retrive the shared socket. |
(package private) boolean |
getSocketKeepAlive()
Retrieves whether to enable socket keep alive. |
(package private) int |
getSocketTimeout()
Retrieves the socket timeout for this connection. |
protected boolean |
getSybaseInfo(int flag)
Retrieve the Sybase capability data. |
(package private) boolean |
getTcpNoDelay()
Retrieves the tcpNoDelay setting for this connection. |
(package private) int |
getTdsVersion()
Retrieve the TDS protocol version. |
int |
getTextSize()
Retrieves the current maximum textsize on this connection. |
int |
getTransactionIsolation()
|
java.util.Map |
getTypeMap()
|
(package private) java.lang.String |
getURL()
Retrieves the original connection URL. |
(package private) boolean |
getUseCursors()
Indicates whether fast forward only cursors should be used for forward only result sets. |
(package private) boolean |
getUseJCIFS()
Retrieves the useJCIFS setting for this connection. |
(package private) boolean |
getUseLOBs()
Indicates whether large types (IMAGE and TEXT/NTEXT) should be mapped by default to LOB types or String and byte[]
respectively. |
(package private) boolean |
getUseMetadataCache()
Retrieves the boolean indicating whether metadata caching is enabled. |
(package private) boolean |
getUseNTLMv2()
Indicates whether, when doing Windows authentication to an MS SQL server, NTLMv2 should be used. |
(package private) java.lang.String |
getUser()
Retrieves the user for this connection. |
protected boolean |
getUseUnicode()
Retrieve the sendParametersAsUnicode flag. |
java.sql.SQLWarning |
getWarnings()
|
(package private) java.lang.String |
getWsid()
Retrieves the workstation ID (WSID) for this connection. |
(package private) int |
getXaState()
Retrieves the XA state variable. |
(package private) java.lang.Object |
getXid()
Gets the XA transaction ID when running in emulation mode. |
(package private) boolean |
isCharsetSpecified()
Retrieves whether a specific charset was requested on creation. |
boolean |
isClosed()
|
boolean |
isReadOnly()
|
protected boolean |
isWideChar()
Retrieve the multibyte status of the current character set. |
(package private) boolean |
isXaEmulation()
Retrieves the XA Emulation flag. |
private void |
loadCharset(CharsetInfo ci,
java.lang.String ref)
Load the Java charset to match the server character set. |
private void |
loadCharset(java.lang.String charset)
Load the Java charset to match the server character set. |
java.lang.String |
nativeSQL(java.lang.String sql)
|
(package private) static void |
notImplemented(java.lang.String method)
Reports that user tried to call a method which has not been implemented. |
private static boolean |
parseBooleanProperty(java.util.Properties info,
java.lang.String key)
Parse a string property value into an boolean value. |
private static int |
parseIntegerProperty(java.util.Properties info,
java.lang.String key)
Parse a string property value into an integer value. |
private static long |
parseLongProperty(java.util.Properties info,
java.lang.String key)
Parse a string property value into a long value. |
java.sql.CallableStatement |
prepareCall(java.lang.String sql)
|
java.sql.CallableStatement |
prepareCall(java.lang.String sql,
int type,
int concurrency)
|
java.sql.CallableStatement |
prepareCall(java.lang.String sql,
int type,
int concurrency,
int holdability)
|
(package private) java.lang.String |
prepareSQL(JtdsPreparedStatement pstmt,
java.lang.String sql,
ParamInfo[] params,
boolean returnKeys,
boolean cursorNeeded)
Try to convert the SQL statement into a statement prepare. |
java.sql.PreparedStatement |
prepareStatement(java.lang.String sql)
|
java.sql.PreparedStatement |
prepareStatement(java.lang.String sql,
int autoGeneratedKeys)
|
java.sql.PreparedStatement |
prepareStatement(java.lang.String sql,
int[] columnIndexes)
|
java.sql.PreparedStatement |
prepareStatement(java.lang.String sql,
int type,
int concurrency)
|
java.sql.PreparedStatement |
prepareStatement(java.lang.String sql,
int type,
int concurrency,
int holdability)
|
java.sql.PreparedStatement |
prepareStatement(java.lang.String sql,
java.lang.String[] columnNames)
|
void |
releaseSavepoint(java.sql.Savepoint savepoint)
|
(package private) void |
releaseTds(TdsCore tds)
Releases (either closes or caches) a TdsCore. |
(package private) void |
removeCachedProcedure(java.lang.String key)
Remove a stored procedure from the cache. |
(package private) void |
removeStatement(JtdsStatement statement)
Removes a statement object from the list maintained by the connection and cleans up the statement cache if necessary. |
void |
rollback()
|
void |
rollback(java.sql.Savepoint savepoint)
|
(package private) byte[][] |
sendXaPacket(int[] args,
byte[] data)
Invokes the xp_jtdsxa extended stored procedure on the
server.
|
void |
setAutoCommit(boolean autoCommit)
|
void |
setCatalog(java.lang.String catalog)
|
(package private) void |
setClosed()
Forces the closed status on the statement if an I/O error has occurred. |
(package private) void |
setCollation(byte[] collation)
Set the default collation for this connection. |
protected void |
setDatabase(java.lang.String newDb,
java.lang.String oldDb)
Called by the protcol to change the current database context. |
protected void |
setDBServerInfo(java.lang.String databaseProductName,
int databaseMajorVersion,
int databaseMinorVersion,
int buildNumber)
Update the connection instance with information about the server. |
void |
setHoldability(int holdability)
|
(package private) void |
setNetPacketSize(int size)
Sets the network packet size. |
void |
setReadOnly(boolean readOnly)
|
(package private) void |
setRowCount(int count)
Sets the current row count on this connection. |
java.sql.Savepoint |
setSavepoint()
|
java.sql.Savepoint |
setSavepoint(java.lang.String name)
|
protected void |
setServerCharset(java.lang.String charset)
Called by the protocol to change the current character set. |
protected void |
setSybaseInfo(int mask)
Set the Sybase capability data. |
void |
setTextSize(int textSize)
Sets the current maximum textsize on this connection. |
void |
setTransactionIsolation(int level)
|
void |
setTypeMap(java.util.Map map)
|
(package private) void |
setXaState(int value)
Sets the XA state variable. |
(package private) void |
setXid(java.lang.Object xid)
Sets the XA transaction ID when running in emulation mode. |
protected void |
unpackProperties(java.util.Properties info)
Transfers the properties to the local instance variables. |
| Methods inherited from class java.lang.Object |
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private static final java.lang.String SYBASE_SERVER_CHARSET_QUERY
private static final java.lang.String SQL_SERVER_65_CHARSET_QUERY
private static final java.lang.String SYBASE_INITIAL_SQL
private static final java.lang.String SQL_SERVER_INITIAL_SQL
SELECT @@MAX_PRECISION query to retrieve
the maximum precision for DECIMAL/NUMERIC data.
public static final int TRANSACTION_SNAPSHOT
private final java.lang.String url
private java.lang.String serverName
private int portNumber
private int serverType
private java.lang.String instanceName
private java.lang.String databaseName
private java.lang.String currentDatabase
private java.lang.String domainName
private java.lang.String user
private java.lang.String password
private java.lang.String serverCharset
private java.lang.String appName
private java.lang.String progName
private java.lang.String wsid
private java.lang.String language
private java.lang.String macAddress
private int tdsVersion
private final SharedSocket socket
private final TdsCore baseTds
private int netPacketSize
private int packetSize
private byte[] collation
private boolean charsetSpecified
private java.lang.String databaseProductName
private java.lang.String databaseProductVersion
private int databaseMajorVersion
private int databaseMinorVersion
private boolean closed
private boolean readOnly
private final java.util.ArrayList statements
private int transactionIsolation
private boolean autoCommit
private final SQLDiagnostic messages
private int rowCount
private int textSize
private int maxPrecision
private int spSequenceNo
private int cursorSequenceNo
private final java.util.ArrayList procInTran
private CharsetInfo charsetInfo
private int prepareSql
private long lobBuffer
private int maxStatements
private StatementCache statementCache
private boolean useUnicode
private boolean namedPipe
private boolean lastUpdateCount
private boolean tcpNoDelay
private int loginTimeout
private int sybaseInfo
private boolean xaTransaction
private int xaState
private java.lang.Object xid
private boolean xaEmulation
private final Semaphore mutex
private int socketTimeout
private boolean socketKeepAlive
private static java.lang.Integer processId
private java.lang.String ssl
private int batchSize
private boolean useMetadataCache
private boolean useCursors
private java.io.File bufferDir
private int bufferMaxMemory
private int bufferMinPackets
private boolean useLOBs
private TdsCore cachedTds
TdsCore instance to reuse on new statements.
private java.lang.String bindAddress
private boolean useJCIFS
private boolean useNTLMv2
private static int connections
| Constructor Detail |
private ConnectionJDBC2()
ConnectionJDBC2(java.lang.String url,
java.util.Properties info)
throws java.sql.SQLException
url - The connection URL starting jdbc:jtds:.info - The additional connection properties.
java.sql.SQLException| Method Detail |
protected void finalize()
throws java.lang.Throwable
java.lang.Throwableprivate SharedSocket createNamedPipe(ConnectionJDBC2 connection) throws java.io.IOException
SharedSocket object representing a connection to a named
pipe. If the os.name system property starts with "Windows"
(case-insensitive) and the useJCIFS parameter is
false, a SharedLocalNamedPipe object is created.
Else a SharedNamedPipe is created which uses
jCIFS to provide a pure-Java
implementation of Windows named pipes.
This method will retry for loginTimeout seconds to create a
named pipe if an IOException continues to be thrown stating,
"All pipe instances are busy". If loginTimeout is set to
zero (e.g., not set), a default of 20 seconds will be used.
connection - the connection object
java.io.IOException - on error; if an IOException is thrown with
a message stating "All pipe instances are busy", then the method timed out
after loginTimeout milliseconds attempting to create a named pipe.SharedSocket getSocket()
SharedSocket object.int getTdsVersion()
int.java.lang.String getProcName()
Notes:
prepareSQL(net.sourceforge.jtds.jdbc.JtdsPreparedStatement, java.lang.String, net.sourceforge.jtds.jdbc.ParamInfo[], boolean, boolean) method.
Stringjava.lang.String getCursorName()
Stringjava.lang.String prepareSQL(JtdsPreparedStatement pstmt, java.lang.String sql, ParamInfo[] params, boolean returnKeys, boolean cursorNeeded) throws java.sql.SQLException
Synchronized because it accesses the procedure cache and the
baseTds, but the method call also needs to made in a
synchronized (connection) block together with the execution
(if the prepared statement is actually executed) to ensure the
transaction isn't rolled back between this method call and the actual
execution.
pstmt - the target prepared statementsql - the SQL statement to prepareparams - the parametersreturnKeys - indicates whether the statement will return
generated keyscursorNeeded - indicates whether a cursor prepare is needed
String or null if the
SQL cannot be prepared
java.sql.SQLException
void addCachedProcedure(java.lang.String key,
ProcEntry proc)
Not explicitly synchronized because it's only called by synchronized methods.
key - The signature of the procedure to cache.proc - The stored procedure descriptor.void removeCachedProcedure(java.lang.String key)
Not explicitly synchronized because it's only called by synchronized methods.
key - The signature of the procedure to remove from the cache.int getMaxStatements()
public int getServerType()
int where 1 == SQLSERVER and
2 == SYBASE.void setNetPacketSize(int size)
size - the new packet sizeint getNetPacketSize()
intint getRowCount()
intvoid setRowCount(int count)
count - the new row countpublic int getTextSize()
intpublic void setTextSize(int textSize)
textSize - the new maximum textsizeboolean getLastUpdateCount()
booleanint getMaxPrecision()
intlong getLobBuffer()
longint getPrepareSql()
int getBatchSize()
intboolean getUseMetadataCache()
true if metadata caching is enabled,
false if caching is disabledboolean getUseCursors()
true if fast forward cursors are requestedboolean getUseLOBs()
String and byte[]
respectively.
true if the default mapping should be to LOBs,
false otherwiseboolean getUseNTLMv2()
java.lang.String getAppName()
java.lang.String getBindAddress()
java.io.File getBufferDir()
int getBufferMaxMemory()
int getBufferMinPackets()
Statement for this connection.
Statementjava.lang.String getDatabaseName()
java.lang.String getDomainName()
java.lang.String getInstanceName()
int getLoginTimeout()
int getSocketTimeout()
boolean getSocketKeepAlive()
true if the socket keep alive is enabledint getProcessId()
java.lang.String getMacAddress()
boolean getNamedPipe()
int getPacketSize()
java.lang.String getPassword()
int getPortNumber()
java.lang.String getProgName()
java.lang.String getServerName()
boolean getTcpNoDelay()
boolean getUseJCIFS()
java.lang.String getUser()
java.lang.String getWsid()
protected void unpackProperties(java.util.Properties info)
throws java.sql.SQLException
info - The connection properties Object.
java.sql.SQLException - If an invalid property value is found.
private static boolean parseBooleanProperty(java.util.Properties info,
java.lang.String key)
throws java.sql.SQLException
info - The connection properties object.key - The message key used to retrieve the property name.
java.sql.SQLException - If the property value can't be parsed.
private static int parseIntegerProperty(java.util.Properties info,
java.lang.String key)
throws java.sql.SQLException
info - The connection properties object.key - The message key used to retrieve the property name.
java.sql.SQLException - If the property value can't be parsed.
private static long parseLongProperty(java.util.Properties info,
java.lang.String key)
throws java.sql.SQLException
info - The connection properties object.key - The message key used to retrieve the property name.
java.sql.SQLException - If the property value can't be parsed.protected java.lang.String getCharset()
Stringprotected boolean isWideChar()
boolean true if a multi byte character setprotected CharsetInfo getCharsetInfo()
CharsetInfo instance used by this connection.
CharsetInfo for this connectionprotected boolean getUseUnicode()
boolean true if parameters should be sent as unicode.protected boolean getSybaseInfo(int flag)
int.protected void setSybaseInfo(int mask)
mask - The capability bit mask.
protected void setServerCharset(java.lang.String charset)
throws java.sql.SQLException
charset - the server character set name
java.sql.SQLException
private void loadCharset(java.lang.String charset)
throws java.sql.SQLException
charset - the server character set
java.sql.SQLExceptionprivate void loadCharset(CharsetInfo ci, java.lang.String ref) throws java.sql.SQLException
ci - the CharsetInfo to load
java.sql.SQLException
private java.lang.String determineServerCharset()
throws java.sql.SQLException
ENVCHANGE packets on login ack, by executing a DB
vendor/version specific query.
Will throw an SQLException if used on SQL Server 7.0 or
2000; the idea is that the charset should already be determined from
ENVCHANGE packets for these DB servers.
Should only be called from the constructor.
java.sql.SQLException - if an error condition occurs
void setCollation(byte[] collation)
throws java.sql.SQLException
Set by a SQL Server 2000 environment change packet. The collation consists of the following fields:
collation - The new collation.
java.sql.SQLExceptionbyte[] getCollation()
byte[5].boolean isCharsetSpecified()
protected void setDatabase(java.lang.String newDb,
java.lang.String oldDb)
throws java.sql.SQLException
newDb - The new database selected on the server.oldDb - The old database as known by the server.
java.sql.SQLException
protected void setDBServerInfo(java.lang.String databaseProductName,
int databaseMajorVersion,
int databaseMinorVersion,
int buildNumber)
databaseProductName - The server name eg SQL Server.databaseMajorVersion - The major version eg 11databaseMinorVersion - The minor version eg 92buildNumber - The server build number.void removeStatement(JtdsStatement statement) throws java.sql.SQLException
Synchronized because it accesses the statement list, the statement cache
and the baseTds.
statement - the statement to remove
java.sql.SQLExceptionvoid addStatement(JtdsStatement statement)
statement - statement to add
void checkOpen()
throws java.sql.SQLException
java.sql.SQLException - if the connection is closed
void checkLocal(java.lang.String method)
throws java.sql.SQLException
method - the method name being tested
java.sql.SQLException - if in XA distributed transaction mode
static void notImplemented(java.lang.String method)
throws java.sql.SQLException
method - the method name to report in the error message
java.sql.SQLException - always, with the not implemented messagepublic int getDatabaseMajorVersion()
intpublic int getDatabaseMinorVersion()
intjava.lang.String getDatabaseProductName()
Stringjava.lang.String getDatabaseProductVersion()
Stringjava.lang.String getURL()
Stringpublic java.lang.String getRmHost()
Used to identify same resource manager in XA transactions.
Stringvoid setClosed()
byte[][] sendXaPacket(int[] args,
byte[] data)
throws java.sql.SQLException
xp_jtdsxa extended stored procedure on the
server.
Synchronized because it accesses the baseTds.
args - the arguments eg cmd, rmid, flags etc.data - option byte data eg open string xid etc.
java.sql.SQLException - if an error condition occurs
void enlistConnection(byte[] oleTranID)
throws java.sql.SQLException
oleTranID - the OLE transaction cookie or null to delist
java.sql.SQLException - if an error condition occursvoid setXid(java.lang.Object xid)
xid - the XA Transaction IDjava.lang.Object getXid()
Objectvoid setXaState(int value)
value - the XA state valueint getXaState()
intboolean isXaEmulation()
Semaphore getMutex()
Semaphorevoid releaseTds(TdsCore tds) throws java.sql.SQLException
TdsCore.
tds - the TdsCore instance to release
java.sql.SQLException - if an error occurs while closing or cleaning upTdsCore getCachedTds()
TdsCore or null if
nothing is cached and resets the cache (sets it to null).
cachedTds
public int getHoldability()
throws java.sql.SQLException
getHoldability in interface java.sql.Connectionjava.sql.SQLException
public int getTransactionIsolation()
throws java.sql.SQLException
getTransactionIsolation in interface java.sql.Connectionjava.sql.SQLException
public void clearWarnings()
throws java.sql.SQLException
clearWarnings in interface java.sql.Connectionjava.sql.SQLException
public void close()
throws java.sql.SQLException
Connection object's database and JDBC
resources immediately instead of waiting for them to be automatically
released.
Calling the method close on a Connection object that is
already closed is a no-op.
Note: A Connection object is automatically closed
when it is garbage collected. Certain fatal errors also close a
Connection object.
Synchronized because it accesses the statement list and the
baseTds.
close in interface java.sql.Connectionjava.sql.SQLException - if a database access error occurs
public void commit()
throws java.sql.SQLException
commit in interface java.sql.Connectionjava.sql.SQLException
public void rollback()
throws java.sql.SQLException
rollback in interface java.sql.Connectionjava.sql.SQLException
public boolean getAutoCommit()
throws java.sql.SQLException
getAutoCommit in interface java.sql.Connectionjava.sql.SQLException
public boolean isClosed()
throws java.sql.SQLException
isClosed in interface java.sql.Connectionjava.sql.SQLException
public boolean isReadOnly()
throws java.sql.SQLException
isReadOnly in interface java.sql.Connectionjava.sql.SQLException
public void setHoldability(int holdability)
throws java.sql.SQLException
setHoldability in interface java.sql.Connectionjava.sql.SQLException
public void setTransactionIsolation(int level)
throws java.sql.SQLException
setTransactionIsolation in interface java.sql.Connectionjava.sql.SQLException
public void setAutoCommit(boolean autoCommit)
throws java.sql.SQLException
setAutoCommit in interface java.sql.Connectionjava.sql.SQLException
public void setReadOnly(boolean readOnly)
throws java.sql.SQLException
setReadOnly in interface java.sql.Connectionjava.sql.SQLException
public java.lang.String getCatalog()
throws java.sql.SQLException
getCatalog in interface java.sql.Connectionjava.sql.SQLException
public void setCatalog(java.lang.String catalog)
throws java.sql.SQLException
setCatalog in interface java.sql.Connectionjava.sql.SQLException
public java.sql.DatabaseMetaData getMetaData()
throws java.sql.SQLException
getMetaData in interface java.sql.Connectionjava.sql.SQLException
public java.sql.SQLWarning getWarnings()
throws java.sql.SQLException
getWarnings in interface java.sql.Connectionjava.sql.SQLException
public java.sql.Savepoint setSavepoint()
throws java.sql.SQLException
setSavepoint in interface java.sql.Connectionjava.sql.SQLException
public void releaseSavepoint(java.sql.Savepoint savepoint)
throws java.sql.SQLException
releaseSavepoint in interface java.sql.Connectionjava.sql.SQLException
public void rollback(java.sql.Savepoint savepoint)
throws java.sql.SQLException
rollback in interface java.sql.Connectionjava.sql.SQLException
public java.sql.Statement createStatement()
throws java.sql.SQLException
createStatement in interface java.sql.Connectionjava.sql.SQLException
public java.sql.Statement createStatement(int type,
int concurrency)
throws java.sql.SQLException
createStatement in interface java.sql.Connectionjava.sql.SQLException
public java.sql.Statement createStatement(int type,
int concurrency,
int holdability)
throws java.sql.SQLException
createStatement in interface java.sql.Connectionjava.sql.SQLException
public java.util.Map getTypeMap()
throws java.sql.SQLException
getTypeMap in interface java.sql.Connectionjava.sql.SQLException
public void setTypeMap(java.util.Map map)
throws java.sql.SQLException
setTypeMap in interface java.sql.Connectionjava.sql.SQLException
public java.lang.String nativeSQL(java.lang.String sql)
throws java.sql.SQLException
nativeSQL in interface java.sql.Connectionjava.sql.SQLException
public java.sql.CallableStatement prepareCall(java.lang.String sql)
throws java.sql.SQLException
prepareCall in interface java.sql.Connectionjava.sql.SQLException
public java.sql.CallableStatement prepareCall(java.lang.String sql,
int type,
int concurrency)
throws java.sql.SQLException
prepareCall in interface java.sql.Connectionjava.sql.SQLException
public java.sql.CallableStatement prepareCall(java.lang.String sql,
int type,
int concurrency,
int holdability)
throws java.sql.SQLException
prepareCall in interface java.sql.Connectionjava.sql.SQLException
public java.sql.PreparedStatement prepareStatement(java.lang.String sql)
throws java.sql.SQLException
prepareStatement in interface java.sql.Connectionjava.sql.SQLException
public java.sql.PreparedStatement prepareStatement(java.lang.String sql,
int autoGeneratedKeys)
throws java.sql.SQLException
prepareStatement in interface java.sql.Connectionjava.sql.SQLException
public java.sql.PreparedStatement prepareStatement(java.lang.String sql,
int type,
int concurrency)
throws java.sql.SQLException
prepareStatement in interface java.sql.Connectionjava.sql.SQLException
public java.sql.PreparedStatement prepareStatement(java.lang.String sql,
int type,
int concurrency,
int holdability)
throws java.sql.SQLException
prepareStatement in interface java.sql.Connectionjava.sql.SQLException
public java.sql.PreparedStatement prepareStatement(java.lang.String sql,
int[] columnIndexes)
throws java.sql.SQLException
prepareStatement in interface java.sql.Connectionjava.sql.SQLException
public java.sql.Savepoint setSavepoint(java.lang.String name)
throws java.sql.SQLException
setSavepoint in interface java.sql.Connectionjava.sql.SQLException
public java.sql.PreparedStatement prepareStatement(java.lang.String sql,
java.lang.String[] columnNames)
throws java.sql.SQLException
prepareStatement in interface java.sql.Connectionjava.sql.SQLExceptionvoid clearSavepoints()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.BlobImpl
An in-memory or disk based representation of binary data.
| Field Summary | |
private BlobBuffer |
blobBuffer
The underlying BlobBuffer. |
private static byte[] |
EMPTY_BLOB
0 length byte[] as initial value for empty
Blobs. |
| Constructor Summary | |
(package private) |
BlobImpl(ConnectionJDBC2 connection)
Constructs a new empty Blob instance. |
(package private) |
BlobImpl(ConnectionJDBC2 connection,
byte[] bytes)
Constructs a new Blob instance initialized with data. |
| Method Summary | |
java.io.InputStream |
getBinaryStream()
|
byte[] |
getBytes(long pos,
int length)
|
long |
length()
|
long |
position(java.sql.Blob pattern,
long start)
|
long |
position(byte[] pattern,
long start)
|
java.io.OutputStream |
setBinaryStream(long pos)
|
int |
setBytes(long pos,
byte[] bytes)
|
int |
setBytes(long pos,
byte[] bytes,
int offset,
int len)
|
void |
truncate(long len)
|
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private static final byte[] EMPTY_BLOB
byte[] as initial value for empty
Blobs.
private final BlobBuffer blobBuffer
BlobBuffer.
| Constructor Detail |
BlobImpl(ConnectionJDBC2 connection)
Blob instance.
connection - a reference to the parent connection objectBlobImpl(ConnectionJDBC2 connection, byte[] bytes)
Blob instance initialized with data.
connection - a reference to the parent connection objectbytes - the blob object to encapsulate| Method Detail |
public java.io.InputStream getBinaryStream()
throws java.sql.SQLException
getBinaryStream in interface java.sql.Blobjava.sql.SQLException
public byte[] getBytes(long pos,
int length)
throws java.sql.SQLException
getBytes in interface java.sql.Blobjava.sql.SQLException
public long length()
throws java.sql.SQLException
length in interface java.sql.Blobjava.sql.SQLException
public long position(byte[] pattern,
long start)
throws java.sql.SQLException
position in interface java.sql.Blobjava.sql.SQLException
public long position(java.sql.Blob pattern,
long start)
throws java.sql.SQLException
position in interface java.sql.Blobjava.sql.SQLException
public java.io.OutputStream setBinaryStream(long pos)
throws java.sql.SQLException
setBinaryStream in interface java.sql.Blobjava.sql.SQLException
public int setBytes(long pos,
byte[] bytes)
throws java.sql.SQLException
setBytes in interface java.sql.Blobjava.sql.SQLException
public int setBytes(long pos,
byte[] bytes,
int offset,
int len)
throws java.sql.SQLException
setBytes in interface java.sql.Blobjava.sql.SQLException
public void truncate(long len)
throws java.sql.SQLException
truncate in interface java.sql.Blobjava.sql.SQLException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.ConnectionJDBC2
net.sourceforge.jtds.jdbc.ConnectionJDBC3
Implements JDBC 3.0 specific functionality. Separated from ConnectionJDBC2 in order to allow the same classes to run under both J2SE 1.3
(ConnectionJDBC2)and 1.4 (ConnectionJDBC3).
| Field Summary | |
private int |
savepointId
Counter for generating unique savepoint identifiers |
private java.util.Map |
savepointProcInTran
Maps each savepoint to a list of tmep procedures created since the savepoint |
private java.util.ArrayList |
savepoints
The list of savepoints. |
| Fields inherited from class net.sourceforge.jtds.jdbc.ConnectionJDBC2 |
TRANSACTION_SNAPSHOT |
| Fields inherited from interface java.sql.Connection |
TRANSACTION_NONE, TRANSACTION_READ_COMMITTED, TRANSACTION_READ_UNCOMMITTED, TRANSACTION_REPEATABLE_READ, TRANSACTION_SERIALIZABLE |
| Constructor Summary | |
(package private) |
ConnectionJDBC3(java.lang.String url,
java.util.Properties props)
Create a new database connection. |
| Method Summary | |
(package private) void |
addCachedProcedure(java.lang.String key)
Add a stored procedure to the savepoint cache. |
(package private) void |
addCachedProcedure(java.lang.String key,
ProcEntry proc)
Add a stored procedure to the cache. |
(package private) void |
clearSavepoints()
Releases all savepoints. |
private int |
getNextSavepointId()
Returns the next savepoint identifier. |
void |
releaseSavepoint(java.sql.Savepoint savepoint)
|
void |
rollback(java.sql.Savepoint savepoint)
|
java.sql.Savepoint |
setSavepoint()
|
private void |
setSavepoint(SavepointImpl savepoint)
Add a savepoint to the list maintained by this connection. |
java.sql.Savepoint |
setSavepoint(java.lang.String name)
|
| Methods inherited from class java.lang.Object |
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private java.util.ArrayList savepoints
private java.util.Map savepointProcInTran
private int savepointId
| Constructor Detail |
ConnectionJDBC3(java.lang.String url,
java.util.Properties props)
throws java.sql.SQLException
url - The connection URL starting jdbc:jtds:.props - The additional connection properties.
java.sql.SQLException| Method Detail |
private void setSavepoint(SavepointImpl savepoint) throws java.sql.SQLException
savepoint - The savepoint object to add.
java.sql.SQLExceptionvoid clearSavepoints()
clearSavepoints in class ConnectionJDBC2
public void releaseSavepoint(java.sql.Savepoint savepoint)
throws java.sql.SQLException
releaseSavepoint in interface java.sql.ConnectionreleaseSavepoint in class ConnectionJDBC2java.sql.SQLException
public void rollback(java.sql.Savepoint savepoint)
throws java.sql.SQLException
rollback in interface java.sql.Connectionrollback in class ConnectionJDBC2java.sql.SQLException
public java.sql.Savepoint setSavepoint()
throws java.sql.SQLException
setSavepoint in interface java.sql.ConnectionsetSavepoint in class ConnectionJDBC2java.sql.SQLException
public java.sql.Savepoint setSavepoint(java.lang.String name)
throws java.sql.SQLException
setSavepoint in interface java.sql.ConnectionsetSavepoint in class ConnectionJDBC2java.sql.SQLExceptionprivate int getNextSavepointId()
void addCachedProcedure(java.lang.String key,
ProcEntry proc)
addCachedProcedure in class ConnectionJDBC2key - The signature of the procedure to cache.proc - The stored procedure descriptor.void addCachedProcedure(java.lang.String key)
key - The signature of the procedure to cache.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.SavepointImpl
Savepoint implementation class.
| Field Summary | |
private int |
id
|
private java.lang.String |
name
|
| Constructor Summary | |
(package private) |
SavepointImpl(int id)
Constructs a savepoint with a specific identifier. |
(package private) |
SavepointImpl(int id,
java.lang.String name)
Constructs a savepoint with a specific identifier and name. |
| Method Summary | |
(package private) int |
getId()
Returns the savepoint id. |
int |
getSavepointId()
|
java.lang.String |
getSavepointName()
|
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private final int id
private final java.lang.String name
| Constructor Detail |
SavepointImpl(int id)
id - a savepoint identifier
SavepointImpl(int id,
java.lang.String name)
id - a savepoint identifiername - the savepoint name| Method Detail |
public int getSavepointId()
throws java.sql.SQLException
getSavepointId in interface java.sql.Savepointjava.sql.SQLException
public java.lang.String getSavepointName()
throws java.sql.SQLException
getSavepointName in interface java.sql.Savepointjava.sql.SQLExceptionint getId()
getSavepointId().
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.DefaultProperties
Container for default property constants.
This class also provides static utility methods forProperties and Settings objects.
To add new properties to the jTDS driver, do the following:
prop.foo and prop.desc.foo
properties to Messages.properties.static final default field to DefaultProperties.addDefaultProperties(java.util.Properties) to set the default.Driver.createChoicesMap() and
DriverUnitTest.test_getPropertyInfo_Choices() if the property
has a specific set of inputs, e.g., "true" and "false", or "1" and "2".Driver.createRequiredTrueMap() and
DriverUnitTest.test_getPropertyInfo_Required() if the property
is required.DefaultPropertiesTestLibrary for the new
property.
| Field Summary | |
static java.lang.String |
APP_NAME
Default appName property. |
static java.lang.String |
BATCH_SIZE_SQLSERVER
Default batchSize property for SQL Server. |
static java.lang.String |
BATCH_SIZE_SYBASE
Default batchSize property for Sybase. |
private static java.util.HashMap |
batchSizeDefaults
Default max batch size based on server type |
static java.lang.String |
BIND_ADDRESS
Default bindAddress property. |
static java.lang.String |
BUFFER_DIR
Default tmpDir property. |
static java.lang.String |
BUFFER_MAX_MEMORY
Default bufferMaxMemory property. |
static java.lang.String |
BUFFER_MIN_PACKETS
Default bufferMinPackets property. |
static java.lang.String |
CACHEMETA
Default cacheMetaData property. |
static java.lang.String |
CHARSET
Default charset property. |
static java.lang.String |
DATABASE_NAME
Default databaseName property. |
static java.lang.String |
DOMAIN
Default domain property. |
static java.lang.String |
INSTANCE
Default instance property. |
static java.lang.String |
LANGUAGE
Default language property. |
static java.lang.String |
LAST_UPDATE_COUNT
Default lastUpdateCount property. |
static java.lang.String |
LOB_BUFFER_SIZE
Default lobBufferSize property. |
static java.lang.String |
LOGFILE
Default logfile property. |
static java.lang.String |
LOGIN_TIMEOUT
Default loginTimeout property. |
static java.lang.String |
MAC_ADDRESS
Default macAddress property. |
static java.lang.String |
MAX_STATEMENTS
Default maxStatements property. |
static java.lang.String |
NAMED_PIPE
Default namedPipe property. |
static java.lang.String |
NAMED_PIPE_PATH_SQLSERVER
Default namedPipePath property for SQL Server. |
static java.lang.String |
NAMED_PIPE_PATH_SYBASE
Default namedPipePath property for Sybase. |
static java.lang.String |
PACKET_SIZE_42
Default packetSize property for TDS 4.2. |
static java.lang.String |
PACKET_SIZE_50
Default packetSize property for TDS 5.0. |
static java.lang.String |
PACKET_SIZE_70_80
Default packetSize property for TDS 7.0 and TDS 8.0. |
private static java.util.HashMap |
packetSizeDefaults
Default packet size based on TDS version |
static java.lang.String |
PASSWORD
Default password property. |
static java.lang.String |
PORT_NUMBER_SQLSERVER
Default portNumber property for SQL Server. |
static java.lang.String |
PORT_NUMBER_SYBASE
Default portNumber property for Sybase. |
private static java.util.HashMap |
portNumberDefaults
Default port number based on server type |
static java.lang.String |
PREPARE_SQLSERVER
Default prepareSql property for SQL Server. |
static java.lang.String |
PREPARE_SYBASE
Default prepareSql property for Sybase. |
private static java.util.HashMap |
prepareSQLDefaults
Default prepare SQL mode based on server type |
static java.lang.String |
PROCESS_ID
Default processId property. |
static java.lang.String |
PROG_NAME
Default progName property. |
static java.lang.String |
SERVER_TYPE_SQLSERVER
Default serverType property for SQL Server. |
static java.lang.String |
SERVER_TYPE_SYBASE
Default serverType property for Sybase. |
static java.lang.String |
SOCKET_KEEPALIVE
Default socketKeepAlive property. |
static java.lang.String |
SOCKET_TIMEOUT
Default sockeTimeout property. |
static java.lang.String |
SSL
Default ssl property. |
static java.lang.String |
TCP_NODELAY
Default tcpNoDelay property. |
static java.lang.String |
TDS_VERSION_42
Default tds property for TDS 4.2. |
static java.lang.String |
TDS_VERSION_50
Default tds property for TDS 5.0. |
static java.lang.String |
TDS_VERSION_70
Default tds property for TDS 7.0. |
static java.lang.String |
TDS_VERSION_80
Default tds property for TDS 8.0. |
private static java.util.HashMap |
tdsDefaults
Default TDS version based on server type |
static java.lang.String |
USE_UNICODE
Default sendStringParametersAsUnicode property. |
static java.lang.String |
USECURSORS
Default useCursors property. |
static java.lang.String |
USEJCIFS
Default useJCIFS property. |
static java.lang.String |
USELOBS
Default useLOBs property. |
static java.lang.String |
USER
Default user property. |
static java.lang.String |
WSID
Default wsid property. |
static java.lang.String |
XAEMULATION
Default XaEmulation property. |
| Constructor Summary | |
DefaultProperties()
|
|
| Method Summary | |
static java.util.Properties |
addDefaultProperties(java.util.Properties props)
Add default properties to the props properties object. |
private static void |
addDefaultPropertyIfNotSet(java.util.Properties props,
java.lang.String key,
java.lang.String defaultValue)
Sets a default property if the property is not already set. |
private static void |
addDefaultPropertyIfNotSet(java.util.Properties props,
java.lang.String key,
java.lang.String defaultKey,
java.util.Map defaults)
Sets a default property if the property is not already set, using the defaultKey and the defaults map to
determine the correct value. |
static java.lang.String |
getNamedPipePath(int serverType)
Returns the default path for the named pipe for a given serverType. |
static java.lang.String |
getServerType(int serverType)
Converts an integer server type to its string representation. |
static java.lang.Integer |
getServerType(java.lang.String serverType)
Converts a string server type to its integer representation. |
static java.lang.String |
getServerTypeWithDefault(int serverType)
Same as getServerType(int), only it returns the default server
type ("sqlserver") if serverType is 0. |
static java.lang.Integer |
getTdsVersion(java.lang.String tdsVersion)
Converts a string TDS version to its integer representation. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
public static final java.lang.String APP_NAME
appName property.
public static final java.lang.String BATCH_SIZE_SQLSERVER
batchSize property for SQL Server.
public static final java.lang.String BATCH_SIZE_SYBASE
batchSize property for Sybase.
public static final java.lang.String BIND_ADDRESS
bindAddress property.
public static final java.lang.String BUFFER_MAX_MEMORY
bufferMaxMemory property.
public static final java.lang.String BUFFER_MIN_PACKETS
bufferMinPackets property.
public static final java.lang.String CACHEMETA
cacheMetaData property.
public static final java.lang.String CHARSET
charset property.
public static final java.lang.String DATABASE_NAME
databaseName property.
public static final java.lang.String INSTANCE
instance property.
public static final java.lang.String DOMAIN
domain property.
public static final java.lang.String LAST_UPDATE_COUNT
lastUpdateCount property.
public static final java.lang.String LOB_BUFFER_SIZE
lobBufferSize property.
public static final java.lang.String LOGIN_TIMEOUT
loginTimeout property.
public static final java.lang.String MAC_ADDRESS
macAddress property.
public static final java.lang.String MAX_STATEMENTS
maxStatements property.
public static final java.lang.String NAMED_PIPE
namedPipe property.
public static final java.lang.String NAMED_PIPE_PATH_SQLSERVER
namedPipePath property for SQL Server.
public static final java.lang.String NAMED_PIPE_PATH_SYBASE
namedPipePath property for Sybase.
public static final java.lang.String PACKET_SIZE_42
packetSize property for TDS 4.2.
public static final java.lang.String PACKET_SIZE_50
packetSize property for TDS 5.0.
public static final java.lang.String PACKET_SIZE_70_80
packetSize property for TDS 7.0 and TDS 8.0.
public static final java.lang.String PASSWORD
password property.
public static final java.lang.String PORT_NUMBER_SQLSERVER
portNumber property for SQL Server.
public static final java.lang.String PORT_NUMBER_SYBASE
portNumber property for Sybase.
public static final java.lang.String LANGUAGE
language property.
public static final java.lang.String PREPARE_SQLSERVER
prepareSql property for SQL Server.
public static final java.lang.String PREPARE_SYBASE
prepareSql property for Sybase.
public static final java.lang.String PROG_NAME
progName property.
public static final java.lang.String TCP_NODELAY
tcpNoDelay property.
public static final java.lang.String BUFFER_DIR
tmpDir property.
public static final java.lang.String USE_UNICODE
sendStringParametersAsUnicode property.
public static final java.lang.String USECURSORS
useCursors property.
public static final java.lang.String USEJCIFS
useJCIFS property.
public static final java.lang.String USELOBS
useLOBs property.
public static final java.lang.String USER
user property.
public static final java.lang.String WSID
wsid property.
public static final java.lang.String XAEMULATION
XaEmulation property.
public static final java.lang.String LOGFILE
logfile property.
public static final java.lang.String SOCKET_TIMEOUT
sockeTimeout property.
public static final java.lang.String SOCKET_KEEPALIVE
socketKeepAlive property.
public static final java.lang.String PROCESS_ID
processId property.
public static final java.lang.String SERVER_TYPE_SQLSERVER
serverType property for SQL Server.
public static final java.lang.String SERVER_TYPE_SYBASE
serverType property for Sybase.
public static final java.lang.String TDS_VERSION_42
tds property for TDS 4.2.
public static final java.lang.String TDS_VERSION_50
tds property for TDS 5.0.
public static final java.lang.String TDS_VERSION_70
tds property for TDS 7.0.
public static final java.lang.String TDS_VERSION_80
tds property for TDS 8.0.
public static final java.lang.String SSL
ssl property.
private static final java.util.HashMap tdsDefaults
private static final java.util.HashMap portNumberDefaults
private static final java.util.HashMap packetSizeDefaults
private static final java.util.HashMap batchSizeDefaults
private static final java.util.HashMap prepareSQLDefaults
| Constructor Detail |
public DefaultProperties()
| Method Detail |
public static java.util.Properties addDefaultProperties(java.util.Properties props)
props properties object.
props - The properties object.
props object, or null
if the serverType property is not set.
private static void addDefaultPropertyIfNotSet(java.util.Properties props,
java.lang.String key,
java.lang.String defaultValue)
props - The properties object.key - The message key to set.defaultValue - The default value to set.
private static void addDefaultPropertyIfNotSet(java.util.Properties props,
java.lang.String key,
java.lang.String defaultKey,
java.util.Map defaults)
defaultKey and the defaults map to
determine the correct value.
props - The properties object.key - The message key to set.defaultKey - The key whose value determines which default
value to set from defaults.defaults - The mapping of defaultKey values to
the correct key value to set.public static java.lang.String getNamedPipePath(int serverType)
serverType - Driver.SQLSERVER or Driver.SYBASE or 0 (default)
java.lang.IllegalArgumentException - if an invalid serverType is givenpublic static java.lang.String getServerType(int serverType)
serverType - the server type as an int
null if unknownpublic static java.lang.Integer getServerType(java.lang.String serverType)
serverType - the server type as a string
null if
unknownpublic static java.lang.String getServerTypeWithDefault(int serverType)
getServerType(int), only it returns the default server
type ("sqlserver") if serverType is 0.
serverType - integer server type or 0 for default
"sqlserver"
if unknownpublic static java.lang.Integer getTdsVersion(java.lang.String tdsVersion)
tdsVersion - The TDS version as a string.
null if unknown.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.SharedSocket
net.sourceforge.jtds.jdbc.SharedNamedPipe
This class implements inter-process communication (IPC) to the database server using named pipes.
SharedSocket and this class., Implement connection timeouts for named pipes.| Field Summary | |
private jcifs.smb.SmbNamedPipe |
pipe
The shared named pipe. |
protected int |
serverType
The servertype one of Driver.SQLSERVER or Driver.SYBASE |
| Constructor Summary | |
SharedNamedPipe(ConnectionJDBC2 connection)
Creates a new instance of SharedNamedPipe. |
|
| Method Summary | |
(package private) boolean |
cancel(int streamId)
Send a TDS cancel packet to the server. |
(package private) void |
close()
Close the socket (noop if in shared mode). |
(package private) void |
closeStream(int streamId)
Deallocate a stream linked to this socket. |
(package private) void |
disableEncryption()
Disable TLS encryption and switch back to raw TCP/IP socket. |
(package private) void |
enableEncryption(java.lang.String ssl)
Enable TLS encryption by creating a TLS socket over the existing TCP/IP network socket. |
protected void |
finalize()
Finalize this object by releasing its resources. |
(package private) void |
forceClose()
Force close the socket causing any pending reads/writes to fail. |
(package private) java.lang.String |
getCharset()
Retrieve the character set name used to translate byte arrays to or from Strings. |
(package private) CharsetInfo |
getCharsetInfo()
Retrieve the character set descriptor used to translate byte arrays to or from Strings. |
protected java.lang.String |
getHost()
Get the server host name. |
protected java.io.DataInputStream |
getIn()
Getter for SharedSocket.in field. |
(package private) static int |
getMemoryBudget()
Get the global buffer memory limit for all instancs of this driver. |
(package private) static int |
getMinMemPkts()
Get the minimum number of memory cached packets. |
(package private) byte[] |
getNetPacket(int streamId,
byte[] buffer)
Get a network packet. |
protected java.io.DataOutputStream |
getOut()
Getter for SharedSocket.out field. |
private jcifs.smb.SmbNamedPipe |
getPipe()
Getter for pipe field. |
(package private) static int |
getPktLen(byte[] buf)
Convert two bytes (in network byte order) in a byte array into a Java short integer. |
protected int |
getPort()
Get the server port number. |
(package private) RequestStream |
getRequestStream(int bufferSize,
int maxPrecision)
Obtain an instance of a server request stream for this socket. |
(package private) ResponseStream |
getResponseStream(RequestStream requestStream,
int bufferSize)
Obtain an instance of a server response stream for this socket. |
(package private) int |
getTdsVersion()
Retrieve the TDS version that is active on the connection supported by this socket. |
(package private) boolean |
isConnected()
Get the connected status of this socket. |
(package private) byte[] |
sendNetPacket(int streamId,
byte[] buffer)
Send a network packet. |
(package private) void |
setCharsetInfo(CharsetInfo charsetInfo)
Set the character set descriptor to be used to translate byte arrays to or from Strings. |
protected void |
setIn(java.io.DataInputStream in)
Setter for SharedSocket.in field. |
protected void |
setKeepAlive(boolean keepAlive)
Set the socket keep alive. |
(package private) static void |
setMemoryBudget(int memoryBudget)
Set the global buffer memory limit for all instances of this driver. |
(package private) static void |
setMinMemPkts(int minMemPkts)
Set the minimum number of packets to cache in memory before writing to disk. |
protected void |
setOut(java.io.DataOutputStream out)
Setter for SharedSocket.out field. |
private void |
setPipe(jcifs.smb.SmbNamedPipe pipe)
Setter for pipe field. |
protected void |
setTdsVersion(int tdsVersion)
Set the TDS version field. |
protected void |
setTimeout(int timeout)
Set the socket timeout. |
| Methods inherited from class java.lang.Object |
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private jcifs.smb.SmbNamedPipe pipe
protected final int serverType
| Constructor Detail |
public SharedNamedPipe(ConnectionJDBC2 connection) throws java.io.IOException
SharedNamedPipe.
connection -
java.io.IOException - if the named pipe or its input or output streams do
not open
java.net.UnknownHostException - if host cannot be found for the named pipe| Method Detail |
boolean isConnected()
isConnected in class SharedSocket
void close()
throws java.io.IOException
close in class SharedSocketjava.io.IOException - if the socket close failsvoid forceClose()
forceClose in class SharedSocketprivate jcifs.smb.SmbNamedPipe getPipe()
pipe field.
SmbNamedPipe used for communicationprivate void setPipe(jcifs.smb.SmbNamedPipe pipe)
pipe field.
pipe - SmbNamedPipe to be used for communicationprotected void setTimeout(int timeout)
setTimeout in class SharedSockettimeout - timeout value in milliseconds
void enableEncryption(java.lang.String ssl)
throws java.io.IOException
ssl - the SSL URL property value
java.io.IOException - if an I/O error occurs
void disableEncryption()
throws java.io.IOException
java.io.IOException - if an I/O error occursvoid setCharsetInfo(CharsetInfo charsetInfo)
charsetInfo - the character set descriptorCharsetInfo getCharsetInfo()
java.lang.String getCharset()
StringRequestStream getRequestStream(int bufferSize, int maxPrecision)
bufferSize - the initial buffer size to be used by the
RequestStreammaxPrecision - the maximum precision for numeric/decimal types
RequestStreamResponseStream getResponseStream(RequestStream requestStream, int bufferSize)
requestStream - an existing server request stream object obtained
from this SharedSocketbufferSize - the initial buffer size to be used by the
RequestStream
ResponseStreamint getTdsVersion()
intprotected void setTdsVersion(int tdsVersion)
tdsVersion - the TDS version as an intstatic void setMemoryBudget(int memoryBudget)
memoryBudget - the global memory budgetstatic int getMemoryBudget()
intstatic void setMinMemPkts(int minMemPkts)
minMemPkts - the minimum number of packets to cachestatic int getMinMemPkts()
intboolean cancel(int streamId)
streamId - the RequestStream id
boolean true if a cancel is actually
issued by this method call.void closeStream(int streamId)
streamId - the ResponseStream id
byte[] sendNetPacket(int streamId,
byte[] buffer)
throws java.io.IOException
streamId - the originating RequestStream objectbuffer - the data to send
java.io.IOException - if an I/O error occurs
byte[] getNetPacket(int streamId,
byte[] buffer)
throws java.io.IOException
streamId - the originating ResponseStream objectbuffer - the data buffer to receive the object (may be replaced)
byte[] buffer
java.io.IOException - if an I/O error occursstatic int getPktLen(byte[] buf)
buf - array of data
int
protected void setKeepAlive(boolean keepAlive)
throws java.net.SocketException
keepAlive - true to turn on socket keep alive
java.net.SocketExceptionprotected java.io.DataInputStream getIn()
SharedSocket.in field.
InputStream used for communicationprotected void setIn(java.io.DataInputStream in)
SharedSocket.in field.
in - the InputStream to be used for communicationprotected java.io.DataOutputStream getOut()
SharedSocket.out field.
OutputStream used for communicationprotected void setOut(java.io.DataOutputStream out)
SharedSocket.out field.
out - the OutputStream to be used for communicationprotected java.lang.String getHost()
Stringprotected int getPort()
int
protected void finalize()
throws java.lang.Throwable
java.lang.Throwable
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.TdsData.TypeInfo
This class implements a descriptor for TDS data types;
| Field Summary | |
int |
displaySize
The display size of the type. |
boolean |
isCollation
true if type requires TDS80 collation. |
boolean |
isSigned
true if type is a signed numeric. |
int |
jdbcType
The java.sql.Types constant for this data type. |
int |
precision
The precision of the type. |
int |
size
The size of this type or < 0 for variable sizes. |
java.lang.String |
sqlType
The SQL type name. |
| Constructor Summary | |
(package private) |
TdsData.TypeInfo(java.lang.String sqlType,
int size,
int precision,
int displaySize,
boolean isSigned,
boolean isCollation,
int jdbcType)
Construct a new TDS data type descriptor. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
public final java.lang.String sqlType
public final int size
Special values as follows:
public final int precision
If this is -1 precision must be calculated from buffer size eg for varchar fields.
public final int displaySize
-1 If the display size must be calculated from the buffer size.
public final boolean isSigned
public final boolean isCollation
public final int jdbcType
| Constructor Detail |
TdsData.TypeInfo(java.lang.String sqlType,
int size,
int precision,
int displaySize,
boolean isSigned,
boolean isCollation,
int jdbcType)
sqlType - SQL type name.size - Byte size for this type or < 0 for variable length types.precision - Decimal precision or -1displaySize - Printout size for this type or special values -1,-2.isSigned - True if signed numeric type.isCollation - True if type has TDS 8 collation information.jdbcType - The java.sql.Type constant for this type.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.JtdsResultSet
net.sourceforge.jtds.jdbc.MSCursorResultSet
This class extends the JtdsResultSet to support scrollable and or updateable cursors on Microsoft servers.
The undocumented Microsoft sp_cursor procedures are used.
Implementation notes:
| Field Summary | |
private boolean |
asyncCursor
The cursor is being built asynchronously. |
private static int |
CURSOR_CONCUR_OPTIMISTIC
|
private static int |
CURSOR_CONCUR_OPTIMISTIC_VALUES
|
private static int |
CURSOR_CONCUR_READ_ONLY
|
private static int |
CURSOR_CONCUR_SCROLL_LOCKS
|
private static java.lang.Integer |
CURSOR_OP_DELETE
|
private static java.lang.Integer |
CURSOR_OP_INSERT
|
private static java.lang.Integer |
CURSOR_OP_UPDATE
|
private static int |
CURSOR_TYPE_AUTO_FETCH
|
private static int |
CURSOR_TYPE_DYNAMIC
|
private static int |
CURSOR_TYPE_FASTFORWARDONLY
|
private static int |
CURSOR_TYPE_FORWARD
|
private static int |
CURSOR_TYPE_KEYSET
|
private static int |
CURSOR_TYPE_PARAMETERIZED
|
private static int |
CURSOR_TYPE_STATIC
|
private int |
cursorPos
Actual position of the cursor. |
private static java.lang.Integer |
FETCH_ABSOLUTE
|
private static java.lang.Integer |
FETCH_FIRST
|
private static java.lang.Integer |
FETCH_INFO
|
private static java.lang.Integer |
FETCH_LAST
|
private static java.lang.Integer |
FETCH_NEXT
|
private static java.lang.Integer |
FETCH_PREVIOUS
|
private static java.lang.Integer |
FETCH_RELATIVE
|
private static java.lang.Integer |
FETCH_REPEAT
|
private ParamInfo[] |
insertRow
The "insert row". |
private boolean |
onInsertRow
Set when moveToInsertRow() was called. |
private ParamInfo |
PARAM_CURSOR_HANDLE
Cursor handle parameter. |
private ParamInfo |
PARAM_FETCHTYPE
sp_cursorfetch fetchtype parameter. |
private ParamInfo |
PARAM_NUMROWS_IN
sp_cursorfetch numrows IN parameter (for actual fetches). |
private ParamInfo |
PARAM_NUMROWS_OUT
sp_cursorfetch numrows OUT parameter (for FETCH_INFO). |
private ParamInfo |
PARAM_OPTYPE
sp_cursor optype parameter. |
private ParamInfo |
PARAM_ROWNUM
sp_cursor rownum parameter. |
private ParamInfo |
PARAM_ROWNUM_IN
sp_cursorfetch rownum IN parameter (for actual fetches). |
private ParamInfo |
PARAM_ROWNUM_OUT
sp_cursorfetch rownum OUT parameter (for FETCH_INFO). |
private ParamInfo |
PARAM_TABLE
sp_cursor table parameter. |
private java.lang.Object[][] |
rowCache
The row cache used instead JtdsResultSet.currentRow. |
private static java.lang.Integer |
SQL_ROW_DELETED
The row has been deleted. |
private static java.lang.Integer |
SQL_ROW_DIRTY
The row is dirty and needs to be reloaded (internal state). |
private static java.lang.Integer |
SQL_ROW_SUCCESS
The row is valid. |
private ParamInfo[] |
updateRow
The "update row". |
| Fields inherited from class net.sourceforge.jtds.jdbc.JtdsResultSet |
cancelled, CLOSE_CURSORS_AT_COMMIT, closed, columnCount, columns, concurrency, currentRow, cursorName, direction, fetchDirection, fetchSize, HOLD_CURSORS_OVER_COMMIT, INITIAL_ROW_COUNT, pos, POS_AFTER_LAST, POS_BEFORE_FIRST, resultSetType, rowData, rowPtr, rowsInResult, statement, wasNull |
| Fields inherited from interface java.sql.ResultSet |
CONCUR_READ_ONLY, CONCUR_UPDATABLE, FETCH_FORWARD, FETCH_REVERSE, FETCH_UNKNOWN, TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, TYPE_SCROLL_SENSITIVE |
| Constructor Summary | |
(package private) |
MSCursorResultSet(JtdsStatement statement,
java.lang.String sql,
java.lang.String procName,
ParamInfo[] procedureParams,
int resultSetType,
int concurrency)
Construct a cursor result set using Microsoft sp_cursorcreate etc. |
| Method Summary | |
boolean |
absolute(int row)
|
void |
afterLast()
|
void |
beforeFirst()
|
void |
cancelRowUpdates()
|
void |
close()
|
private void |
cursor(java.lang.Integer opType,
ParamInfo[] row)
Support general cursor operations such as delete, update etc. |
private void |
cursorClose()
Close a server side cursor. |
private void |
cursorCreate(java.lang.String sql,
java.lang.String procName,
ParamInfo[] parameters)
Create a new Cursor result set using the internal sp_cursoropen procedure. |
private boolean |
cursorFetch(java.lang.Integer fetchType,
int rowNum)
Fetch the next result row from a cursor using the internal sp_cursorfetch procedure. |
void |
deleteRow()
|
boolean |
first()
|
protected java.lang.Object |
getColumn(int index)
Get the specified column's data item. |
protected java.lang.Object[] |
getCurrentRow()
Retrieve the current row data. |
(package private) static int |
getCursorConcurrencyOpt(int resultSetConcurrency)
Translates a JDBC result set concurrency into SQL Server native @ccOpt value for use with stored procedures such as sp_cursoropen, sp_cursorprepare or sp_cursorprepexec. |
(package private) static int |
getCursorScrollOpt(int resultSetType,
int resultSetConcurrency,
boolean parameterized)
Translates a JDBC result set type into SQL Server native @scrollOpt value for use with stored procedures such as sp_cursoropen, sp_cursorprepare or sp_cursorprepexec. |
void |
insertRow()
|
boolean |
isLast()
|
boolean |
last()
|
void |
moveToCurrentRow()
|
void |
moveToInsertRow()
|
boolean |
next()
|
boolean |
previous()
|
private void |
processOutput(TdsCore tds,
boolean setMeta)
Processes the output of a cursor open or fetch operation. |
void |
refreshRow()
|
boolean |
relative(int row)
|
boolean |
rowDeleted()
|
boolean |
rowInserted()
|
boolean |
rowUpdated()
|
protected java.lang.Object |
setColValue(int colIndex,
int jdbcType,
java.lang.Object value,
int length)
Set the specified column's data value. |
void |
updateRow()
|
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private static final java.lang.Integer FETCH_FIRST
private static final java.lang.Integer FETCH_NEXT
private static final java.lang.Integer FETCH_PREVIOUS
private static final java.lang.Integer FETCH_LAST
private static final java.lang.Integer FETCH_ABSOLUTE
private static final java.lang.Integer FETCH_RELATIVE
private static final java.lang.Integer FETCH_REPEAT
private static final java.lang.Integer FETCH_INFO
private static final int CURSOR_TYPE_KEYSET
private static final int CURSOR_TYPE_DYNAMIC
private static final int CURSOR_TYPE_FORWARD
private static final int CURSOR_TYPE_STATIC
private static final int CURSOR_TYPE_FASTFORWARDONLY
private static final int CURSOR_TYPE_PARAMETERIZED
private static final int CURSOR_TYPE_AUTO_FETCH
private static final int CURSOR_CONCUR_READ_ONLY
private static final int CURSOR_CONCUR_SCROLL_LOCKS
private static final int CURSOR_CONCUR_OPTIMISTIC
private static final int CURSOR_CONCUR_OPTIMISTIC_VALUES
private static final java.lang.Integer CURSOR_OP_INSERT
private static final java.lang.Integer CURSOR_OP_UPDATE
private static final java.lang.Integer CURSOR_OP_DELETE
private static final java.lang.Integer SQL_ROW_DIRTY
private static final java.lang.Integer SQL_ROW_SUCCESS
private static final java.lang.Integer SQL_ROW_DELETED
private boolean onInsertRow
moveToInsertRow() was called.
private ParamInfo[] insertRow
private ParamInfo[] updateRow
private java.lang.Object[][] rowCache
JtdsResultSet.currentRow.
private int cursorPos
private boolean asyncCursor
private final ParamInfo PARAM_CURSOR_HANDLE
private final ParamInfo PARAM_FETCHTYPE
sp_cursorfetch fetchtype parameter.
private final ParamInfo PARAM_ROWNUM_IN
sp_cursorfetch rownum IN parameter (for actual fetches).
private final ParamInfo PARAM_NUMROWS_IN
sp_cursorfetch numrows IN parameter (for actual fetches).
private final ParamInfo PARAM_ROWNUM_OUT
sp_cursorfetch rownum OUT parameter (for FETCH_INFO).
private final ParamInfo PARAM_NUMROWS_OUT
sp_cursorfetch numrows OUT parameter (for FETCH_INFO).
private final ParamInfo PARAM_OPTYPE
sp_cursor optype parameter.
private final ParamInfo PARAM_ROWNUM
sp_cursor rownum parameter.
private final ParamInfo PARAM_TABLE
sp_cursor table parameter.
| Constructor Detail |
MSCursorResultSet(JtdsStatement statement, java.lang.String sql, java.lang.String procName, ParamInfo[] procedureParams, int resultSetType, int concurrency) throws java.sql.SQLException
statement - The parent statement object or null.resultSetType - one of FORWARD_ONLY, SCROLL_INSENSITIVE, SCROLL_SENSITIVE.concurrency - One of CONCUR_READ_ONLY, CONCUR_UPDATE.
java.sql.SQLException| Method Detail |
protected java.lang.Object setColValue(int colIndex,
int jdbcType,
java.lang.Object value,
int length)
throws java.sql.SQLException
setColValue in class JtdsResultSetcolIndex - index of the columnvalue - new column valuelength - the length of a stream parameter
java.sql.SQLException
protected java.lang.Object getColumn(int index)
throws java.sql.SQLException
getColumn in class JtdsResultSetindex - the column index in the row
Object
java.sql.SQLException - if the index is out of bounds or there is no
current row
static int getCursorScrollOpt(int resultSetType,
int resultSetConcurrency,
boolean parameterized)
resultSetType - JDBC result set type (one of the
ResultSet.TYPE_XXX
values)resultSetConcurrency - JDBC result set concurrency (one of the
ResultSet.CONCUR_XXX
values)
static int getCursorConcurrencyOpt(int resultSetConcurrency)
resultSetConcurrency - JDBC result set concurrency (one of the
ResultSet.CONCUR_XXX
values)
private void cursorCreate(java.lang.String sql,
java.lang.String procName,
ParamInfo[] parameters)
throws java.sql.SQLException
sql - The SQL SELECT statement.procName - Optional procedure name for cursors based on a stored procedure.parameters - Optional stored procedure parameters.
java.sql.SQLException
private boolean cursorFetch(java.lang.Integer fetchType,
int rowNum)
throws java.sql.SQLException
fetchType - The type of fetch eg FETCH_ABSOLUTE.rowNum - The row number to fetch.
boolean true if a result set row is returned.
java.sql.SQLException
private void cursor(java.lang.Integer opType,
ParamInfo[] row)
throws java.sql.SQLException
opType - the type of operation to performrow - the row number to update
java.sql.SQLException
private void cursorClose()
throws java.sql.SQLException
java.sql.SQLExceptionprivate void processOutput(TdsCore tds, boolean setMeta) throws java.sql.SQLException
TdsCore, loading them into the row
cache and optionally sets the column meta data (if called on cursor
open). Consumes all the response and checks for server returned errors.
tds - the TdsCore instancesetMeta - whether column meta data needs to be loaded (cursor open)
java.sql.SQLException - if an error occurs or an error message is returned
by the server
public void afterLast()
throws java.sql.SQLException
afterLast in interface java.sql.ResultSetafterLast in class JtdsResultSetjava.sql.SQLException
public void beforeFirst()
throws java.sql.SQLException
beforeFirst in interface java.sql.ResultSetbeforeFirst in class JtdsResultSetjava.sql.SQLException
public void cancelRowUpdates()
throws java.sql.SQLException
cancelRowUpdates in interface java.sql.ResultSetcancelRowUpdates in class JtdsResultSetjava.sql.SQLException
public void close()
throws java.sql.SQLException
close in interface java.sql.ResultSetclose in class JtdsResultSetjava.sql.SQLException
public void deleteRow()
throws java.sql.SQLException
deleteRow in interface java.sql.ResultSetdeleteRow in class JtdsResultSetjava.sql.SQLException
public void insertRow()
throws java.sql.SQLException
insertRow in interface java.sql.ResultSetinsertRow in class JtdsResultSetjava.sql.SQLException
public void moveToCurrentRow()
throws java.sql.SQLException
moveToCurrentRow in interface java.sql.ResultSetmoveToCurrentRow in class JtdsResultSetjava.sql.SQLException
public void moveToInsertRow()
throws java.sql.SQLException
moveToInsertRow in interface java.sql.ResultSetmoveToInsertRow in class JtdsResultSetjava.sql.SQLException
public void refreshRow()
throws java.sql.SQLException
refreshRow in interface java.sql.ResultSetrefreshRow in class JtdsResultSetjava.sql.SQLException
public void updateRow()
throws java.sql.SQLException
updateRow in interface java.sql.ResultSetupdateRow in class JtdsResultSetjava.sql.SQLException
public boolean first()
throws java.sql.SQLException
first in interface java.sql.ResultSetfirst in class JtdsResultSetjava.sql.SQLException
public boolean isLast()
throws java.sql.SQLException
isLast in interface java.sql.ResultSetisLast in class JtdsResultSetjava.sql.SQLException
public boolean last()
throws java.sql.SQLException
last in interface java.sql.ResultSetlast in class JtdsResultSetjava.sql.SQLException
public boolean next()
throws java.sql.SQLException
next in interface java.sql.ResultSetnext in class JtdsResultSetjava.sql.SQLException
public boolean previous()
throws java.sql.SQLException
previous in interface java.sql.ResultSetprevious in class JtdsResultSetjava.sql.SQLException
public boolean rowDeleted()
throws java.sql.SQLException
rowDeleted in interface java.sql.ResultSetrowDeleted in class JtdsResultSetjava.sql.SQLException
public boolean rowInserted()
throws java.sql.SQLException
rowInserted in interface java.sql.ResultSetrowInserted in class JtdsResultSetjava.sql.SQLException
public boolean rowUpdated()
throws java.sql.SQLException
rowUpdated in interface java.sql.ResultSetrowUpdated in class JtdsResultSetjava.sql.SQLException
public boolean absolute(int row)
throws java.sql.SQLException
absolute in interface java.sql.ResultSetabsolute in class JtdsResultSetjava.sql.SQLException
public boolean relative(int row)
throws java.sql.SQLException
relative in interface java.sql.ResultSetrelative in class JtdsResultSetjava.sql.SQLExceptionprotected java.lang.Object[] getCurrentRow()
JtdsResultSet
getCurrentRow in class JtdsResultSetObject[].
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV PACKAGE NEXT PACKAGE | FRAMES NO FRAMES | ||||||||||
| Class Summary | |
| BlobImpl | An in-memory or disk based representation of binary data. |
| CachedResultSet | A memory cached scrollable/updateable result set. |
| CharsetInfo | Loads and stores information about character sets. |
| ClobImpl | An in-memory or disk based representation of character data. |
| ColInfo | This class is a descriptor for result set columns. |
| ConnectionJDBC2 | jTDS implementation of the java.sql.Connection interface. |
| ConnectionJDBC3 | Implements JDBC 3.0 specific functionality. |
| DateTime | Encapsulates Sybase date/time values and provides conversions to and from Java classes. |
| DefaultProperties | Container for default property constants. |
| Driver | jTDS implementation of the java.sql.Driver interface. |
| JtdsCallableStatement | jTDS implementation of the java.sql.CallableStatement interface. |
| JtdsDatabaseMetaData | jTDS implementation of the java.sql.DatabaseMetaData interface. |
| JtdsPreparedStatement | jTDS implementation of the java.sql.PreparedStatement interface. |
| JtdsResultSet | jTDS Implementation of the java.sql.ResultSet interface supporting forward read only result sets. |
| JtdsResultSetMetaData | jTDS implementation of the java.sql.ResultSetMetaData interface. |
| JtdsStatement | jTDS implementation of the java.sql.Statement interface. |
| Messages | Support class for Messages.properties. |
| MSCursorResultSet | This class extends the JtdsResultSet to support scrollable and or updateable cursors on Microsoft servers. |
| MSSqlServerInfo | This class communicates with SQL Server 2k to determine what ports its instances are listening to. |
| NtlmAuth | This class calculates the two "responses" to the nonce supplied by the server as a part of NTLM authentication. |
| ParameterMetaDataImpl | jTDS implementation of ParameterMetaData.
|
| ParamInfo | This class is a descriptor for procedure and prepared statement parameters. |
| ProcEntry | Stores information about a cached stored procedure or statement handle. |
| RequestStream | Class to implement an output stream for the server request. |
| ResponseStream | Implements an input stream for the server response. |
| ResponseStream.TdsInputStream | Simple inner class implementing an InputStream over the
server response. |
| SavepointImpl | Savepoint implementation class. |
| Semaphore | Simple semaphore class used to serialize access requests over the network connection. |
| SharedLocalNamedPipe | This class implements inter-process communication (IPC) to the database server using local named pipes (will only work on Windows). |
| SharedNamedPipe | This class implements inter-process communication (IPC) to the database server using named pipes. |
| SharedSocket | This class mananges the physical connection to the SQL Server and serialises its use amongst a number of virtual sockets. |
| SharedSocket.VirtualSocket | This inner class contains the state information for the virtual socket. |
| SQLDiagnostic | Helper class for handling SQL warnings and errors. |
| SQLParser | Process JDBC escape strings and parameter markers in the SQL string. |
| SQLParser.CachedSQLQuery | Serialized version of a parsed SQL query (the value stored in the cache for a parsed SQL). |
| Support | This class contains static utility methods designed to support the main driver classes. |
| TdsCore | This class implements the Sybase / Microsoft TDS protocol. |
| TdsCore.TableMetaData | Inner static class used to hold table meta data. |
| TdsCore.TdsToken | Inner static class used to hold information about TDS tokens read. |
| TdsData | Implement TDS data types and related I/O logic. |
| TdsData.TypeInfo | This class implements a descriptor for TDS data types; |
| TypeInfo | Represents an SQL data type as required by getTypeInfo().
|
| UniqueIdentifier | This class encapsulates the MS SQL2000 UniqueIdentifer data type. |
| XASupport | This class contains static utility methods used to implement distributed transactions. |
| Exception Summary | |
| ProtocolException | Exception class used to report errors in the TDS protocol. |
|
|||||||||||
| PREV PACKAGE NEXT PACKAGE | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.TdsCore
This class implements the Sybase / Microsoft TDS protocol.
Implementation notes:
| Nested Class Summary | |
private static class |
TdsCore.TableMetaData
Inner static class used to hold table meta data. |
private static class |
TdsCore.TdsToken
Inner static class used to hold information about TDS tokens read. |
| Field Summary | |
private static int |
ASYNC_CANCEL
Cancel has been generated by Statement.cancel(). |
static byte |
CANCEL_PKT
TDS Cancel packet. |
private int[] |
cancelMonitor
Synchronization monitor for cancelPending. |
private boolean |
cancelPending
Indicates pending cancel that needs to be cleared. |
private ColInfo[] |
columns
The array of column meta data objects for this result set. |
private ConnectionJDBC2 |
connection
The Connection object that created this object. |
private Semaphore |
connectionLock
Mutual exclusion lock on connection. |
private TdsCore.TdsToken |
currentToken
The descriptor object for the current TDS token. |
static int |
DEFAULT_MIN_PKT_SIZE_TDS70
Default minimum network packet size for TDS 7.0 and newer. |
(package private) static byte |
DONE_CANCEL
Done: Cancel acknowledgement. |
private static byte |
DONE_END_OF_RESPONSE
Done: Response terminator (if more than one request packet is sent, each response is terminated by a DONE packet with this flag set). |
private static byte |
DONE_ERROR
Done: command caused an error. |
private static byte |
DONE_MORE_RESULTS
Done: more results are expected. |
private static byte |
DONE_ROW_COUNT
Done: There is a valid row count. |
private static ParamInfo[] |
EMPTY_PARAMETER_INFO
Used to optimize the getParameters() call |
private boolean |
endOfResponse
True if the server response is fully read. |
private boolean |
endOfResults
True if the current result set is at end of file. |
static int |
EXECUTE_SQL
Prepare SQL using sp_executesql |
private boolean |
fatalError
Indicates that a fatal error has occured and the connection will close. |
private static java.lang.String |
hostName
Name of the client host (it can take quite a while to find it out if DNS is configured incorrectly). |
private ResponseStream |
in
The input server response stream. |
private boolean |
inBatch
Indicates processing a batch. |
private boolean |
isClosed
Indicates that this object is closed. |
static byte |
LOGIN_PKT
TDS 4.2 or 5.0 Login packet. |
static int |
MAX_PKT_SIZE
Maximum network packet size. |
private SQLDiagnostic |
messages
The head of the diagnostic messages chain. |
static int |
MIN_PKT_SIZE
Minimum network packet size. |
static byte |
MSDTC_PKT
TDS MSDTC packet. |
static byte |
MSLOGIN_PKT
TDS 7.0 Login packet. |
private int |
nextParam
The index of the next output parameter to populate. |
static byte |
NTLMAUTH_PKT
TDS 7.0 NTLM Authentication packet. |
private boolean |
ntlmAuthSSO
Flag that indicates if logon() should try to use Windows Single Sign On using SSPI. |
private RequestStream |
out
The output server request stream. |
private ParamInfo[] |
parameters
The array of parameter meta data objects for the current procedure call. |
static int |
PKT_HDR_LEN
The size of the packet header. |
static byte |
PRELOGIN_PKT
SQL 2000 prelogin negotiation packet. |
static int |
PREPARE
Prepare SQL using sp_prepare and sp_execute |
static byte |
QUERY_PKT
TDS 4.2 or 7.0 Query packet. |
static byte |
REPLY_PKT
TDS Reply packet. |
private ParamInfo |
returnParam
The return parameter meta data object for the current procedure call. |
private java.lang.Integer |
returnStatus
The stored procedure return status. |
private java.lang.Object[] |
rowData
The array of column data objects in the current row. |
static byte |
RPC_PKT
TDS Remote Procedure Call. |
private int |
serverType
The make of SQL Server (Sybase/Microsoft). |
private SharedSocket |
socket
The Shared network socket object. |
static int |
SSL_CLIENT_FORCE_ENCRYPT
SSL Mode - Client requested force encryption. |
static int |
SSL_ENCRYPT_LOGIN
SSL Mode - Login packet must be encrypted. |
static int |
SSL_NO_ENCRYPT
SSL Mode - No server certificate installed. |
static int |
SSL_SERVER_FORCE_ENCRYPT
SSL Mode - Server requested force encryption. |
private int |
sslMode
Indicates type of SSL connection. |
private static SSPIJNIClient |
sspiJNIClient
A reference to ntlm.SSPIJNIClient. |
(package private) static int |
SYB_BIGINT
Sybase 15+ bigint. |
(package private) static int |
SYB_BITNULL
Sybase nullable bit type. |
(package private) static int |
SYB_DATETIME
Sybase date and time data types. |
(package private) static int |
SYB_EXTCOLINFO
Sybase extended column meta data. |
(package private) static int |
SYB_LONGDATA
Sybase char and binary > 255. |
(package private) static int |
SYB_UNICODE
Sybase univarchar etc. |
(package private) static int |
SYB_UNITEXT
Sybase 15+ unitext. |
static byte |
SYBQUERY_PKT
TDS 5.0 Query packet. |
private TdsCore.TableMetaData[] |
tables
The array of table names associated with this result. |
private static byte |
TDS_ALTROW
TDS Computed result set data row token. |
private static byte |
TDS_AUTH_TOKEN
TDS 7.0 NTLM authentication challenge token. |
private static byte |
TDS_CAP_TOKEN
TDS 5.0 capabilities token. |
private static byte |
TDS_CLOSE_TOKEN
TDS 5.0 Close token. |
private static byte |
TDS_COLFMT_TOKEN
TDS 4.2 Column meta data token. |
private static byte |
TDS_COLINFO_TOKEN
TDS Cursor results column infomation token. |
private static byte |
TDS_COLNAME_TOKEN
TDS 4.2 Column names token. |
private static byte |
TDS_COMP_NAMES_TOKEN
TDS Computed result set names token. |
private static byte |
TDS_COMP_RESULT_TOKEN
TDS Computed result set token. |
private static byte |
TDS_CONTROL_TOKEN
TDS control token. |
private static byte |
TDS_DBRPC_TOKEN
TDS 5.0 RPC token. |
private static byte |
TDS_DONE_TOKEN
TDS done token. |
private static byte |
TDS_DONEINPROC_TOKEN
TDS done in procedure token. |
private static byte |
TDS_DONEPROC_TOKEN
TDS done procedure token. |
private static byte |
TDS_ENV_CHARSET
Environment change: charset changed. |
private static byte |
TDS_ENV_DATABASE
Environment change: database changed. |
private static byte |
TDS_ENV_LANG
Environment change: language changed. |
private static byte |
TDS_ENV_LCID
Environment change: locale changed. |
private static byte |
TDS_ENV_PACKSIZE
Environment change: network packet size changed. |
private static byte |
TDS_ENV_SQLCOLLATION
Environment change: TDS 8 collation changed. |
private static byte |
TDS_ENVCHANGE_TOKEN
TDS environment change token. |
private static byte |
TDS_ERROR_TOKEN
TDS error result token. |
private static byte |
TDS_INFO_TOKEN
TDS Information message token. |
private static byte |
TDS_LANG_TOKEN
TDS 5.0 Language token. |
private static byte |
TDS_LOGINACK_TOKEN
TDS Login acknowledgement token. |
private static byte |
TDS_MSG50_TOKEN
TDS 5.0 message token. |
private static byte |
TDS_OFFSETS_TOKEN
TDS DBLIB Offsets token. |
private static byte |
TDS_OPTIONCMD_TOKEN
TDS Optional command token. |
private static byte |
TDS_ORDER_TOKEN
TDS Order by columns token. |
private static byte |
TDS_PARAM_TOKEN
TDS Output parameter value token. |
private static byte |
TDS_PROCID
TDS Procedure ID token. |
private static byte |
TDS_RESULT_TOKEN
TDS 5.0 Result set column meta data token. |
private static byte |
TDS_RETURNSTATUS_TOKEN
TDS Procedure call return status token. |
private static byte |
TDS_ROW_TOKEN
TDS Result set data row token. |
private static byte |
TDS_TABNAME_TOKEN
TDS Table name token. |
private static byte |
TDS5_DYNAMIC_TOKEN
TDS 5.0 Dynamic SQL token. |
private static byte |
TDS5_PARAMFMT_TOKEN
TDS 5.0 parameter descriptor token. |
private static byte |
TDS5_PARAMFMT2_TOKEN
TDS 5.0 Parameter format token. |
private static byte |
TDS5_PARAMS_TOKEN
TDS 5.0 parameter value token. |
private static byte |
TDS5_WIDE_RESULT
TSD 5.0 Wide result set token. |
private static byte |
TDS7_COMP_RESULT_TOKEN
TDS 7.0 Computed Result set column meta data token. |
private static byte |
TDS7_RESULT_TOKEN
TDS 7.0 Result set column meta data token. |
private static java.util.HashMap |
tds8SpNames
Map of system stored procedures that have shortcuts in TDS8. |
private int |
tdsVersion
The TDS version being supported by this connection. |
static int |
TEMPORARY_STORED_PROCEDURES
Prepare SQL using temporary stored procedures |
private static int |
TIMEOUT_CANCEL
Cancel has been generated by a query timeout. |
static int |
UNPREPARED
Do not prepare SQL |
| Constructor Summary | |
(package private) |
TdsCore(ConnectionJDBC2 connection,
SQLDiagnostic messages)
Construct a TdsCore object. |
| Method Summary | |
(package private) void |
cancel(boolean timeout)
Send (only) one cancel packet to the server. |
private void |
checkOpen()
Check that the connection is still open. |
void |
cleanUp()
Releases parameter and result set data and metadata to free up memory. |
(package private) void |
clearResponseQueue()
Empty the server response queue. |
(package private) void |
close()
Close the TdsCore connection object and associated streams. |
(package private) void |
closeConnection()
Inform the server that this connection is closing. |
(package private) void |
consumeOneResponse()
Consume packets from the server response queue up to (and including) the first response terminator. |
(package private) byte[] |
enlistConnection(int type,
byte[] oleTranID)
Enlist the current connection in a distributed transaction or request the location of the MSDTC instance controlling the server we are connected to. |
(package private) void |
executeSQL(java.lang.String sql,
java.lang.String procName,
ParamInfo[] parameters,
boolean noMetaData,
int timeOut,
int maxRows,
int maxFieldSize,
boolean sendNow)
Send an SQL statement with optional parameters to the server. |
private void |
executeSQL42(java.lang.String sql,
java.lang.String procName,
ParamInfo[] parameters,
boolean noMetaData,
boolean sendNow)
Execute SQL using TDS 4.2 protocol. |
private void |
executeSQL50(java.lang.String sql,
java.lang.String procName,
ParamInfo[] parameters)
Execute SQL using TDS 5.0 protocol. |
private void |
executeSQL70(java.lang.String sql,
java.lang.String procName,
ParamInfo[] parameters,
boolean noMetaData,
boolean sendNow)
Execute SQL using TDS 7.0 protocol. |
(package private) java.sql.SQLException |
getBatchCounts(java.util.ArrayList counts,
java.sql.SQLException sqlEx)
Obtain the counts from a batch of SQL updates. |
(package private) ColInfo[] |
getColumns()
Retrieve the current result set column descriptors. |
private static java.lang.String |
getHostName()
Tries to figure out what client name we should identify ourselves as. |
private static int |
getIntFromBuffer(byte[] buf,
int offset)
|
private static byte[] |
getMACAddress(java.lang.String macString)
Converts a user supplied MAC address into a byte array. |
SQLDiagnostic |
getMessages()
Returns the diagnostic chain for this instance. |
(package private) boolean |
getMoreResults()
Get the next result set or update count from the TDS stream. |
(package private) boolean |
getNextRow()
Retrieve the next data row from the result set. |
(package private) ParamInfo[] |
getParameters()
Retrieve the parameter meta data from a Sybase prepare. |
(package private) java.lang.Integer |
getReturnStatus()
Retrieve the return status for the current stored procedure. |
(package private) java.lang.Object[] |
getRowData()
Retrieve the current result set data items. |
private static int |
getShortFromBuffer(byte[] buf,
int offset)
|
(package private) int |
getTdsVersion()
Retrieve the TDS protocol version. |
(package private) int |
getUpdateCount()
Retrieve the update count from the current TDS token. |
(package private) boolean |
isDataInResultSet()
Retrieve the status of result set. |
(package private) boolean |
isEndOfResponse()
Retrieve the status of the response stream. |
static boolean |
isPreparedProcedureName(java.lang.String procName)
Returns true if the specified procName
is a sp_prepare or sp_prepexec handle; returns false
otherwise. |
(package private) boolean |
isResultSet()
Retrieve the status of the next result item. |
(package private) boolean |
isRowData()
Retrieve the status of the next result item. |
(package private) boolean |
isUpdateCount()
Retrieve the status of the next result item. |
(package private) void |
login(java.lang.String serverName,
java.lang.String database,
java.lang.String user,
java.lang.String password,
java.lang.String domain,
java.lang.String charset,
java.lang.String appName,
java.lang.String progName,
java.lang.String wsid,
java.lang.String language,
java.lang.String macAddress,
int packetSize)
Login to the SQL Server. |
(package private) java.lang.String |
microsoftPrepare(java.lang.String sql,
ParamInfo[] params,
boolean needCursor,
int resultSetType,
int resultSetConcurrency)
Prepares the SQL for use with Microsoft server. |
(package private) void |
negotiateSSL(java.lang.String instance,
java.lang.String ssl)
Negotiate SSL settings with SQL 2000+ server. |
private void |
nextToken()
Read the next TDS token from the response stream. |
private void |
putLoginString(java.lang.String txt,
int len)
Write a TDS login packet string. |
private int |
readPreLoginPacket()
Process the pre login acknowledgement from the server. |
private void |
send42LoginPkt(java.lang.String serverName,
java.lang.String user,
java.lang.String password,
java.lang.String charset,
java.lang.String appName,
java.lang.String progName,
java.lang.String wsid,
java.lang.String language,
int packetSize)
TDS 4.2 Login Packet. |
private void |
send50LoginPkt(java.lang.String serverName,
java.lang.String user,
java.lang.String password,
java.lang.String charset,
java.lang.String appName,
java.lang.String progName,
java.lang.String wsid,
java.lang.String language,
int packetSize)
TDS 5.0 Login Packet. |
private void |
sendMSLoginPkt(java.lang.String serverName,
java.lang.String database,
java.lang.String user,
java.lang.String password,
java.lang.String domain,
java.lang.String appName,
java.lang.String progName,
java.lang.String wsid,
java.lang.String language,
java.lang.String macAddress,
int netPacketSize)
Send a TDS 7 login packet. |
private void |
sendNtlmChallengeResponse(byte[] nonce,
java.lang.String user,
java.lang.String password,
java.lang.String domain)
Send the response to the NTLM authentication challenge. |
private void |
sendPreLoginPacket(java.lang.String instance,
boolean forceEncryption)
Send the SQL Server 2000 pre login packet. |
(package private) void |
setColumns(ColInfo[] columns)
Sets the column meta data. |
private void |
setRowCountAndTextSize(int rowCount,
int textSize)
Sets the server row count (to limit the number of rows in a result set) and text size (to limit the size of returned TEXT/NTEXT fields). |
(package private) void |
startBatch()
Notifies the TdsCore that a batch is starting. |
(package private) void |
submitSQL(java.lang.String sql)
Submit a simple SQL statement to the server and process all output. |
(package private) java.lang.String |
sybasePrepare(java.lang.String sql,
ParamInfo[] params)
Creates a light weight stored procedure on a Sybase server. |
(package private) void |
sybaseUnPrepare(java.lang.String procName)
Drops a Sybase temporary stored procedure. |
private void |
tds4ColFormatToken()
Process a TDS 4.2 column format token. |
private void |
tds4ColNamesToken()
Process a TDS 4.2 column names token. |
private void |
tds5DynamicToken()
Process TDS5 dynamic SQL aknowledgements. |
private void |
tds5ErrorToken()
Process a TDS 5 error or informational message. |
private void |
tds5ParamFmt2Token()
Process TDS 5 Sybase 12+ Dynamic results parameter descriptor. |
private void |
tds5ParamFmtToken()
Process TDS 5 Dynamic results parameter descriptors. |
private void |
tds5ParamsToken()
Process TDS 5.0 Params Token. |
private void |
tds5ResultToken()
Process a TDS 5.0 result set packet. |
private void |
tds5WideResultToken()
Process Sybase 12+ wide result token which provides enhanced column meta data. |
private static java.lang.String |
tds7CryptPass(java.lang.String pw)
A very poor man's "encryption". |
private void |
tds7ResultToken()
Process a TDS 7.0 result set token. |
private void |
tdsCapabilityToken()
Processes a TDS 5.0 capability token. |
private void |
tdsColumnInfoToken()
Process a column infomation token. |
private void |
tdsControlToken()
Process a control token (function unknown). |
private void |
tdsDoneToken()
Process a DONE, DONEINPROC or DONEPROC token. |
private void |
tdsEnvChangeToken()
Process an environment change packet. |
private void |
tdsErrorToken()
Process a TD4/TDS7 error or informational message. |
private void |
tdsInvalidToken()
Report unsupported TDS token in input stream. |
private void |
tdsLoginAckToken()
Process a login acknowledgement packet. |
private void |
tdsNtlmAuthToken()
Process a NTLM Authentication challenge. |
private void |
tdsOffsetsToken()
Process offsets token. |
private void |
tdsOrderByToken()
Process an order by token. |
private void |
tdsOutputParamToken()
Process output parameters. |
private void |
tdsProcIdToken()
Process procedure ID token. |
private void |
tdsReturnStatusToken()
Process stored procedure return status token. |
private void |
tdsRowToken()
Process a row data token. |
private void |
tdsTableNameToken()
Process a table name token. |
private void |
wait(int timeOut)
Waits for the first byte of the server response. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
public static final int MIN_PKT_SIZE
public static final int DEFAULT_MIN_PKT_SIZE_TDS70
public static final int MAX_PKT_SIZE
public static final int PKT_HDR_LEN
public static final byte QUERY_PKT
public static final byte LOGIN_PKT
public static final byte RPC_PKT
public static final byte REPLY_PKT
public static final byte CANCEL_PKT
public static final byte MSDTC_PKT
public static final byte SYBQUERY_PKT
public static final byte MSLOGIN_PKT
public static final byte NTLMAUTH_PKT
public static final byte PRELOGIN_PKT
public static final int SSL_ENCRYPT_LOGIN
public static final int SSL_CLIENT_FORCE_ENCRYPT
public static final int SSL_NO_ENCRYPT
public static final int SSL_SERVER_FORCE_ENCRYPT
private static final byte TDS5_PARAMFMT2_TOKEN
private static final byte TDS_LANG_TOKEN
private static final byte TDS5_WIDE_RESULT
private static final byte TDS_CLOSE_TOKEN
private static final byte TDS_OFFSETS_TOKEN
private static final byte TDS_RETURNSTATUS_TOKEN
private static final byte TDS_PROCID
private static final byte TDS7_RESULT_TOKEN
private static final byte TDS7_COMP_RESULT_TOKEN
private static final byte TDS_COLNAME_TOKEN
private static final byte TDS_COLFMT_TOKEN
private static final byte TDS_TABNAME_TOKEN
private static final byte TDS_COLINFO_TOKEN
private static final byte TDS_OPTIONCMD_TOKEN
private static final byte TDS_COMP_NAMES_TOKEN
private static final byte TDS_COMP_RESULT_TOKEN
private static final byte TDS_ORDER_TOKEN
private static final byte TDS_ERROR_TOKEN
private static final byte TDS_INFO_TOKEN
private static final byte TDS_PARAM_TOKEN
private static final byte TDS_LOGINACK_TOKEN
private static final byte TDS_CONTROL_TOKEN
private static final byte TDS_ROW_TOKEN
private static final byte TDS_ALTROW
private static final byte TDS5_PARAMS_TOKEN
private static final byte TDS_CAP_TOKEN
private static final byte TDS_ENVCHANGE_TOKEN
private static final byte TDS_MSG50_TOKEN
private static final byte TDS_DBRPC_TOKEN
private static final byte TDS5_DYNAMIC_TOKEN
private static final byte TDS5_PARAMFMT_TOKEN
private static final byte TDS_AUTH_TOKEN
private static final byte TDS_RESULT_TOKEN
private static final byte TDS_DONE_TOKEN
private static final byte TDS_DONEPROC_TOKEN
private static final byte TDS_DONEINPROC_TOKEN
private static final byte TDS_ENV_DATABASE
private static final byte TDS_ENV_LANG
private static final byte TDS_ENV_CHARSET
private static final byte TDS_ENV_PACKSIZE
private static final byte TDS_ENV_LCID
private static final byte TDS_ENV_SQLCOLLATION
private static final ParamInfo[] EMPTY_PARAMETER_INFO
getParameters() call
private static final byte DONE_MORE_RESULTS
private static final byte DONE_ERROR
private static final byte DONE_ROW_COUNT
static final byte DONE_CANCEL
private static final byte DONE_END_OF_RESPONSE
public static final int UNPREPARED
public static final int TEMPORARY_STORED_PROCEDURES
public static final int EXECUTE_SQL
public static final int PREPARE
static final int SYB_LONGDATA
static final int SYB_DATETIME
static final int SYB_BITNULL
static final int SYB_EXTCOLINFO
static final int SYB_UNICODE
static final int SYB_UNITEXT
static final int SYB_BIGINT
private static final int ASYNC_CANCEL
Statement.cancel().
private static final int TIMEOUT_CANCEL
private static java.util.HashMap tds8SpNames
private static java.lang.String hostName
private static SSPIJNIClient sspiJNIClient
private final ConnectionJDBC2 connection
private int tdsVersion
private final int serverType
private final SharedSocket socket
private final RequestStream out
private final ResponseStream in
private boolean endOfResponse
private boolean endOfResults
private ColInfo[] columns
private java.lang.Object[] rowData
private TdsCore.TableMetaData[] tables
private TdsCore.TdsToken currentToken
private java.lang.Integer returnStatus
private ParamInfo returnParam
private ParamInfo[] parameters
private int nextParam
private final SQLDiagnostic messages
private boolean isClosed
private boolean ntlmAuthSSO
private boolean fatalError
private Semaphore connectionLock
private boolean inBatch
private int sslMode
private boolean cancelPending
private final int[] cancelMonitor
cancelPending.
| Constructor Detail |
TdsCore(ConnectionJDBC2 connection, SQLDiagnostic messages)
connection - The connection which owns this object.messages - The SQLDiagnostic messages chain.| Method Detail |
private void checkOpen()
throws java.sql.SQLException
java.sql.SQLException - if the connection is closedint getTdsVersion()
int.ColInfo[] getColumns()
ColInfo[].void setColumns(ColInfo[] columns)
columns - the column descriptor arrayParamInfo[] getParameters()
ParamInfo[].java.lang.Object[] getRowData()
Object array
void negotiateSSL(java.lang.String instance,
java.lang.String ssl)
throws java.io.IOException,
java.sql.SQLException
instance - The server instance name.ssl - The SSL URL property value.
java.io.IOException
java.sql.SQLException
void login(java.lang.String serverName,
java.lang.String database,
java.lang.String user,
java.lang.String password,
java.lang.String domain,
java.lang.String charset,
java.lang.String appName,
java.lang.String progName,
java.lang.String wsid,
java.lang.String language,
java.lang.String macAddress,
int packetSize)
throws java.sql.SQLException
serverName - server host namedatabase - required databaseuser - user namepassword - user passworddomain - Windows NT domain (or null)charset - required server character setappName - application nameprogName - library namewsid - workstation IDlanguage - language to use for server messagesmacAddress - client network MAC addresspacketSize - required network packet size
java.sql.SQLException - if an error occurs
boolean getMoreResults()
throws java.sql.SQLException
boolean if the next item is a result set.
java.sql.SQLException - if an I/O or protocol error occurs; server errors
are queued up and not thrownboolean isResultSet()
boolean true if the next item is a result set.boolean isRowData()
boolean true if the next item is row data.boolean isUpdateCount()
boolean true if the next item is an update count.int getUpdateCount()
int.boolean isEndOfResponse()
boolean true if the response has been entirely consumed
void clearResponseQueue()
throws java.sql.SQLException
java.sql.SQLException - if an error occurs
void consumeOneResponse()
throws java.sql.SQLException
java.sql.SQLException - if an I/O or protocol error occurs; server errors
are queued up and not thrown
boolean getNextRow()
throws java.sql.SQLException
false if at the end of results, true
otherwise
java.sql.SQLException - if an I/O or protocol error occurs; server errors
are queued up and not thrown
boolean isDataInResultSet()
throws java.sql.SQLException
This does a quick read ahead and is needed to support the isLast() method in the ResultSet.
boolean - true if there is more data
in the result set.
java.sql.SQLExceptionjava.lang.Integer getReturnStatus()
Integer.void closeConnection()
Used by Sybase a no-op for Microsoft.
void close()
throws java.sql.SQLException
TdsCore connection object and associated streams.
java.sql.SQLExceptionvoid cancel(boolean timeout)
timeout - true if this is a query timeout cancel
void submitSQL(java.lang.String sql)
throws java.sql.SQLException
sql - the statement to execute
java.sql.SQLException - if an error is returned by the servervoid startBatch()
TdsCore that a batch is starting. This is so
that it knows to use sp_executesql for parameterized
queries (because there's no way to prepare a statement in the middle of
a batch).
Sets the inBatch flag.
void executeSQL(java.lang.String sql,
java.lang.String procName,
ParamInfo[] parameters,
boolean noMetaData,
int timeOut,
int maxRows,
int maxFieldSize,
boolean sendNow)
throws java.sql.SQLException
sql - SQL statement to executeprocName - stored procedure to execute or nullparameters - parameters for call or nullnoMetaData - suppress meta data for cursor callstimeOut - optional query timeout or 0maxRows - the maximum number of data rows to return (-1 to
leave unaltered)maxFieldSize - the maximum number of bytes in a column to return
(-1 to leave unaltered)sendNow - whether to send the request now or not
java.sql.SQLException - if an error occurs
java.lang.String microsoftPrepare(java.lang.String sql,
ParamInfo[] params,
boolean needCursor,
int resultSetType,
int resultSetConcurrency)
throws java.sql.SQLException
sql - the SQL statement to prepare.params - the actual parameter listneedCursor - true if a cursorprepare is requiredresultSetType - value of the resultSetType parameter when
the Statement was createdresultSetConcurrency - value of the resultSetConcurrency parameter
whenthe Statement was created
java.sql.SQLException
java.lang.String sybasePrepare(java.lang.String sql,
ParamInfo[] params)
throws java.sql.SQLException
sql - SQL statement to prepareparams - the actual parameter list
java.sql.SQLException - if an error occurs
void sybaseUnPrepare(java.lang.String procName)
throws java.sql.SQLException
procName - the temporary procedure name
java.sql.SQLException - if an error occurs
byte[] enlistConnection(int type,
byte[] oleTranID)
throws java.sql.SQLException
type - set to 0 to request TM address or 1 to enlist connectionoleTranID - the 40 OLE transaction ID
byte[] array containing the TM address data
java.sql.SQLException
java.sql.SQLException getBatchCounts(java.util.ArrayList counts,
java.sql.SQLException sqlEx)
throws java.sql.SQLException
SQLExceptions are chained
because there could be several errors reported in a batch.
counts - the ArrayList containing the update countssqlEx - any previous SQLException(s) encountered
SQLException or null if no
error has yet occurred
java.sql.SQLException - if the connection is closed
private void putLoginString(java.lang.String txt,
int len)
throws java.io.IOException
java.io.IOException
private void sendPreLoginPacket(java.lang.String instance,
boolean forceEncryption)
throws java.io.IOException
Packet contains; netlib version, ssl mode, instance and process ID.
instance - forceEncryption -
java.io.IOException
private int readPreLoginPacket()
throws java.io.IOException
Packet contains; server version no, SSL mode, instance name and process id.
Server returns the following values for SSL mode:
java.io.IOException
private void send42LoginPkt(java.lang.String serverName,
java.lang.String user,
java.lang.String password,
java.lang.String charset,
java.lang.String appName,
java.lang.String progName,
java.lang.String wsid,
java.lang.String language,
int packetSize)
throws java.io.IOException
serverName - server host nameuser - user namepassword - user passwordcharset - required server character setappName - application nameprogName - program namewsid - workstation IDlanguage - server language for messagespacketSize - required network packet size
java.io.IOException - if an I/O error occurs
private void send50LoginPkt(java.lang.String serverName,
java.lang.String user,
java.lang.String password,
java.lang.String charset,
java.lang.String appName,
java.lang.String progName,
java.lang.String wsid,
java.lang.String language,
int packetSize)
throws java.io.IOException
serverName - server host nameuser - user namepassword - user passwordcharset - required server character setappName - application nameprogName - library namewsid - workstation IDlanguage - server language for messagespacketSize - required network packet size
java.io.IOException - if an I/O error occurs
private void sendMSLoginPkt(java.lang.String serverName,
java.lang.String database,
java.lang.String user,
java.lang.String password,
java.lang.String domain,
java.lang.String appName,
java.lang.String progName,
java.lang.String wsid,
java.lang.String language,
java.lang.String macAddress,
int netPacketSize)
throws java.io.IOException,
java.sql.SQLException
This method incorporates the Windows single sign on code contributed by
Magendran Sathaiah. To invoke single sign on just leave the user name
blank or null. NB. This can only work if the driver is being executed on
a Windows PC and ntlmauth.dll is on the path.
serverName - server host namedatabase - required databaseuser - user namepassword - user passworddomain - Windows NT domain (or null)appName - application nameprogName - program namewsid - workstation IDlanguage - server language for messagesmacAddress - client network MAC addressnetPacketSize - TDS packet size to use
java.io.IOException - if an I/O error occurs
java.sql.SQLException
private void sendNtlmChallengeResponse(byte[] nonce,
java.lang.String user,
java.lang.String password,
java.lang.String domain)
throws java.io.IOException
nonce - The secret to hash with password.user - The user name.password - The user password.domain - The Windows NT Dommain.
java.io.IOException
private void nextToken()
throws java.sql.SQLException
java.sql.SQLException - if an I/O or protocol error occurs
private void tdsInvalidToken()
throws java.io.IOException,
ProtocolException
java.io.IOException
ProtocolException
private void tds5ParamFmt2Token()
throws java.io.IOException,
ProtocolException
When returning output parameters this token will be followed by a TDS5_PARAMS_TOKEN with the actual data.
java.io.IOException
ProtocolException
private void tds5WideResultToken()
throws java.io.IOException,
ProtocolException
java.io.IOException
ProtocolException
private void tdsReturnStatusToken()
throws java.io.IOException,
java.sql.SQLException
java.io.IOException
java.sql.SQLException
private void tdsProcIdToken()
throws java.io.IOException
Used by DBLIB to obtain the object id of a stored procedure.
java.io.IOException
private void tdsOffsetsToken()
throws java.io.IOException
Used by DBLIB to return the offset of various keywords in a statement.
This saves the client from having to parse a SQL statement. Enabled with
"set offsets from on".
java.io.IOException
private void tds7ResultToken()
throws java.io.IOException,
ProtocolException,
java.sql.SQLException
java.io.IOException
ProtocolException
java.sql.SQLException
private void tds4ColNamesToken()
throws java.io.IOException
Note: Will be followed by a COL_FMT token.
java.io.IOException
private void tds4ColFormatToken()
throws java.io.IOException,
ProtocolException
java.io.IOException
ProtocolException
private void tdsTableNameToken()
throws java.io.IOException,
ProtocolException
Sent by select for browse or cursor functions.
java.io.IOException
ProtocolException
private void tdsColumnInfoToken()
throws java.io.IOException,
ProtocolException
Sent by select for browse or cursor functions.
java.io.IOException
ProtocolException
private void tdsOrderByToken()
throws java.io.IOException
Sent to describe columns in an order by clause.
java.io.IOException
private void tdsErrorToken()
throws java.io.IOException
java.io.IOException
private void tdsOutputParamToken()
throws java.io.IOException,
ProtocolException,
java.sql.SQLException
java.io.IOException
ProtocolException
java.sql.SQLException
private void tdsLoginAckToken()
throws java.io.IOException
java.io.IOException
private void tdsControlToken()
throws java.io.IOException
java.io.IOException
private void tdsRowToken()
throws java.io.IOException,
ProtocolException
java.io.IOException
ProtocolException
private void tds5ParamsToken()
throws java.io.IOException,
ProtocolException,
java.sql.SQLException
The type of the preceding token is inspected to determine if this packet contains output parameter result data. A TDS5_PARAMFMT2_TOKEN is sent before this one in Sybase 12 to introduce output parameter results. A TDS5_PARAMFMT_TOKEN is sent before this one to introduce extended error information.
java.io.IOException
ProtocolException
java.sql.SQLException
private void tdsCapabilityToken()
throws java.io.IOException,
ProtocolException
Sent after login to describe the server's capabilities.
java.io.IOException - if an I/O error occurs
ProtocolException
private void tdsEnvChangeToken()
throws java.io.IOException,
java.sql.SQLException
java.io.IOException
java.sql.SQLException
private void tds5ErrorToken()
throws java.io.IOException
java.io.IOException
private void tds5DynamicToken()
throws java.io.IOException
java.io.IOException
private void tds5ParamFmtToken()
throws java.io.IOException,
ProtocolException
With Sybase 12+ this has been superseded by the TDS5_PARAMFMT2_TOKEN except when used to return extended error information.
java.io.IOException
ProtocolException
private void tdsNtlmAuthToken()
throws java.io.IOException,
ProtocolException
java.io.IOException
ProtocolException
private static int getIntFromBuffer(byte[] buf,
int offset)
private static int getShortFromBuffer(byte[] buf,
int offset)
private void tds5ResultToken()
throws java.io.IOException,
ProtocolException
java.io.IOException
ProtocolException
private void tdsDoneToken()
throws java.io.IOException
java.io.IOException
private void executeSQL42(java.lang.String sql,
java.lang.String procName,
ParamInfo[] parameters,
boolean noMetaData,
boolean sendNow)
throws java.io.IOException,
java.sql.SQLException
sql - The SQL statement to execute.procName - Stored procedure to execute or null.parameters - Parameters for call or null.noMetaData - Suppress meta data for cursor calls.
java.sql.SQLException
java.io.IOException
private void executeSQL50(java.lang.String sql,
java.lang.String procName,
ParamInfo[] parameters)
throws java.io.IOException,
java.sql.SQLException
sql - The SQL statement to execute.procName - Stored procedure to execute or null.parameters - Parameters for call or null.
java.sql.SQLException
java.io.IOExceptionpublic static boolean isPreparedProcedureName(java.lang.String procName)
true if the specified procName
is a sp_prepare or sp_prepexec handle; returns false
otherwise.
procName - Stored procedure to execute or null.
true if the specified procName
is a sp_prepare or sp_prepexec handle; false
otherwise.
private void executeSQL70(java.lang.String sql,
java.lang.String procName,
ParamInfo[] parameters,
boolean noMetaData,
boolean sendNow)
throws java.io.IOException,
java.sql.SQLException
sql - The SQL statement to execute.procName - Stored procedure to execute or null.parameters - Parameters for call or null.noMetaData - Suppress meta data for cursor calls.
java.sql.SQLException
java.io.IOException
private void setRowCountAndTextSize(int rowCount,
int textSize)
throws java.sql.SQLException
rowCount - the number of rows to return or 0 for no limit or -1 to
leave as istextSize - the maximum number of bytes in a TEXT column to return
or -1 to leave as is
java.sql.SQLException - if an error is returned by the server
private void wait(int timeOut)
throws java.io.IOException,
java.sql.SQLException
timeOut - the timeout period in seconds or 0
java.io.IOException
java.sql.SQLExceptionpublic void cleanUp()
TdsCore is cached for reuse.
public SQLDiagnostic getMessages()
private static byte[] getMACAddress(java.lang.String macString)
macString - the MAC address as a hex string
byte[]private static java.lang.String getHostName()
private static java.lang.String tds7CryptPass(java.lang.String pw)
pw - password to encrypt
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.JtdsResultSet
net.sourceforge.jtds.jdbc.CachedResultSet
A memory cached scrollable/updateable result set.
Notes:
| Field Summary | |
protected ConnectionJDBC2 |
connection
The parent connection object |
protected TdsCore |
cursorTds
Cursor TdsCore object. |
protected int |
initialRowCnt
The row count of the initial result set. |
protected ParamInfo[] |
insertRow
Buffer row used for inserts. |
protected boolean |
isKeyed
Table is keyed. |
protected boolean |
isSybase
Flag to indicate Sybase. |
protected boolean |
onInsertRow
Indicates currently inserting. |
protected ParamInfo[] |
procedureParams
Original parameters. |
protected java.lang.String |
procName
Original procedure name. |
protected boolean |
rowDeleted
Indicates that row has been deleted. |
protected boolean |
rowUpdated
Indicates that row has been updated. |
protected boolean |
sizeChanged
Fetch size has been changed. |
protected java.lang.String |
sql
Original SQL statement. |
protected java.lang.String |
tableName
First table name in select. |
protected boolean |
tempResultSet
True if this is a local temporary result set. |
protected ParamInfo[] |
updateRow
The "update" row. |
protected TdsCore |
updateTds
Updates TdsCore object used for positioned updates. |
| Fields inherited from class net.sourceforge.jtds.jdbc.JtdsResultSet |
cancelled, CLOSE_CURSORS_AT_COMMIT, closed, columnCount, columns, concurrency, currentRow, cursorName, direction, fetchDirection, fetchSize, HOLD_CURSORS_OVER_COMMIT, INITIAL_ROW_COUNT, pos, POS_AFTER_LAST, POS_BEFORE_FIRST, resultSetType, rowData, rowPtr, rowsInResult, statement, wasNull |
| Fields inherited from interface java.sql.ResultSet |
CONCUR_READ_ONLY, CONCUR_UPDATABLE, FETCH_FORWARD, FETCH_REVERSE, FETCH_UNKNOWN, TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, TYPE_SCROLL_SENSITIVE |
| Constructor Summary | |
(package private) |
CachedResultSet(JtdsResultSet rs,
boolean load)
Creates a cached result set with the same columns (and optionally data) as an existing result set. |
(package private) |
CachedResultSet(JtdsStatement statement,
ColInfo[] columns,
java.lang.Object[] data)
Creates a cached result set containing one row. |
(package private) |
CachedResultSet(JtdsStatement statement,
java.lang.String[] colName,
int[] colType)
Constructs a cached result set based on locally generated data. |
(package private) |
CachedResultSet(JtdsStatement statement,
java.lang.String sql,
java.lang.String procName,
ParamInfo[] procedureParams,
int resultSetType,
int concurrency)
Constructs a new cached result set. |
| Method Summary | |
boolean |
absolute(int row)
|
void |
afterLast()
|
void |
beforeFirst()
|
protected static ParamInfo |
buildParameter(int pos,
ColInfo info,
java.lang.Object value,
boolean isUnicode)
Creates a parameter object for an UPDATE, DELETE or INSERT statement. |
(package private) ParamInfo[] |
buildWhereClause(java.lang.StringBuffer sql,
java.util.ArrayList params,
boolean select)
Builds a WHERE clause for UPDATE or DELETE statements. |
void |
cancelRowUpdates()
|
void |
close()
|
private void |
cursorClose()
Closes the result set. |
private void |
cursorCreate()
Creates a new scrollable result set in memory or a named server cursor. |
private boolean |
cursorFetch(int rowNum)
Fetches the next result row from the internal row array. |
void |
deleteRow()
|
boolean |
first()
|
java.lang.String |
getCursorName()
|
void |
insertRow()
|
(package private) boolean |
isCursorUpdateable()
Analyses the tables in the result set and determines if the primary key columns needed to make it updateable exist. |
boolean |
isLast()
|
boolean |
last()
|
void |
moveToCurrentRow()
|
void |
moveToInsertRow()
|
boolean |
next()
|
boolean |
previous()
|
protected void |
refreshKeyedRows()
Refreshes a result set row from keyed tables. |
protected void |
refreshReRead()
Refreshes the row by rereading the result set. |
void |
refreshRow()
|
boolean |
relative(int row)
|
boolean |
rowDeleted()
|
boolean |
rowInserted()
|
boolean |
rowUpdated()
|
protected java.lang.Object |
setColValue(int colIndex,
int jdbcType,
java.lang.Object value,
int length)
Sets the specified column's data value. |
(package private) void |
setConcurrency(int concurrency)
Modify the concurrency of the result set. |
void |
setFetchSize(int size)
|
void |
updateRow()
|
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
protected boolean onInsertRow
protected ParamInfo[] insertRow
protected ParamInfo[] updateRow
protected boolean rowUpdated
protected boolean rowDeleted
protected int initialRowCnt
protected final boolean tempResultSet
protected final TdsCore cursorTds
protected final TdsCore updateTds
protected boolean isSybase
protected boolean sizeChanged
protected java.lang.String sql
protected final java.lang.String procName
protected final ParamInfo[] procedureParams
protected boolean isKeyed
protected java.lang.String tableName
protected ConnectionJDBC2 connection
| Constructor Detail |
CachedResultSet(JtdsStatement statement, java.lang.String sql, java.lang.String procName, ParamInfo[] procedureParams, int resultSetType, int concurrency) throws java.sql.SQLException
statement - the parent statement objectsql - the SQL statement used to build the result setprocName - an optional stored procedure nameprocedureParams - parameters for prepared statementsresultSetType - the result set type eg scrollableconcurrency - the result set concurrency eg updateable
java.sql.SQLException - if an error occursCachedResultSet(JtdsStatement statement, java.lang.String[] colName, int[] colType) throws java.sql.SQLException
statement - the parent statement objectcolName - array of column namescolType - array of corresponding data types
java.sql.SQLException - if an error occursCachedResultSet(JtdsResultSet rs, boolean load) throws java.sql.SQLException
rs - the result set to copyload - load data from the supplied result set
java.sql.SQLException - if an error occursCachedResultSet(JtdsStatement statement, ColInfo[] columns, java.lang.Object[] data) throws java.sql.SQLException
statement - the parent statement objectcolumns - the column descriptor arraydata - the row data
java.sql.SQLException - if an error occurs| Method Detail |
void setConcurrency(int concurrency)
concurrency - the concurrency value eg
ResultSet.CONCUR_READ_ONLY
private void cursorCreate()
throws java.sql.SQLException
java.sql.SQLException - if an error occurs
boolean isCursorUpdateable()
throws java.sql.SQLException
true if there is one table and it is keyed
- Throws:
java.sql.SQLException
private boolean cursorFetch(int rowNum)
throws java.sql.SQLException
rowNum - the row number to fetch
true if a result set row is returned
java.sql.SQLException - if an error occurs
private void cursorClose()
throws java.sql.SQLException
java.sql.SQLExceptionprotected static ParamInfo buildParameter(int pos, ColInfo info, java.lang.Object value, boolean isUnicode) throws java.sql.SQLException
pos - the substitution position of the parameter marker in the SQLinfo - the ColInfo column descriptorvalue - the column data item
ParamInfo object
java.sql.SQLException
protected java.lang.Object setColValue(int colIndex,
int jdbcType,
java.lang.Object value,
int length)
throws java.sql.SQLException
setColValue in class JtdsResultSetcolIndex - index of the columnvalue - new column valuelength - the length of a stream parameter
java.sql.SQLExceptionParamInfo[] buildWhereClause(java.lang.StringBuffer sql, java.util.ArrayList params, boolean select) throws java.sql.SQLException
sql - the SQL Statement to append the WHERE clause toparams - the parameter descriptor array for this statementselect - true if this WHERE clause will be used in a select
statement
ParamInfo[]
java.sql.SQLException - if an error occurs
protected void refreshKeyedRows()
throws java.sql.SQLException
java.sql.SQLException - if an error occurs
protected void refreshReRead()
throws java.sql.SQLException
java.sql.SQLException
public void setFetchSize(int size)
throws java.sql.SQLException
setFetchSize in interface java.sql.ResultSetsetFetchSize in class JtdsResultSetjava.sql.SQLException
public void afterLast()
throws java.sql.SQLException
afterLast in interface java.sql.ResultSetafterLast in class JtdsResultSetjava.sql.SQLException
public void beforeFirst()
throws java.sql.SQLException
beforeFirst in interface java.sql.ResultSetbeforeFirst in class JtdsResultSetjava.sql.SQLException
public void cancelRowUpdates()
throws java.sql.SQLException
cancelRowUpdates in interface java.sql.ResultSetcancelRowUpdates in class JtdsResultSetjava.sql.SQLException
public void close()
throws java.sql.SQLException
close in interface java.sql.ResultSetclose in class JtdsResultSetjava.sql.SQLException
public void deleteRow()
throws java.sql.SQLException
deleteRow in interface java.sql.ResultSetdeleteRow in class JtdsResultSetjava.sql.SQLException
public void insertRow()
throws java.sql.SQLException
insertRow in interface java.sql.ResultSetinsertRow in class JtdsResultSetjava.sql.SQLException
public void moveToCurrentRow()
throws java.sql.SQLException
moveToCurrentRow in interface java.sql.ResultSetmoveToCurrentRow in class JtdsResultSetjava.sql.SQLException
public void moveToInsertRow()
throws java.sql.SQLException
moveToInsertRow in interface java.sql.ResultSetmoveToInsertRow in class JtdsResultSetjava.sql.SQLException
public void refreshRow()
throws java.sql.SQLException
refreshRow in interface java.sql.ResultSetrefreshRow in class JtdsResultSetjava.sql.SQLException
public void updateRow()
throws java.sql.SQLException
updateRow in interface java.sql.ResultSetupdateRow in class JtdsResultSetjava.sql.SQLException
public boolean first()
throws java.sql.SQLException
first in interface java.sql.ResultSetfirst in class JtdsResultSetjava.sql.SQLException
public boolean isLast()
throws java.sql.SQLException
isLast in interface java.sql.ResultSetisLast in class JtdsResultSetjava.sql.SQLException
public boolean last()
throws java.sql.SQLException
last in interface java.sql.ResultSetlast in class JtdsResultSetjava.sql.SQLException
public boolean next()
throws java.sql.SQLException
next in interface java.sql.ResultSetnext in class JtdsResultSetjava.sql.SQLException
public boolean previous()
throws java.sql.SQLException
previous in interface java.sql.ResultSetprevious in class JtdsResultSetjava.sql.SQLException
public boolean rowDeleted()
throws java.sql.SQLException
rowDeleted in interface java.sql.ResultSetrowDeleted in class JtdsResultSetjava.sql.SQLException
public boolean rowInserted()
throws java.sql.SQLException
rowInserted in interface java.sql.ResultSetrowInserted in class JtdsResultSetjava.sql.SQLException
public boolean rowUpdated()
throws java.sql.SQLException
rowUpdated in interface java.sql.ResultSetrowUpdated in class JtdsResultSetjava.sql.SQLException
public boolean absolute(int row)
throws java.sql.SQLException
absolute in interface java.sql.ResultSetabsolute in class JtdsResultSetjava.sql.SQLException
public boolean relative(int row)
throws java.sql.SQLException
relative in interface java.sql.ResultSetrelative in class JtdsResultSetjava.sql.SQLException
public java.lang.String getCursorName()
throws java.sql.SQLException
getCursorName in interface java.sql.ResultSetgetCursorName in class JtdsResultSetjava.sql.SQLException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.TypeInfo
Represents an SQL data type as required by getTypeInfo().
Provides a suitable natural ordering.
| Field Summary | |
private boolean |
autoIncrement
|
private boolean |
caseSensitive
|
private java.lang.String |
createParams
|
private int |
dataType
|
private int |
distanceFromJdbcType
|
private boolean |
fixedPrecScale
|
private java.lang.String |
literalPrefix
|
private java.lang.String |
literalSuffix
|
private java.lang.String |
localTypeName
|
private short |
maximumScale
|
private short |
minimumScale
|
private int |
normalizedType
|
private short |
nullable
|
(package private) static int |
NUM_COLS
|
private int |
numPrecRadix
|
private int |
precision
|
private short |
searchable
|
private int |
sqlDataType
|
private int |
sqlDatetimeSub
|
private java.lang.String |
typeName
|
private boolean |
unsigned
|
| Constructor Summary | |
TypeInfo(java.sql.ResultSet rs,
boolean useLOBs)
|
|
TypeInfo(java.lang.String typeName,
int dataType,
boolean autoIncrement)
For testing only. |
|
| Method Summary | |
private int |
compare(int i1,
int i2)
|
int |
compareTo(java.lang.Object o)
Comparable implementation that orders by dataType, then by how closely the data type maps to the corresponding JDBC SQL type. |
private int |
determineDistanceFromJdbcType()
Determine how close this type is to the corresponding JDBC type. |
boolean |
equals(java.lang.Object o)
|
int |
hashCode()
|
static int |
normalizeDataType(int serverDataType,
boolean useLOBs)
Return a Types-defined type for an SQL Server specific data type. |
java.lang.String |
toString()
|
void |
update(java.sql.ResultSet rs)
|
| Methods inherited from class java.lang.Object |
clone, finalize, getClass, notify, notifyAll, wait, wait, wait |
| Field Detail |
static final int NUM_COLS
private final java.lang.String typeName
private final int dataType
private final int precision
private final java.lang.String literalPrefix
private final java.lang.String literalSuffix
private final java.lang.String createParams
private final short nullable
private final boolean caseSensitive
private final short searchable
private final boolean unsigned
private final boolean fixedPrecScale
private final boolean autoIncrement
private final java.lang.String localTypeName
private final short minimumScale
private final short maximumScale
private final int sqlDataType
private final int sqlDatetimeSub
private final int numPrecRadix
private final int normalizedType
private final int distanceFromJdbcType
| Constructor Detail |
public TypeInfo(java.sql.ResultSet rs,
boolean useLOBs)
throws java.sql.SQLException
public TypeInfo(java.lang.String typeName,
int dataType,
boolean autoIncrement)
compareTo() method (set name, type, and auto
increment).
| Method Detail |
public boolean equals(java.lang.Object o)
public int hashCode()
public java.lang.String toString()
public void update(java.sql.ResultSet rs)
throws java.sql.SQLException
java.sql.SQLExceptionpublic int compareTo(java.lang.Object o)
compareTo in interface java.lang.Comparable
private int compare(int i1,
int i2)
private int determineDistanceFromJdbcType()
normalizedType value.
public static int normalizeDataType(int serverDataType,
boolean useLOBs)
Types-defined type for an SQL Server specific data type.
serverDataType - the data type, as returned by the serveruseLOBs - whether LOB data types are used for large types
java.sql.Types
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.JtdsStatement
net.sourceforge.jtds.jdbc.JtdsPreparedStatement
jTDS implementation of the java.sql.PreparedStatement interface.
Implementation notes:
| Field Summary | |
private static java.text.NumberFormat |
f
Used to format numeric values when scale is specified. |
(package private) java.util.Collection |
handles
Collection of handles used by this statement |
private java.lang.String |
originalSql
The original SQL statement provided at construction time. |
protected ParamInfo[] |
parameters
The parameter list for the call. |
protected ParamInfo[] |
paramMetaData
The cached parameter meta data. |
protected java.lang.String |
procName
The procedure name for CallableStatements. |
private boolean |
returnKeys
True to return generated keys. |
protected java.lang.String |
sql
The SQL statement being prepared. |
protected java.lang.String |
sqlWord
The first SQL keyword in the SQL string. |
| Fields inherited from class net.sourceforge.jtds.jdbc.JtdsStatement |
batchValues, BOOLEAN, CLOSE_ALL_RESULTS, CLOSE_CURRENT_RESULT, closed, colMetaData, connection, currentResult, cursorName, DATALINK, DEFAULT_FETCH_SIZE, escapeProcessing, EXECUTE_FAILED, fetchDirection, fetchSize, genKeyResultSet, KEEP_CURRENT_RESULT, maxFieldSize, maxRows, messages, NO_GENERATED_KEYS, openResultSets, queryTimeout, resultQueue, resultSetConcurrency, resultSetType, RETURN_GENERATED_KEYS, SUCCESS_NO_INFO, tds |
| Fields inherited from interface java.sql.Statement |
CLOSE_ALL_RESULTS, CLOSE_CURRENT_RESULT, EXECUTE_FAILED, KEEP_CURRENT_RESULT, NO_GENERATED_KEYS, RETURN_GENERATED_KEYS, SUCCESS_NO_INFO |
| Constructor Summary | |
(package private) |
JtdsPreparedStatement(ConnectionJDBC2 connection,
java.lang.String sql,
int resultSetType,
int concurrency,
boolean returnKeys)
Construct a new preparedStatement object. |
| Method Summary | |
void |
addBatch()
|
void |
addBatch(java.lang.String sql)
|
protected void |
checkOpen()
Check that this statement is still open. |
void |
clearParameters()
|
void |
close()
|
boolean |
execute()
|
boolean |
execute(java.lang.String sql)
|
boolean |
execute(java.lang.String arg0,
int arg1)
|
boolean |
execute(java.lang.String arg0,
int[] arg1)
|
boolean |
execute(java.lang.String arg0,
java.lang.String[] arg1)
|
protected java.sql.SQLException |
executeMSBatch(int size,
int executeSize,
java.util.ArrayList counts)
Execute the SQL batch on a MS server. |
java.sql.ResultSet |
executeQuery()
|
java.sql.ResultSet |
executeQuery(java.lang.String sql)
|
protected java.sql.SQLException |
executeSybaseBatch(int size,
int executeSize,
java.util.ArrayList counts)
Execute the SQL batch on a Sybase server. |
int |
executeUpdate()
|
int |
executeUpdate(java.lang.String sql)
|
int |
executeUpdate(java.lang.String sql,
int getKeys)
|
int |
executeUpdate(java.lang.String arg0,
int[] arg1)
|
int |
executeUpdate(java.lang.String arg0,
java.lang.String[] arg1)
|
java.sql.ResultSetMetaData |
getMetaData()
|
protected ParamInfo |
getParameter(int parameterIndex)
Check the supplied index and return the selected parameter. |
java.sql.ParameterMetaData |
getParameterMetaData()
|
protected static java.lang.String |
normalizeCall(java.lang.String sql)
This method converts native call syntax into (hopefully) valid JDBC escape syntax. |
protected void |
notSupported(java.lang.String method)
Report that user tried to call a method not supported on this type of statement. |
void |
setArray(int arg0,
java.sql.Array arg1)
|
void |
setAsciiStream(int parameterIndex,
java.io.InputStream inputStream,
int length)
|
void |
setBigDecimal(int parameterIndex,
java.math.BigDecimal x)
|
void |
setBinaryStream(int parameterIndex,
java.io.InputStream x,
int length)
|
void |
setBlob(int parameterIndex,
java.sql.Blob x)
|
void |
setBoolean(int parameterIndex,
boolean x)
|
void |
setByte(int parameterIndex,
byte x)
|
void |
setBytes(int parameterIndex,
byte[] x)
|
void |
setCharacterStream(int parameterIndex,
java.io.Reader reader,
int length)
|
void |
setClob(int parameterIndex,
java.sql.Clob x)
|
(package private) void |
setColMetaData(ColInfo[] value)
Update the cached column meta data information. |
void |
setDate(int parameterIndex,
java.sql.Date x)
|
void |
setDate(int parameterIndex,
java.sql.Date x,
java.util.Calendar cal)
|
void |
setDouble(int parameterIndex,
double x)
|
void |
setFloat(int parameterIndex,
float x)
|
void |
setInt(int parameterIndex,
int x)
|
void |
setLong(int parameterIndex,
long x)
|
void |
setNull(int parameterIndex,
int sqlType)
|
void |
setNull(int parameterIndex,
int sqlType,
java.lang.String typeName)
|
void |
setObject(int parameterIndex,
java.lang.Object x)
|
void |
setObject(int parameterIndex,
java.lang.Object x,
int targetSqlType)
|
void |
setObject(int parameterIndex,
java.lang.Object x,
int targetSqlType,
int scale)
|
void |
setObjectBase(int parameterIndex,
java.lang.Object x,
int targetSqlType,
int scale)
Generic setObject method. |
protected void |
setParameter(int parameterIndex,
java.lang.Object x,
int targetSqlType,
int scale,
int length)
Update the ParamInfo object for the specified parameter. |
(package private) void |
setParamMetaData(ParamInfo[] value)
Update the cached parameter meta data information. |
void |
setRef(int parameterIndex,
java.sql.Ref x)
|
void |
setShort(int parameterIndex,
short x)
|
void |
setString(int parameterIndex,
java.lang.String x)
|
void |
setTime(int parameterIndex,
java.sql.Time x)
|
void |
setTime(int parameterIndex,
java.sql.Time x,
java.util.Calendar cal)
|
void |
setTimestamp(int parameterIndex,
java.sql.Timestamp x)
|
void |
setTimestamp(int parameterIndex,
java.sql.Timestamp x,
java.util.Calendar cal)
|
void |
setUnicodeStream(int parameterIndex,
java.io.InputStream inputStream,
int length)
|
void |
setURL(int parameterIndex,
java.net.URL url)
|
java.lang.String |
toString()
Returns the SQL command provided at construction time. |
| Methods inherited from class java.lang.Object |
clone, equals, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Methods inherited from interface java.sql.Statement |
cancel, clearBatch, clearWarnings, executeBatch, getConnection, getFetchDirection, getFetchSize, getGeneratedKeys, getMaxFieldSize, getMaxRows, getMoreResults, getMoreResults, getQueryTimeout, getResultSet, getResultSetConcurrency, getResultSetHoldability, getResultSetType, getUpdateCount, getWarnings, setCursorName, setEscapeProcessing, setFetchDirection, setFetchSize, setMaxFieldSize, setMaxRows, setQueryTimeout |
| Field Detail |
protected final java.lang.String sql
private final java.lang.String originalSql
protected java.lang.String sqlWord
protected java.lang.String procName
protected ParamInfo[] parameters
private boolean returnKeys
protected ParamInfo[] paramMetaData
private static final java.text.NumberFormat f
java.util.Collection handles
| Constructor Detail |
JtdsPreparedStatement(ConnectionJDBC2 connection, java.lang.String sql, int resultSetType, int concurrency, boolean returnKeys) throws java.sql.SQLException
connection - The parent connection.sql - The SQL statement to prepare.resultSetType - The result set type eg SCROLLABLE etc.concurrency - The result set concurrency eg READONLY.returnKeys - True if generated keys should be returned.
java.sql.SQLException| Method Detail |
public java.lang.String toString()
protected static java.lang.String normalizeCall(java.lang.String sql)
sql - the SQL statement to process
protected void checkOpen()
throws java.sql.SQLException
checkOpen in class JtdsStatementjava.sql.SQLException - if statement closed.
protected void notSupported(java.lang.String method)
throws java.sql.SQLException
method - The method name to report in the error message.
java.sql.SQLException
protected java.sql.SQLException executeMSBatch(int size,
int executeSize,
java.util.ArrayList counts)
throws java.sql.SQLException
prepareSQL=1 or 3, the driver will first prepare temporary stored
procedures or statements for each parameter combination found in the batch. The handles to these pre-preared
statements will then be used to execute the actual batch statements.
executeMSBatch in class JtdsStatementsize - the total size of the batchexecuteSize - the maximum number of statements to send in one requestcounts - the returned update counts
SQLException
java.sql.SQLException - if a serious error occurs during execution
protected java.sql.SQLException executeSybaseBatch(int size,
int executeSize,
java.util.ArrayList counts)
throws java.sql.SQLException
CallableStatements.
executeSybaseBatch in class JtdsStatementsize - the total size of the batchexecuteSize - the maximum number of statements to send in one requestcounts - the returned update counts
SQLException
java.sql.SQLException - if a serious error occurs during executionprotected ParamInfo getParameter(int parameterIndex) throws java.sql.SQLException
parameterIndex - the parameter index 1 to n.
ParamInfo object.
java.sql.SQLException - if the statement is closed;
if parameterIndex is less than 0;
if parameterIndex is greater than the
number of parameters;
if checkIfSet was true
and the parameter was not set
public void setObjectBase(int parameterIndex,
java.lang.Object x,
int targetSqlType,
int scale)
throws java.sql.SQLException
parameterIndex - Parameter index 1 to n.x - The value to set.targetSqlType - The java.sql.Types constant describing the data.scale - The decimal scale -1 if not set.
java.sql.SQLException
protected void setParameter(int parameterIndex,
java.lang.Object x,
int targetSqlType,
int scale,
int length)
throws java.sql.SQLException
parameterIndex - Parameter index 1 to n.x - The value to set.targetSqlType - The java.sql.Types constant describing the data.scale - The decimal scale -1 if not set.length - The length of the data item.
java.sql.SQLExceptionvoid setColMetaData(ColInfo[] value)
value - The Column meta data array.void setParamMetaData(ParamInfo[] value)
value - The Column meta data array.
public void close()
throws java.sql.SQLException
close in interface java.sql.Statementclose in class JtdsStatementjava.sql.SQLException
public int executeUpdate()
throws java.sql.SQLException
executeUpdate in interface java.sql.PreparedStatementjava.sql.SQLException
public void addBatch()
throws java.sql.SQLException
addBatch in interface java.sql.PreparedStatementjava.sql.SQLException
public void clearParameters()
throws java.sql.SQLException
clearParameters in interface java.sql.PreparedStatementjava.sql.SQLException
public boolean execute()
throws java.sql.SQLException
execute in interface java.sql.PreparedStatementjava.sql.SQLException
public void setByte(int parameterIndex,
byte x)
throws java.sql.SQLException
setByte in interface java.sql.PreparedStatementjava.sql.SQLException
public void setDouble(int parameterIndex,
double x)
throws java.sql.SQLException
setDouble in interface java.sql.PreparedStatementjava.sql.SQLException
public void setFloat(int parameterIndex,
float x)
throws java.sql.SQLException
setFloat in interface java.sql.PreparedStatementjava.sql.SQLException
public void setInt(int parameterIndex,
int x)
throws java.sql.SQLException
setInt in interface java.sql.PreparedStatementjava.sql.SQLException
public void setNull(int parameterIndex,
int sqlType)
throws java.sql.SQLException
setNull in interface java.sql.PreparedStatementjava.sql.SQLException
public void setLong(int parameterIndex,
long x)
throws java.sql.SQLException
setLong in interface java.sql.PreparedStatementjava.sql.SQLException
public void setShort(int parameterIndex,
short x)
throws java.sql.SQLException
setShort in interface java.sql.PreparedStatementjava.sql.SQLException
public void setBoolean(int parameterIndex,
boolean x)
throws java.sql.SQLException
setBoolean in interface java.sql.PreparedStatementjava.sql.SQLException
public void setBytes(int parameterIndex,
byte[] x)
throws java.sql.SQLException
setBytes in interface java.sql.PreparedStatementjava.sql.SQLException
public void setAsciiStream(int parameterIndex,
java.io.InputStream inputStream,
int length)
throws java.sql.SQLException
setAsciiStream in interface java.sql.PreparedStatementjava.sql.SQLException
public void setBinaryStream(int parameterIndex,
java.io.InputStream x,
int length)
throws java.sql.SQLException
setBinaryStream in interface java.sql.PreparedStatementjava.sql.SQLException
public void setUnicodeStream(int parameterIndex,
java.io.InputStream inputStream,
int length)
throws java.sql.SQLException
setUnicodeStream in interface java.sql.PreparedStatementjava.sql.SQLException
public void setCharacterStream(int parameterIndex,
java.io.Reader reader,
int length)
throws java.sql.SQLException
setCharacterStream in interface java.sql.PreparedStatementjava.sql.SQLException
public void setObject(int parameterIndex,
java.lang.Object x)
throws java.sql.SQLException
setObject in interface java.sql.PreparedStatementjava.sql.SQLException
public void setObject(int parameterIndex,
java.lang.Object x,
int targetSqlType)
throws java.sql.SQLException
setObject in interface java.sql.PreparedStatementjava.sql.SQLException
public void setObject(int parameterIndex,
java.lang.Object x,
int targetSqlType,
int scale)
throws java.sql.SQLException
setObject in interface java.sql.PreparedStatementjava.sql.SQLException
public void setNull(int parameterIndex,
int sqlType,
java.lang.String typeName)
throws java.sql.SQLException
setNull in interface java.sql.PreparedStatementjava.sql.SQLException
public void setString(int parameterIndex,
java.lang.String x)
throws java.sql.SQLException
setString in interface java.sql.PreparedStatementjava.sql.SQLException
public void setBigDecimal(int parameterIndex,
java.math.BigDecimal x)
throws java.sql.SQLException
setBigDecimal in interface java.sql.PreparedStatementjava.sql.SQLException
public void setURL(int parameterIndex,
java.net.URL url)
throws java.sql.SQLException
setURL in interface java.sql.PreparedStatementjava.sql.SQLException
public void setArray(int arg0,
java.sql.Array arg1)
throws java.sql.SQLException
setArray in interface java.sql.PreparedStatementjava.sql.SQLException
public void setBlob(int parameterIndex,
java.sql.Blob x)
throws java.sql.SQLException
setBlob in interface java.sql.PreparedStatementjava.sql.SQLException
public void setClob(int parameterIndex,
java.sql.Clob x)
throws java.sql.SQLException
setClob in interface java.sql.PreparedStatementjava.sql.SQLException
public void setDate(int parameterIndex,
java.sql.Date x)
throws java.sql.SQLException
setDate in interface java.sql.PreparedStatementjava.sql.SQLException
public java.sql.ParameterMetaData getParameterMetaData()
throws java.sql.SQLException
getParameterMetaData in interface java.sql.PreparedStatementjava.sql.SQLException
public void setRef(int parameterIndex,
java.sql.Ref x)
throws java.sql.SQLException
setRef in interface java.sql.PreparedStatementjava.sql.SQLException
public java.sql.ResultSet executeQuery()
throws java.sql.SQLException
executeQuery in interface java.sql.PreparedStatementjava.sql.SQLException
public java.sql.ResultSetMetaData getMetaData()
throws java.sql.SQLException
getMetaData in interface java.sql.PreparedStatementjava.sql.SQLException
public void setTime(int parameterIndex,
java.sql.Time x)
throws java.sql.SQLException
setTime in interface java.sql.PreparedStatementjava.sql.SQLException
public void setTimestamp(int parameterIndex,
java.sql.Timestamp x)
throws java.sql.SQLException
setTimestamp in interface java.sql.PreparedStatementjava.sql.SQLException
public void setDate(int parameterIndex,
java.sql.Date x,
java.util.Calendar cal)
throws java.sql.SQLException
setDate in interface java.sql.PreparedStatementjava.sql.SQLException
public void setTime(int parameterIndex,
java.sql.Time x,
java.util.Calendar cal)
throws java.sql.SQLException
setTime in interface java.sql.PreparedStatementjava.sql.SQLException
public void setTimestamp(int parameterIndex,
java.sql.Timestamp x,
java.util.Calendar cal)
throws java.sql.SQLException
setTimestamp in interface java.sql.PreparedStatementjava.sql.SQLException
public int executeUpdate(java.lang.String sql)
throws java.sql.SQLException
executeUpdate in interface java.sql.StatementexecuteUpdate in class JtdsStatementjava.sql.SQLException
public void addBatch(java.lang.String sql)
throws java.sql.SQLException
addBatch in interface java.sql.StatementaddBatch in class JtdsStatementjava.sql.SQLException
public boolean execute(java.lang.String sql)
throws java.sql.SQLException
execute in interface java.sql.Statementexecute in class JtdsStatementjava.sql.SQLException
public int executeUpdate(java.lang.String sql,
int getKeys)
throws java.sql.SQLException
executeUpdate in interface java.sql.StatementexecuteUpdate in class JtdsStatementjava.sql.SQLException
public boolean execute(java.lang.String arg0,
int arg1)
throws java.sql.SQLException
execute in interface java.sql.Statementexecute in class JtdsStatementjava.sql.SQLException
public int executeUpdate(java.lang.String arg0,
int[] arg1)
throws java.sql.SQLException
executeUpdate in interface java.sql.StatementexecuteUpdate in class JtdsStatementjava.sql.SQLException
public boolean execute(java.lang.String arg0,
int[] arg1)
throws java.sql.SQLException
execute in interface java.sql.Statementexecute in class JtdsStatementjava.sql.SQLException
public int executeUpdate(java.lang.String arg0,
java.lang.String[] arg1)
throws java.sql.SQLException
executeUpdate in interface java.sql.StatementexecuteUpdate in class JtdsStatementjava.sql.SQLException
public boolean execute(java.lang.String arg0,
java.lang.String[] arg1)
throws java.sql.SQLException
execute in interface java.sql.Statementexecute in class JtdsStatementjava.sql.SQLException
public java.sql.ResultSet executeQuery(java.lang.String sql)
throws java.sql.SQLException
executeQuery in interface java.sql.StatementexecuteQuery in class JtdsStatementjava.sql.SQLException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
Interface for a statement cache. Abstraction of the caching mechanism by use of this interface will allow developers to create custom caching schemes that are optimal for their specific applications. Any synchronization required by an implementation should utilize the implementing object for the lock.
There are two types of attributes that the cache is concerned with:
String generated from the SQL query for which the
prepared statement was created, the database name and the parameter
types; this key uniquely identifies a server-side preparation of the
statement and is used to retrieve the handle of the statement when it
needs to be executedsp_prepare or
sp_cursorprepare handle on the serverPreparedStatement can map to multiple handles, depending on
the types of the parameters it is called with (hence the need to be able
to map both keys and SQL strings to handles)The caching types provided by jTDS should be:
| Method Summary | |
java.lang.Object |
get(java.lang.String key)
Returns a statement handle associated with the specified key or null if the key specified does not have an associated
statement handle. |
java.util.Collection |
getObsoleteHandles(java.util.Collection handles)
Returns a Collection of obsolete statement handles that may
be released, or null if no statement handles are obsolete. |
void |
put(java.lang.String key,
java.lang.Object handle)
Places the specified statement handle in the cache for the given key. |
void |
remove(java.lang.String key)
Removes a statement key and handle from the cache for the specified key. |
| Method Detail |
public java.lang.Object get(java.lang.String key)
null if the key specified does not have an associated
statement handle.
key - the statement key whose associated handle is to be returned
public void put(java.lang.String key,
java.lang.Object handle)
key - the statement key to associated with the handlehandle - the statement handlepublic void remove(java.lang.String key)
key - the statement key whose associated handle is to be removed
from the cachepublic java.util.Collection getObsoleteHandles(java.util.Collection handles)
Collection of obsolete statement handles that may
be released, or null if no statement handles are obsolete.
handles - the statement handles that are no longer being used
Collection of obsolete statement handles to be
removed
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use StatementCache | |
| net.sourceforge.jtds.jdbc | |
| net.sourceforge.jtds.jdbc.cache | |
| Uses of StatementCache in net.sourceforge.jtds.jdbc |
| Fields in net.sourceforge.jtds.jdbc declared as StatementCache | |
private StatementCache |
ConnectionJDBC2.statementCache
Statement cache. |
| Uses of StatementCache in net.sourceforge.jtds.jdbc.cache |
| Classes in net.sourceforge.jtds.jdbc.cache that implement StatementCache | |
class |
ProcedureCache
LRU cache for procedures and statement handles. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use SimpleLRUCache | |
| net.sourceforge.jtds.jdbc | |
| Uses of SimpleLRUCache in net.sourceforge.jtds.jdbc |
| Fields in net.sourceforge.jtds.jdbc declared as SimpleLRUCache | |
private static SimpleLRUCache |
SQLParser.cache
LRU cache of previously parsed SQL |
| Methods in net.sourceforge.jtds.jdbc that return SimpleLRUCache | |
private static SimpleLRUCache |
SQLParser.getCache(ConnectionJDBC2 connection)
Retrieves the statement cache, creating it if required. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use ProcedureCache.CacheEntry | |
| net.sourceforge.jtds.jdbc.cache | |
| Uses of ProcedureCache.CacheEntry in net.sourceforge.jtds.jdbc.cache |
| Fields in net.sourceforge.jtds.jdbc.cache declared as ProcedureCache.CacheEntry | |
(package private) ProcedureCache.CacheEntry |
ProcedureCache.head
Head node of the linked list. |
(package private) ProcedureCache.CacheEntry |
ProcedureCache.tail
Tail node of the linked list. |
(package private) ProcedureCache.CacheEntry |
ProcedureCache.CacheEntry.next
|
(package private) ProcedureCache.CacheEntry |
ProcedureCache.CacheEntry.prior
|
| Methods in net.sourceforge.jtds.jdbc.cache with parameters of type ProcedureCache.CacheEntry | |
(package private) void |
ProcedureCache.CacheEntry.link(ProcedureCache.CacheEntry ce)
Links this CacheEntry into the linked list after the node specified. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV PACKAGE NEXT PACKAGE | FRAMES NO FRAMES | ||||||||||
| Interface Summary | |
| StatementCache | Interface for a statement cache. |
| Class Summary | |
| ProcedureCache | LRU cache for procedures and statement handles. |
| ProcedureCache.CacheEntry | Encapsulates the cached Object and implements the linked list used to implement the LRU logic. |
| SimpleLRUCache | Simple LRU cache for any type of object. |
| SQLCacheKey | Cache key for an SQL query, consisting of the query and server type, major and minor version. |
|
|||||||||||
| PREV PACKAGE NEXT PACKAGE | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.cache.ProcedureCache
LRU cache for procedures and statement handles.
| Nested Class Summary | |
private static class |
ProcedureCache.CacheEntry
Encapsulates the cached Object and implements the linked list used to implement the LRU logic. |
| Field Summary | |
private java.util.HashMap |
cache
The actual cache instance. |
(package private) int |
cacheSize
Maximum cache size or 0 to disable. |
(package private) java.util.ArrayList |
free
List of redundant cache entries. |
(package private) ProcedureCache.CacheEntry |
head
Head node of the linked list. |
private static int |
MAX_INITIAL_SIZE
The maximum initial HashMap size. |
(package private) ProcedureCache.CacheEntry |
tail
Tail node of the linked list. |
| Constructor Summary | |
ProcedureCache(int cacheSize)
Constructs a new statement cache. |
|
| Method Summary | |
java.lang.Object |
get(java.lang.String key)
Retrieves a ProcEntry object from the cache. |
java.util.Collection |
getObsoleteHandles(java.util.Collection handles)
Obtains a list of statement handles or procedures that can now be dropped. |
void |
put(java.lang.String key,
java.lang.Object handle)
Inserts a new entry, identified by a key, into the cache. |
void |
remove(java.lang.String key)
Removes a redundant entry from the cache. |
private void |
scavengeCache()
Removes unused entries trying to bring down the cache to the requested size. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private static final int MAX_INITIAL_SIZE
private java.util.HashMap cache
int cacheSize
ProcedureCache.CacheEntry head
ProcedureCache.CacheEntry tail
java.util.ArrayList free
| Constructor Detail |
public ProcedureCache(int cacheSize)
cacheSize - maximum cache size or 0 to disable caching| Method Detail |
public java.lang.Object get(java.lang.String key)
get in interface StatementCachekey - the key value identifying the required entry
Object or null if the entry
does not exist
public void put(java.lang.String key,
java.lang.Object handle)
put in interface StatementCachekey - value used to identify the entryhandle - proc entry to be inserted into the cachepublic void remove(java.lang.String key)
remove in interface StatementCachekey - value that identifies the cache entrypublic java.util.Collection getObsoleteHandles(java.util.Collection handles)
getObsoleteHandles in interface StatementCachehandles - a collection of single use statements that will be
returned for dropping if the cache is disabled
private void scavengeCache()
free list.
Note: entries that are in use will not be removed so it is
possible for the cache to still be larger than cacheSize after
the call finishes.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use net.sourceforge.jtds.jdbc.cache | |
| net.sourceforge.jtds.jdbc | |
| net.sourceforge.jtds.jdbc.cache | |
| Classes in net.sourceforge.jtds.jdbc.cache used by net.sourceforge.jtds.jdbc | |
| SimpleLRUCache
Simple LRU cache for any type of object. |
|
| StatementCache
Interface for a statement cache. |
|
| Classes in net.sourceforge.jtds.jdbc.cache used by net.sourceforge.jtds.jdbc.cache | |
| ProcedureCache.CacheEntry
Encapsulates the cached Object and implements the linked list used to implement the LRU logic. |
|
| StatementCache
Interface for a statement cache. |
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjava.util.AbstractMap
java.util.HashMap
net.sourceforge.jtds.jdbc.cache.SimpleLRUCache
Simple LRU cache for any type of object. Implemented as an extended
HashMap with a maximum size and an aggregated List
as LRU queue.
| Nested Class Summary |
| Nested classes inherited from class java.util.HashMap |
|
| Nested classes inherited from class java.util.AbstractMap |
|
| Field Summary | |
private java.util.LinkedList |
list
LRU list. |
private int |
maxCacheSize
Maximum cache size. |
| Fields inherited from class java.util.HashMap |
|
| Fields inherited from class java.util.AbstractMap |
|
| Constructor Summary | |
SimpleLRUCache(int maxCacheSize)
Constructs a new LRU cache instance. |
|
| Method Summary | |
void |
clear()
Overrides clear() to also clear the LRU list. |
private void |
freshenKey(java.lang.Object key)
Moves the specified value to the top of the LRU list (the bottom of the list is where least recently used items live). |
java.lang.Object |
get(java.lang.Object key)
Overrides get() so that it also updates the LRU list. |
java.lang.Object |
put(java.lang.Object key,
java.lang.Object value)
Overrides put() so that it also updates the LRU list. |
java.lang.Object |
remove(java.lang.Object key)
|
| Methods inherited from class java.util.HashMap |
clone, containsKey, containsValue, entrySet, isEmpty, keySet, putAll, size, values |
| Methods inherited from class java.util.AbstractMap |
equals, hashCode, toString |
| Methods inherited from class java.lang.Object |
finalize, getClass, notify, notifyAll, wait, wait, wait |
| Methods inherited from interface java.util.Map |
equals, hashCode |
| Field Detail |
private final int maxCacheSize
private final java.util.LinkedList list
| Constructor Detail |
public SimpleLRUCache(int maxCacheSize)
maxCacheSize - the maximum number of entries in this cache before
entries are aged off| Method Detail |
public void clear()
public java.lang.Object put(java.lang.Object key,
java.lang.Object value)
put() so that it also updates the LRU list.
key - key with which the specified value is to be associatedvalue - value to be associated with the key
null if there
was no mapping for key; a null return can also
indicate that the cache previously associated null
with the specified keyMap.put(Object, Object)public java.lang.Object get(java.lang.Object key)
get() so that it also updates the LRU list.
key - key with which the expected value is associated
null if the map contains no mapping for this keypublic java.lang.Object remove(java.lang.Object key)
Map.remove(Object)private void freshenKey(java.lang.Object key)
key - key of the value to move to the top of the list
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.cache.SQLCacheKey
Cache key for an SQL query, consisting of the query and server type, major and minor version.
| Field Summary | |
private int |
hashCode
|
private int |
majorVersion
|
private int |
minorVersion
|
private int |
serverType
|
private java.lang.String |
sql
|
| Constructor Summary | |
SQLCacheKey(java.lang.String sql,
ConnectionJDBC2 connection)
|
|
| Method Summary | |
boolean |
equals(java.lang.Object object)
|
int |
hashCode()
|
| Methods inherited from class java.lang.Object |
clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private final java.lang.String sql
private final int serverType
private final int majorVersion
private final int minorVersion
private final int hashCode
| Constructor Detail |
public SQLCacheKey(java.lang.String sql,
ConnectionJDBC2 connection)
| Method Detail |
public int hashCode()
public boolean equals(java.lang.Object object)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.cache.ProcedureCache.CacheEntry
Encapsulates the cached Object and implements the linked list used to implement the LRU logic.
| Field Summary | |
(package private) java.lang.String |
key
|
(package private) ProcedureCache.CacheEntry |
next
|
(package private) ProcedureCache.CacheEntry |
prior
|
(package private) ProcEntry |
value
|
| Constructor Summary | |
(package private) |
ProcedureCache.CacheEntry(java.lang.String key,
ProcEntry value)
Constructs a new cache entry encapsulating the supplied key and value. |
| Method Summary | |
(package private) void |
link(ProcedureCache.CacheEntry ce)
Links this CacheEntry into the linked list after the node specified. |
(package private) void |
unlink()
Unlinks this CacheEntry from the linked list. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
java.lang.String key
ProcEntry value
ProcedureCache.CacheEntry next
ProcedureCache.CacheEntry prior
| Constructor Detail |
ProcedureCache.CacheEntry(java.lang.String key,
ProcEntry value)
key - key used to identify the cache entryvalue - object being cached| Method Detail |
void unlink()
void link(ProcedureCache.CacheEntry ce)
ce - node after which this entry will be linked
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
Interfaces
StatementCache |
|
Classes
ProcedureCache ProcedureCache.CacheEntry SimpleLRUCache SQLCacheKey |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.ParameterMetaDataImpl
jTDS implementation of ParameterMetaData.
| Field Summary | |
private int |
maxPrecision
|
private ParamInfo[] |
parameterList
|
private boolean |
useLOBs
|
| Fields inherited from interface java.sql.ParameterMetaData |
parameterModeIn, parameterModeInOut, parameterModeOut, parameterModeUnknown, parameterNoNulls, parameterNullable, parameterNullableUnknown |
| Constructor Summary | |
ParameterMetaDataImpl(ParamInfo[] parameterList,
ConnectionJDBC2 connection)
|
|
| Method Summary | |
private ParamInfo |
getParameter(int param)
|
java.lang.String |
getParameterClassName(int param)
|
int |
getParameterCount()
|
int |
getParameterMode(int param)
|
int |
getParameterType(int param)
|
java.lang.String |
getParameterTypeName(int param)
|
int |
getPrecision(int param)
|
int |
getScale(int param)
|
int |
isNullable(int param)
|
boolean |
isSigned(int param)
|
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private final ParamInfo[] parameterList
private final int maxPrecision
private final boolean useLOBs
| Constructor Detail |
public ParameterMetaDataImpl(ParamInfo[] parameterList, ConnectionJDBC2 connection)
| Method Detail |
public int getParameterCount()
throws java.sql.SQLException
getParameterCount in interface java.sql.ParameterMetaDatajava.sql.SQLException
public int isNullable(int param)
throws java.sql.SQLException
isNullable in interface java.sql.ParameterMetaDatajava.sql.SQLException
public int getParameterType(int param)
throws java.sql.SQLException
getParameterType in interface java.sql.ParameterMetaDatajava.sql.SQLException
public int getScale(int param)
throws java.sql.SQLException
getScale in interface java.sql.ParameterMetaDatajava.sql.SQLException
public boolean isSigned(int param)
throws java.sql.SQLException
isSigned in interface java.sql.ParameterMetaDatajava.sql.SQLException
public int getPrecision(int param)
throws java.sql.SQLException
getPrecision in interface java.sql.ParameterMetaDatajava.sql.SQLException
public java.lang.String getParameterTypeName(int param)
throws java.sql.SQLException
getParameterTypeName in interface java.sql.ParameterMetaDatajava.sql.SQLException
public java.lang.String getParameterClassName(int param)
throws java.sql.SQLException
getParameterClassName in interface java.sql.ParameterMetaDatajava.sql.SQLException
public int getParameterMode(int param)
throws java.sql.SQLException
getParameterMode in interface java.sql.ParameterMetaDatajava.sql.SQLExceptionprivate ParamInfo getParameter(int param) throws java.sql.SQLException
java.sql.SQLException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use net.sourceforge.jtds.jdbc | |
| net.sourceforge.jtds.jdbc | |
| net.sourceforge.jtds.jdbc.cache | |
| net.sourceforge.jtds.jdbcx | |
| net.sourceforge.jtds.jdbcx.proxy | |
| net.sourceforge.jtds.test | |
| Classes in net.sourceforge.jtds.jdbc used by net.sourceforge.jtds.jdbc | |
| CachedResultSet
A memory cached scrollable/updateable result set. |
|
| CharsetInfo
Loads and stores information about character sets. |
|
| ColInfo
This class is a descriptor for result set columns. |
|
| ConnectionJDBC2
jTDS implementation of the java.sql.Connection interface. |
|
| DateTime
Encapsulates Sybase date/time values and provides conversions to and from Java classes. |
|
| JtdsPreparedStatement
jTDS implementation of the java.sql.PreparedStatement interface. |
|
| JtdsResultSet
jTDS Implementation of the java.sql.ResultSet interface supporting forward read only result sets. |
|
| JtdsStatement
jTDS implementation of the java.sql.Statement interface. |
|
| ParamInfo
This class is a descriptor for procedure and prepared statement parameters. |
|
| ProcEntry
Stores information about a cached stored procedure or statement handle. |
|
| ProtocolException
Exception class used to report errors in the TDS protocol. |
|
| RequestStream
Class to implement an output stream for the server request. |
|
| ResponseStream
Implements an input stream for the server response. |
|
| SavepointImpl
Savepoint implementation class. |
|
| Semaphore
Simple semaphore class used to serialize access requests over the network connection. |
|
| SharedSocket
This class mananges the physical connection to the SQL Server and serialises its use amongst a number of virtual sockets. |
|
| SharedSocket.VirtualSocket
This inner class contains the state information for the virtual socket. |
|
| SQLDiagnostic
Helper class for handling SQL warnings and errors. |
|
| TdsCore
This class implements the Sybase / Microsoft TDS protocol. |
|
| TdsCore.TableMetaData
Inner static class used to hold table meta data. |
|
| TdsCore.TdsToken
Inner static class used to hold information about TDS tokens read. |
|
| TdsData.TypeInfo
This class implements a descriptor for TDS data types; |
|
| Classes in net.sourceforge.jtds.jdbc used by net.sourceforge.jtds.jdbc.cache | |
| ConnectionJDBC2
jTDS implementation of the java.sql.Connection interface. |
|
| ProcEntry
Stores information about a cached stored procedure or statement handle. |
|
| Classes in net.sourceforge.jtds.jdbc used by net.sourceforge.jtds.jdbcx | |
| Driver
jTDS implementation of the java.sql.Driver interface. |
|
| Classes in net.sourceforge.jtds.jdbc used by net.sourceforge.jtds.jdbcx.proxy | |
| ConnectionJDBC2
jTDS implementation of the java.sql.Connection interface. |
|
| JtdsCallableStatement
jTDS implementation of the java.sql.CallableStatement interface. |
|
| JtdsPreparedStatement
jTDS implementation of the java.sql.PreparedStatement interface. |
|
| JtdsStatement
jTDS implementation of the java.sql.Statement interface. |
|
| Classes in net.sourceforge.jtds.jdbc used by net.sourceforge.jtds.test | |
| TypeInfo
Represents an SQL data type as required by getTypeInfo().
|
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.SharedSocket
This class mananges the physical connection to the SQL Server and serialises its use amongst a number of virtual sockets. This allows one physical connection to service a number of concurrent statements.
Constraints and assumptions:
| Nested Class Summary | |
private static class |
SharedSocket.VirtualSocket
This inner class contains the state information for the virtual socket. |
| Field Summary | |
private java.io.File |
bufferDir
The directory to buffer data to. |
private java.lang.Object |
cancelMonitor
Synchronization monitor for cancelPending and
responseOwner. |
private boolean |
cancelPending
A cancel packet is pending. |
private CharsetInfo |
charsetInfo
The character set to use for converting strings to/from bytes. |
private byte[] |
doneBuffer
Buffer for TDS_DONE packets |
private static int |
globalMemUsage
Total memory usage in all instances of the driver NB. |
private byte[] |
hdrBuf
Buffer for packet header. |
private java.lang.String |
host
The server host name. |
private java.io.DataInputStream |
in
Input stream for network socket. |
private int |
maxBufSize
Current maxium input buffer size. |
private static int |
memoryBudget
Max memory limit to use for buffers. |
private static int |
minMemPkts
Minimum number of packets that will be cached in memory before the driver tries to write to disk even if memoryBudget has been exceeded. |
private java.io.DataOutputStream |
out
Output stream for network socket. |
private int |
packetCount
Count of packets received. |
private static int |
peakMemUsage
Peak memory usage for debug purposes. |
private int |
port
The server port number. |
private int |
responseOwner
The Stream ID of the object that is expecting a response from the server. |
private static boolean |
securityViolation
Global flag to indicate that security constraints mean that attempts to create work files will fail. |
protected int |
serverType
The servertype one of Driver.SQLSERVER or Driver.SYBASE |
private java.net.Socket |
socket
The shared network socket. |
private java.util.ArrayList |
socketTable
Table of stream objects sharing this socket. |
private java.net.Socket |
sslSocket
The shared SSL network socket; |
private static int |
TDS_DONE_LEN
Length of a TDS_DONE token. |
private static int |
TDS_DONE_TOKEN
TDS done token. |
private static int |
TDS_HDR_LEN
Length of TDS packet header. |
private int |
tdsVersion
Tds protocol version |
| Constructor Summary | |
(package private) |
SharedSocket(ConnectionJDBC2 connection)
Construct a SharedSocket object specifying host name and
port. |
protected |
SharedSocket(java.io.File bufferDir,
int tdsVersion,
int serverType)
|
| Method Summary | |
(package private) boolean |
cancel(int streamId)
Send a TDS cancel packet to the server. |
(package private) void |
close()
Close the socket and release all resources. |
(package private) void |
closeStream(int streamId)
Deallocate a stream linked to this socket. |
private java.net.Socket |
createSocketForJDBC3(ConnectionJDBC2 connection)
Creates a SharedSocket.VirtualSocket through reflection when Driver.JDBC3
is true. |
private byte[] |
dequeueInput(SharedSocket.VirtualSocket vsock)
Read a cached packet from the in memory queue or from a disk based queue. |
(package private) void |
disableEncryption()
Disable TLS encryption and switch back to raw TCP/IP socket. |
(package private) void |
enableEncryption(java.lang.String ssl)
Enable TLS encryption by creating a TLS socket over the existing TCP/IP network socket. |
private void |
enqueueInput(SharedSocket.VirtualSocket vsock,
byte[] buffer)
Save a packet buffer in a memory queue or to a disk queue if the global memory limit for the driver has been exceeded. |
protected void |
finalize()
Finalize this object by releasing its resources. |
(package private) void |
forceClose()
Force close the socket causing any pending reads/writes to fail. |
(package private) java.lang.String |
getCharset()
Retrieve the character set name used to translate byte arrays to or from Strings. |
(package private) CharsetInfo |
getCharsetInfo()
Retrieve the character set descriptor used to translate byte arrays to or from Strings. |
protected java.lang.String |
getHost()
Get the server host name. |
protected java.io.DataInputStream |
getIn()
Getter for in field. |
(package private) static int |
getMemoryBudget()
Get the global buffer memory limit for all instancs of this driver. |
(package private) static int |
getMinMemPkts()
Get the minimum number of memory cached packets. |
(package private) byte[] |
getNetPacket(int streamId,
byte[] buffer)
Get a network packet. |
protected java.io.DataOutputStream |
getOut()
Getter for out field. |
(package private) static int |
getPktLen(byte[] buf)
Convert two bytes (in network byte order) in a byte array into a Java short integer. |
protected int |
getPort()
Get the server port number. |
(package private) RequestStream |
getRequestStream(int bufferSize,
int maxPrecision)
Obtain an instance of a server request stream for this socket. |
(package private) ResponseStream |
getResponseStream(RequestStream requestStream,
int bufferSize)
Obtain an instance of a server response stream for this socket. |
(package private) int |
getTdsVersion()
Retrieve the TDS version that is active on the connection supported by this socket. |
(package private) boolean |
isConnected()
Get the connected status of this socket. |
private SharedSocket.VirtualSocket |
lookup(int streamId)
Retrieves the virtual socket with the given id. |
private byte[] |
readPacket(byte[] buffer)
Read a physical TDS packet from the network. |
(package private) byte[] |
sendNetPacket(int streamId,
byte[] buffer)
Send a network packet. |
(package private) void |
setCharsetInfo(CharsetInfo charsetInfo)
Set the character set descriptor to be used to translate byte arrays to or from Strings. |
protected void |
setIn(java.io.DataInputStream in)
Setter for in field. |
protected void |
setKeepAlive(boolean keepAlive)
Set the socket keep alive. |
(package private) static void |
setMemoryBudget(int memoryBudget)
Set the global buffer memory limit for all instances of this driver. |
(package private) static void |
setMinMemPkts(int minMemPkts)
Set the minimum number of packets to cache in memory before writing to disk. |
protected void |
setOut(java.io.DataOutputStream out)
Setter for out field. |
protected void |
setTdsVersion(int tdsVersion)
Set the TDS version field. |
protected void |
setTimeout(int timeout)
Set the socket timeout. |
| Methods inherited from class java.lang.Object |
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private java.net.Socket socket
private java.net.Socket sslSocket
private java.io.DataOutputStream out
private java.io.DataInputStream in
private int maxBufSize
private final java.util.ArrayList socketTable
private int responseOwner
private final byte[] hdrBuf
private final java.io.File bufferDir
private static int globalMemUsage
private static int peakMemUsage
private static int memoryBudget
private static int minMemPkts
private static boolean securityViolation
private int tdsVersion
protected final int serverType
private CharsetInfo charsetInfo
private int packetCount
private java.lang.String host
private int port
private boolean cancelPending
private java.lang.Object cancelMonitor
cancelPending and
responseOwner.
private byte[] doneBuffer
private static final int TDS_DONE_TOKEN
private static final int TDS_DONE_LEN
private static final int TDS_HDR_LEN
| Constructor Detail |
protected SharedSocket(java.io.File bufferDir,
int tdsVersion,
int serverType)
SharedSocket(ConnectionJDBC2 connection) throws java.io.IOException, java.net.UnknownHostException
SharedSocket object specifying host name and
port.
connection - the connection object
java.io.IOException - if socket open fails
java.net.UnknownHostException| Method Detail |
private java.net.Socket createSocketForJDBC3(ConnectionJDBC2 connection) throws java.io.IOException
SharedSocket.VirtualSocket through reflection when Driver.JDBC3
is true. Reflection must be used to stay compatible
with JDK 1.3.
connection - the connection object
java.io.IOException - if socket open fails
void enableEncryption(java.lang.String ssl)
throws java.io.IOException
ssl - the SSL URL property value
java.io.IOException - if an I/O error occurs
void disableEncryption()
throws java.io.IOException
java.io.IOException - if an I/O error occursvoid setCharsetInfo(CharsetInfo charsetInfo)
charsetInfo - the character set descriptorCharsetInfo getCharsetInfo()
java.lang.String getCharset()
StringRequestStream getRequestStream(int bufferSize, int maxPrecision)
bufferSize - the initial buffer size to be used by the
RequestStreammaxPrecision - the maximum precision for numeric/decimal types
RequestStreamResponseStream getResponseStream(RequestStream requestStream, int bufferSize)
requestStream - an existing server request stream object obtained
from this SharedSocketbufferSize - the initial buffer size to be used by the
RequestStream
ResponseStreamint getTdsVersion()
intprotected void setTdsVersion(int tdsVersion)
tdsVersion - the TDS version as an intstatic void setMemoryBudget(int memoryBudget)
memoryBudget - the global memory budgetstatic int getMemoryBudget()
intstatic void setMinMemPkts(int minMemPkts)
minMemPkts - the minimum number of packets to cachestatic int getMinMemPkts()
intboolean isConnected()
true if the underlying socket is connectedboolean cancel(int streamId)
streamId - the RequestStream id
boolean true if a cancel is actually
issued by this method call.
void close()
throws java.io.IOException
java.io.IOException - if the socket close failsvoid forceClose()
Used by the login timer to abort a login attempt.
void closeStream(int streamId)
streamId - the ResponseStream id
byte[] sendNetPacket(int streamId,
byte[] buffer)
throws java.io.IOException
streamId - the originating RequestStream objectbuffer - the data to send
java.io.IOException - if an I/O error occurs
byte[] getNetPacket(int streamId,
byte[] buffer)
throws java.io.IOException
streamId - the originating ResponseStream objectbuffer - the data buffer to receive the object (may be replaced)
byte[] buffer
java.io.IOException - if an I/O error occursprivate void enqueueInput(SharedSocket.VirtualSocket vsock, byte[] buffer) throws java.io.IOException
vsock - the virtual socket owning this databuffer - the data to queue
java.io.IOExceptionprivate byte[] dequeueInput(SharedSocket.VirtualSocket vsock) throws java.io.IOException
vsock - the virtual socket owning this data
java.io.IOException
private byte[] readPacket(byte[] buffer)
throws java.io.IOException
buffer - a buffer to read the data into (if it fits) or null
java.io.IOExceptionprivate SharedSocket.VirtualSocket lookup(int streamId)
streamId - id of the virtual socket to retrievestatic int getPktLen(byte[] buf)
buf - array of data
int
protected void setTimeout(int timeout)
throws java.net.SocketException
timeout - the timeout value in milliseconds
java.net.SocketException
protected void setKeepAlive(boolean keepAlive)
throws java.net.SocketException
keepAlive - true to turn on socket keep alive
java.net.SocketExceptionprotected java.io.DataInputStream getIn()
in field.
InputStream used for communicationprotected void setIn(java.io.DataInputStream in)
in field.
in - the InputStream to be used for communicationprotected java.io.DataOutputStream getOut()
out field.
OutputStream used for communicationprotected void setOut(java.io.DataOutputStream out)
out field.
out - the OutputStream to be used for communicationprotected java.lang.String getHost()
Stringprotected int getPort()
int
protected void finalize()
throws java.lang.Throwable
java.lang.Throwable
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjava.io.InputStream
net.sourceforge.jtds.jdbc.ResponseStream.TdsInputStream
Simple inner class implementing an InputStream over the
server response.
| Field Summary | |
(package private) int |
maxLen
The maximum amount of data to make available. |
(package private) ResponseStream |
tds
The underlying ResponseStream. |
| Fields inherited from class java.io.InputStream |
|
| Constructor Summary | |
ResponseStream.TdsInputStream(ResponseStream tds,
int maxLen)
Creates a TdsInputStream instance. |
|
| Method Summary | |
int |
read()
|
int |
read(byte[] bytes,
int offset,
int len)
|
| Methods inherited from class java.io.InputStream |
available, close, mark, markSupported, read, reset, skip |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
ResponseStream tds
ResponseStream.
int maxLen
| Constructor Detail |
public ResponseStream.TdsInputStream(ResponseStream tds, int maxLen)
TdsInputStream instance.
tds - the underlying ResponseStreammaxLen - the maximum amount of data that will be available| Method Detail |
public int read()
throws java.io.IOException
java.io.IOException
public int read(byte[] bytes,
int offset,
int len)
throws java.io.IOException
java.io.IOException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.ResponseStream
Implements an input stream for the server response.
Implementation note:
| Nested Class Summary | |
private static class |
ResponseStream.TdsInputStream
Simple inner class implementing an InputStream over the
server response. |
| Field Summary | |
private byte[] |
buffer
The Input packet buffer. |
private int |
bufferLen
The length of current input packet. |
private int |
bufferPtr
The offset of the next byte to read. |
private byte[] |
byteBuffer
A shared byte buffer. |
private char[] |
charBuffer
A shared char buffer. |
private boolean |
isClosed
True if stream is closed. |
private SharedSocket |
socket
The shared network socket. |
private int |
streamId
The unique stream id. |
| Constructor Summary | |
(package private) |
ResponseStream(SharedSocket socket,
int streamId,
int bufferSize)
Constructs a RequestStream object. |
| Method Summary | |
(package private) void |
close()
Closes this response stream. |
(package private) java.io.InputStream |
getInputStream(int len)
Creates a simple InputStream over the server response.
|
private void |
getPacket()
Read the next TDS packet from the network. |
(package private) int |
getServerType()
Retrieves the server type. |
(package private) int |
getStreamId()
Retrieves the unique stream id. |
(package private) int |
getTdsVersion()
Retrieves the TDS version number. |
(package private) int |
peek()
Retrieves the next input byte without reading forward. |
(package private) int |
read()
Reads the next input byte from the server response stream. |
(package private) int |
read(byte[] b)
Reads a byte array from the server response stream. |
(package private) int |
read(byte[] b,
int off,
int len)
Reads a byte array from the server response stream, specifying a start offset and length. |
(package private) int |
read(char[] c)
Reads a char array from the server response stream. |
(package private) int |
readInt()
Reads an int value from the server response stream. |
(package private) long |
readLong()
Reads a long value from the server response stream. |
(package private) java.lang.String |
readNonUnicodeString(int len)
Reads a non Unicode String from the server response stream,
creating the String from a translated byte
array. |
(package private) java.lang.String |
readNonUnicodeString(int len,
CharsetInfo charsetInfo)
Reads a String from the server response stream, translating
it from a byte array using the specified character set. |
(package private) short |
readShort()
Reads a short value from the server response stream. |
(package private) java.lang.String |
readString(int len)
Reads a String object from the server response stream. |
(package private) java.lang.String |
readString(int len,
CharsetInfo info)
Reads a String from the server response stream, creating
it from a translated byte array. |
(package private) java.lang.String |
readUnicodeString(int len)
Reads a UCS2-LE (Unicode) encoded String object from the server response stream. |
(package private) java.math.BigDecimal |
readUnsignedLong()
Reads an unsigned long value from the server response stream. |
(package private) int |
skip(int skip)
Discards bytes from the server response stream. |
(package private) void |
skipString(int len)
Skips a String from the server response stream. |
(package private) void |
skipToEnd()
Consumes the rest of the server response, without parsing it. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private final SharedSocket socket
private byte[] buffer
private int bufferPtr
private int bufferLen
private final int streamId
private boolean isClosed
private final byte[] byteBuffer
private final char[] charBuffer
| Constructor Detail |
ResponseStream(SharedSocket socket, int streamId, int bufferSize)
RequestStream object.
socket - the shared socket object to write tostreamId - the unique id for this stream (from ResponseStream)bufferSize - the initial buffer size| Method Detail |
int getStreamId()
intint peek() throws java.io.IOException
int
java.io.IOException - if an I/O error occursint read() throws java.io.IOException
int
java.io.IOException - if an I/O error occursint read(byte[] b) throws java.io.IOException
b - the byte array to read into
int
java.io.IOException - if an I/O error occurs
int read(byte[] b,
int off,
int len)
throws java.io.IOException
b - the byte arrayoff - the starting offset in the arraylen - the number of bytes to read
int
java.io.IOException - if an I/O error occursint read(char[] c) throws java.io.IOException
c - the char array
byte[]
java.io.IOException - if an I/O error occurs
java.lang.String readString(int len)
throws java.io.IOException
String object from the server response stream. If
the TDS protocol version is 4.2 or 5.0 decode the string use the default
server charset, otherwise use UCS2-LE (Unicode).
len - the length of the string to read in bytes in the case
of TDS 4.2/5.0 and in characters for TDS 7.0+
(UCS2-LE encoded strings)
String
java.io.IOException - if an I/O error occurs
void skipString(int len)
throws java.io.IOException
String from the server response stream. If the TDS
protocol version is 4.2 or 5.0 len is the length in bytes,
otherwise it's the length in UCS2-LE characters (length in bytes == 2 *
len).
len - the length of the string to skip in bytes in the case
of TDS 4.2/5.0 and in characters for TDS 7.0+
(UCS2-LE encoded strings)
java.io.IOException - if an I/O error occurs
java.lang.String readUnicodeString(int len)
throws java.io.IOException
len - the length of the string to read in characters
String
java.io.IOException - if an I/O error occurs
java.lang.String readNonUnicodeString(int len)
throws java.io.IOException
String from the server response stream,
creating the String from a translated byte
array.
len - the length of the string to read in bytes
String
java.io.IOException - if an I/O error occurs
java.lang.String readNonUnicodeString(int len,
CharsetInfo charsetInfo)
throws java.io.IOException
String from the server response stream, translating
it from a byte array using the specified character set.
len - the length of the string to read in bytes
String
java.io.IOException - if an I/O error occurs
java.lang.String readString(int len,
CharsetInfo info)
throws java.io.IOException
String from the server response stream, creating
it from a translated byte array.
len - the length of the string to read in bytesinfo - descriptor of the charset to use
String
java.io.IOException - if an I/O error occurs
short readShort()
throws java.io.IOException
short value from the server response stream.
short
java.io.IOException - if an I/O error occurs
int readInt()
throws java.io.IOException
int value from the server response stream.
int
java.io.IOException - if an I/O error occurs
long readLong()
throws java.io.IOException
long value from the server response stream.
long
java.io.IOException - if an I/O error occurs
java.math.BigDecimal readUnsignedLong()
throws java.io.IOException
unsigned long value from the server response stream.
BigDecimal
java.io.IOException - if an I/O error occursint skip(int skip) throws java.io.IOException
skip - the number of bytes to discard
java.io.IOExceptionvoid skipToEnd()
void close()
int getTdsVersion()
intint getServerType()
intjava.io.InputStream getInputStream(int len)
InputStream over the server response.
This method can be used to obtain a stream which can be passed to
InputStreamReaders to assist in reading multi byte
character sets.
len - the number of bytes available in the server response
InputStream built over the server response
private void getPacket()
throws java.io.IOException
java.io.IOException - if an I/O error occurs
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.Semaphore
Simple semaphore class used to serialize access requests over the network connection.
Based on the code originally written by Doug Lea. Once JDK 1.5 is the standard this class can be replaced by thejava.util.concurrent.Sempahore class.
| Field Summary | |
protected long |
permits
Current number of available permits. |
| Constructor Summary | |
Semaphore(long initialPermits)
Create a Semaphore with the given initial number of permits. |
|
| Method Summary | |
void |
acquire()
Wait until a permit is available, and take one. |
boolean |
attempt(long msecs)
Wait at most msecs millisconds for a permit. |
long |
permits()
Return the current number of available permits. |
void |
release()
Release a permit. |
void |
release(long n)
Release N permits. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
protected long permits
| Constructor Detail |
public Semaphore(long initialPermits)
| Method Detail |
public void acquire()
throws java.lang.InterruptedException
java.lang.InterruptedException
public boolean attempt(long msecs)
throws java.lang.InterruptedException
java.lang.InterruptedExceptionpublic void release()
public void release(long n)
release(n) is equivalent in effect to:
for (int i = 0; i < n; ++i) release();But may be more efficient in some semaphore implementations.
java.lang.IllegalArgumentException - if n is negativepublic long permits()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.JtdsStatement
jTDS implementation of the java.sql.Statement interface.
NB. As allowed by the JDBC standard and like most other drivers, this implementation only allows one open result set at a time.
Implementation notes:
I experimented with allowing multiple open result sets as supported by the origianal jTDS but rejected this approach for the following reasons:
Statement,
Connection.createStatement(),
ResultSet| Field Summary | |
protected java.util.ArrayList |
batchValues
Batched SQL Statement array. |
(package private) static int |
BOOLEAN
|
(package private) static int |
CLOSE_ALL_RESULTS
|
(package private) static int |
CLOSE_CURRENT_RESULT
|
protected boolean |
closed
True if this statement is closed. |
protected ColInfo[] |
colMetaData
The cached column meta data. |
protected ConnectionJDBC2 |
connection
The connection owning this statement object. |
protected JtdsResultSet |
currentResult
The current ResultSet. |
protected java.lang.String |
cursorName
The cursor name to be used for positioned updates. |
(package private) static int |
DATALINK
|
(package private) static int |
DEFAULT_FETCH_SIZE
|
protected boolean |
escapeProcessing
True if SQL statements should be preprocessed. |
(package private) static java.lang.Integer |
EXECUTE_FAILED
|
protected int |
fetchDirection
The fetch direction for result sets. |
protected int |
fetchSize
The fetch size (default 100, only used by cursor ResultSets). |
protected JtdsResultSet |
genKeyResultSet
Dummy result set for getGeneratedKeys. |
(package private) static int |
KEEP_CURRENT_RESULT
|
protected int |
maxFieldSize
The maximum field size (not used at present). |
protected int |
maxRows
The maximum number of rows to return (not used at present). |
protected SQLDiagnostic |
messages
SQL Diagnostic exceptions and warnings. |
(package private) static int |
NO_GENERATED_KEYS
|
protected java.util.ArrayList |
openResultSets
List of open result sets. |
protected int |
queryTimeout
The read query timeout in seconds |
protected java.util.LinkedList |
resultQueue
List of queued results (update counts, possibly followed by a ResultSet). |
protected int |
resultSetConcurrency
The concurrency of result sets created by this statement. |
protected int |
resultSetType
The type of result sets created by this statement. |
(package private) static int |
RETURN_GENERATED_KEYS
|
(package private) static java.lang.Integer |
SUCCESS_NO_INFO
|
protected TdsCore |
tds
The TDS object used for server access. |
private int |
updateCount
The current update count. |
| Constructor Summary | |
(package private) |
JtdsStatement(ConnectionJDBC2 connection,
int resultSetType,
int resultSetConcurrency)
Construct a new Statement object. |
| Method Summary | |
void |
addBatch(java.lang.String sql)
|
(package private) void |
addWarning(java.sql.SQLWarning w)
Add an SQLWarning object to the statment warnings list. |
protected void |
cacheResults()
Cache as many results as possible (up to the first ResultSet). |
void |
cancel()
|
protected void |
checkCursorException(java.sql.SQLException e)
Check that the exception is caused by the failure to open a cursor and not by a more serious SQL error. |
protected void |
checkOpen()
Check that this statement is still open. |
void |
clearBatch()
|
void |
clearWarnings()
|
void |
close()
|
(package private) void |
closeAllResultSets()
Close all result sets. |
(package private) void |
closeCurrentResultSet()
Close current result set (if any). |
boolean |
execute(java.lang.String sql)
|
boolean |
execute(java.lang.String sql,
int autoGeneratedKeys)
|
boolean |
execute(java.lang.String sql,
int[] columnIndexes)
|
boolean |
execute(java.lang.String sql,
java.lang.String[] columnNames)
|
int[] |
executeBatch()
Execute batch of SQL Statements. |
private boolean |
executeImpl(java.lang.String sql,
int autoGeneratedKeys,
boolean update)
Implements the common functionality for plain statement execute(java.lang.String)
and {#link #executeUpdate}: basic checks, cleaning up of previous
results, setting up and executing the query and loading the first
results. |
protected java.sql.SQLException |
executeMSBatch(int size,
int executeSize,
java.util.ArrayList counts)
Execute the SQL batch on a MS server. |
java.sql.ResultSet |
executeQuery(java.lang.String sql)
|
protected boolean |
executeSQL(java.lang.String sql,
java.lang.String spName,
ParamInfo[] params,
boolean returnKeys,
boolean update,
boolean useCursor)
Executes any type of SQL. |
protected java.sql.ResultSet |
executeSQLQuery(java.lang.String sql,
java.lang.String spName,
ParamInfo[] params,
boolean useCursor)
Executes SQL to obtain a result set. |
protected java.sql.SQLException |
executeSybaseBatch(int size,
int executeSize,
java.util.ArrayList counts)
Execute the SQL batch on a Sybase server. |
int |
executeUpdate(java.lang.String sql)
|
int |
executeUpdate(java.lang.String sql,
int autoGeneratedKeys)
|
int |
executeUpdate(java.lang.String sql,
int[] columnIndexes)
|
int |
executeUpdate(java.lang.String sql,
java.lang.String[] columnNames)
|
protected void |
finalize()
Called when this object goes out of scope to close any ResultSet object and this statement. |
java.sql.Connection |
getConnection()
|
(package private) int |
getDefaultFetchSize()
Retrieve the default fetch size for this statement. |
int |
getFetchDirection()
|
int |
getFetchSize()
|
java.sql.ResultSet |
getGeneratedKeys()
|
int |
getMaxFieldSize()
|
int |
getMaxRows()
|
(package private) SQLDiagnostic |
getMessages()
Get the statement's warnings list. |
boolean |
getMoreResults()
|
boolean |
getMoreResults(int current)
|
int |
getQueryTimeout()
|
java.sql.ResultSet |
getResultSet()
|
int |
getResultSetConcurrency()
|
int |
getResultSetHoldability()
|
int |
getResultSetType()
|
(package private) TdsCore |
getTds()
Get the Statement's TDS object. |
int |
getUpdateCount()
|
java.sql.SQLWarning |
getWarnings()
|
protected void |
initialize()
Initialize the Statement, by cleaning up all queued and
unprocessed results. |
(package private) static void |
notImplemented(java.lang.String method)
Report that user tried to call a method which has not been implemented. |
private boolean |
processResults(boolean returnKeys,
boolean update)
Queue up update counts into resultQueue until the end of the
response is reached or a ResultSet is encountered. |
void |
setCursorName(java.lang.String name)
|
void |
setEscapeProcessing(boolean enable)
|
void |
setFetchDirection(int direction)
|
void |
setFetchSize(int rows)
|
void |
setMaxFieldSize(int max)
|
void |
setMaxRows(int max)
|
void |
setQueryTimeout(int seconds)
|
protected boolean |
useCursor(boolean returnKeys,
java.lang.String sqlWord)
Determines whether a cursor should be used based on the requested result set type and concurrency, whether a cursor name has been set, the useCursors connection property has been set, the first
word in the SQL query is either SELECT or EXEC/EXECUTE and no generated
keys are returned. |
| Methods inherited from class java.lang.Object |
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
static final int RETURN_GENERATED_KEYS
static final int NO_GENERATED_KEYS
static final int CLOSE_CURRENT_RESULT
static final int KEEP_CURRENT_RESULT
static final int CLOSE_ALL_RESULTS
static final int BOOLEAN
static final int DATALINK
static final java.lang.Integer SUCCESS_NO_INFO
static final java.lang.Integer EXECUTE_FAILED
static final int DEFAULT_FETCH_SIZE
protected ConnectionJDBC2 connection
protected TdsCore tds
protected int queryTimeout
protected JtdsResultSet currentResult
ResultSet.
private int updateCount
protected int fetchDirection
protected int resultSetType
protected int resultSetConcurrency
protected int fetchSize
ResultSets).
protected java.lang.String cursorName
protected boolean closed
protected int maxFieldSize
protected int maxRows
protected boolean escapeProcessing
protected final SQLDiagnostic messages
protected java.util.ArrayList batchValues
protected JtdsResultSet genKeyResultSet
protected final java.util.LinkedList resultQueue
ResultSet).
protected java.util.ArrayList openResultSets
protected ColInfo[] colMetaData
| Constructor Detail |
JtdsStatement(ConnectionJDBC2 connection, int resultSetType, int resultSetConcurrency) throws java.sql.SQLException
connection - The parent connection.resultSetType - The result set type for example TYPE_FORWARD_ONLY.resultSetConcurrency - The concurrency for example CONCUR_READ_ONLY.| Method Detail |
protected void finalize()
throws java.lang.Throwable
ResultSet object and this statement.
java.lang.ThrowableTdsCore getTds()
TdsCore Object.SQLDiagnostic getMessages()
SQLDiagnostic.
protected void checkOpen()
throws java.sql.SQLException
java.sql.SQLException - if statement closed.
protected void checkCursorException(java.sql.SQLException e)
throws java.sql.SQLException
e - the exception returned by the cursor class
java.sql.SQLException - if exception is not due to a cursor error
static void notImplemented(java.lang.String method)
throws java.sql.SQLException
method - The method name to report in the error message.
java.sql.SQLException
void closeCurrentResultSet()
throws java.sql.SQLException
java.sql.SQLException
void closeAllResultSets()
throws java.sql.SQLException
java.sql.SQLExceptionvoid addWarning(java.sql.SQLWarning w)
w - The SQLWarning to add.
protected java.sql.SQLException executeMSBatch(int size,
int executeSize,
java.util.ArrayList counts)
throws java.sql.SQLException
size - the total size of the batchexecuteSize - the maximum number of statements to send in one requestcounts - the returned update counts
SQLException
java.sql.SQLException - if a serious error occurs during execution
protected java.sql.SQLException executeSybaseBatch(int size,
int executeSize,
java.util.ArrayList counts)
throws java.sql.SQLException
PreparedStatements.
size - the total size of the batchexecuteSize - the maximum number of statements to send in one requestcounts - the returned update counts
SQLException
java.sql.SQLException - if a serious error occurs during execution
protected java.sql.ResultSet executeSQLQuery(java.lang.String sql,
java.lang.String spName,
ParamInfo[] params,
boolean useCursor)
throws java.sql.SQLException
sql - the SQL statement to executespName - optional stored procedure nameparams - optional parametersuseCursor - whether a cursor should be created for the SQL
java.sql.SQLException
protected boolean executeSQL(java.lang.String sql,
java.lang.String spName,
ParamInfo[] params,
boolean returnKeys,
boolean update,
boolean useCursor)
throws java.sql.SQLException
sql - the SQL statement to executespName - optional stored procedure nameparams - optional parametersreturnKeys - whether the statement returns generated keysupdate - whether the caller is executeUpdate(java.lang.String)useCursor - whether the requested result set type or concurrency
or connection properties request usage of a cursor
true if the first result is a result set
java.sql.SQLException - if an error condition occurs
private boolean processResults(boolean returnKeys,
boolean update)
throws java.sql.SQLException
resultQueue until the end of the
response is reached or a ResultSet is encountered. Calling
processResults while a ResultSet is open will
not close it, but will consume all remaining rows.
returnKeys - true if a generated keys
ResultSet is expectedupdate - true if the method is called from within
executeUpdate
true if there are any results,
false otherwise
java.sql.SQLException - if an error condition occurs
protected void cacheResults()
throws java.sql.SQLException
ResultSet). Called by ResultSets when the
end is reached.
java.sql.SQLException
protected void initialize()
throws java.sql.SQLException
Statement, by cleaning up all queued and
unprocessed results. Called by all execute methods.
java.sql.SQLException - if an error occurs
private boolean executeImpl(java.lang.String sql,
int autoGeneratedKeys,
boolean update)
throws java.sql.SQLException
execute(java.lang.String)
and {#link #executeUpdate}: basic checks, cleaning up of previous
results, setting up and executing the query and loading the first
results.
sql - an SQL INSERT, UPDATE or
DELETE statement or an SQL statement that
returns nothing, such as an SQL DDL statementautoGeneratedKeys - a flag indicating whether auto-generated keys
should be made available for retrievalupdate - boolean flag indicating whether the caller is
executeUpdate(java.lang.String) -- in this case an exception is
thrown if the first result is not an update count and no
cursor is created (direct execution)
true if the first result is a
ResultSet, false if it's an update
count
java.sql.SQLExceptionexecute(java.lang.String),
executeUpdate(java.lang.String)
protected boolean useCursor(boolean returnKeys,
java.lang.String sqlWord)
useCursors connection property has been set, the first
word in the SQL query is either SELECT or EXEC/EXECUTE and no generated
keys are returned.
returnKeys - indicates whether keys will be returned by the querysqlWord - the first word in the SQL query; can be
null if the caller is
executeQuery(java.lang.String)
true if a cursor should be used, false
if notint getDefaultFetchSize()
ResultSet
public int getFetchDirection()
throws java.sql.SQLException
getFetchDirection in interface java.sql.Statementjava.sql.SQLException
public int getFetchSize()
throws java.sql.SQLException
getFetchSize in interface java.sql.Statementjava.sql.SQLException
public int getMaxFieldSize()
throws java.sql.SQLException
getMaxFieldSize in interface java.sql.Statementjava.sql.SQLException
public int getMaxRows()
throws java.sql.SQLException
getMaxRows in interface java.sql.Statementjava.sql.SQLException
public int getQueryTimeout()
throws java.sql.SQLException
getQueryTimeout in interface java.sql.Statementjava.sql.SQLException
public int getResultSetConcurrency()
throws java.sql.SQLException
getResultSetConcurrency in interface java.sql.Statementjava.sql.SQLException
public int getResultSetHoldability()
throws java.sql.SQLException
getResultSetHoldability in interface java.sql.Statementjava.sql.SQLException
public int getResultSetType()
throws java.sql.SQLException
getResultSetType in interface java.sql.Statementjava.sql.SQLException
public int getUpdateCount()
throws java.sql.SQLException
getUpdateCount in interface java.sql.Statementjava.sql.SQLException
public void cancel()
throws java.sql.SQLException
cancel in interface java.sql.Statementjava.sql.SQLException
public void clearBatch()
throws java.sql.SQLException
clearBatch in interface java.sql.Statementjava.sql.SQLException
public void clearWarnings()
throws java.sql.SQLException
clearWarnings in interface java.sql.Statementjava.sql.SQLException
public void close()
throws java.sql.SQLException
close in interface java.sql.Statementjava.sql.SQLException
public boolean getMoreResults()
throws java.sql.SQLException
getMoreResults in interface java.sql.Statementjava.sql.SQLException
public int[] executeBatch()
throws java.sql.SQLException,
java.sql.BatchUpdateException
EXECUTE_FAILED.
There is a problem with certain statements, returning more update counts
than there are batch operations. (see bug [])
executeBatch in interface java.sql.Statementint[]
java.sql.SQLException
java.sql.BatchUpdateException
public void setFetchDirection(int direction)
throws java.sql.SQLException
setFetchDirection in interface java.sql.Statementjava.sql.SQLException
public void setFetchSize(int rows)
throws java.sql.SQLException
setFetchSize in interface java.sql.Statementjava.sql.SQLException
public void setMaxFieldSize(int max)
throws java.sql.SQLException
setMaxFieldSize in interface java.sql.Statementjava.sql.SQLException
public void setMaxRows(int max)
throws java.sql.SQLException
setMaxRows in interface java.sql.Statementjava.sql.SQLException
public void setQueryTimeout(int seconds)
throws java.sql.SQLException
setQueryTimeout in interface java.sql.Statementjava.sql.SQLException
public boolean getMoreResults(int current)
throws java.sql.SQLException
getMoreResults in interface java.sql.Statementjava.sql.SQLException
public void setEscapeProcessing(boolean enable)
throws java.sql.SQLException
setEscapeProcessing in interface java.sql.Statementjava.sql.SQLException
public int executeUpdate(java.lang.String sql)
throws java.sql.SQLException
executeUpdate in interface java.sql.Statementjava.sql.SQLException
public void addBatch(java.lang.String sql)
throws java.sql.SQLException
addBatch in interface java.sql.Statementjava.sql.SQLException
public void setCursorName(java.lang.String name)
throws java.sql.SQLException
setCursorName in interface java.sql.Statementjava.sql.SQLException
public boolean execute(java.lang.String sql)
throws java.sql.SQLException
execute in interface java.sql.Statementjava.sql.SQLException
public int executeUpdate(java.lang.String sql,
int autoGeneratedKeys)
throws java.sql.SQLException
executeUpdate in interface java.sql.Statementjava.sql.SQLException
public boolean execute(java.lang.String sql,
int autoGeneratedKeys)
throws java.sql.SQLException
execute in interface java.sql.Statementjava.sql.SQLException
public int executeUpdate(java.lang.String sql,
int[] columnIndexes)
throws java.sql.SQLException
executeUpdate in interface java.sql.Statementjava.sql.SQLException
public boolean execute(java.lang.String sql,
int[] columnIndexes)
throws java.sql.SQLException
execute in interface java.sql.Statementjava.sql.SQLException
public java.sql.Connection getConnection()
throws java.sql.SQLException
getConnection in interface java.sql.Statementjava.sql.SQLException
public java.sql.ResultSet getGeneratedKeys()
throws java.sql.SQLException
getGeneratedKeys in interface java.sql.Statementjava.sql.SQLException
public java.sql.ResultSet getResultSet()
throws java.sql.SQLException
getResultSet in interface java.sql.Statementjava.sql.SQLException
public java.sql.SQLWarning getWarnings()
throws java.sql.SQLException
getWarnings in interface java.sql.Statementjava.sql.SQLException
public int executeUpdate(java.lang.String sql,
java.lang.String[] columnNames)
throws java.sql.SQLException
executeUpdate in interface java.sql.Statementjava.sql.SQLException
public boolean execute(java.lang.String sql,
java.lang.String[] columnNames)
throws java.sql.SQLException
execute in interface java.sql.Statementjava.sql.SQLException
public java.sql.ResultSet executeQuery(java.lang.String sql)
throws java.sql.SQLException
executeQuery in interface java.sql.Statementjava.sql.SQLException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.RequestStream
Class to implement an output stream for the server request.
Implementation note:
| Field Summary | |
private byte[] |
buffer
The output packet buffer. |
private int |
bufferPtr
The offset of the next byte to write. |
private int |
bufferSize
The current output buffer size |
private boolean |
isClosed
True if stream is closed. |
private int |
maxPrecision
The maximum decimal precision. |
private byte |
pktType
The request packet type. |
private SharedSocket |
socket
The shared network socket. |
private int |
streamId
The unique stream id. |
| Constructor Summary | |
(package private) |
RequestStream(SharedSocket socket,
int streamId,
int bufferSize,
int maxPrecision)
Construct a RequestStream object. |
| Method Summary | |
(package private) void |
close()
Close the output stream. |
(package private) void |
flush()
Flush the packet to the output stream setting the last packet flag. |
(package private) int |
getBufferSize()
Retrieve the current output packet size. |
(package private) byte |
getMaxDecimalBytes()
Returns the maximum number of bytes required to output a decimal given the current maxPrecision. |
(package private) int |
getMaxPrecision()
Retrive the maximum decimal precision. |
(package private) int |
getServerType()
Retrieve the Server type. |
(package private) int |
getStreamId()
Retrieve the unique stream id. |
(package private) int |
getTdsVersion()
Retrieve the TDS version number. |
private void |
putPacket(int last)
Write the TDS packet to the network. |
(package private) void |
setBufferSize(int size)
Set the output buffer size |
(package private) void |
setPacketType(byte pktType)
Set the current output packet type. |
(package private) void |
write(java.math.BigDecimal value)
Write a BigDecimal value to the output stream. |
(package private) void |
write(byte b)
Write a byte to the output stream. |
(package private) void |
write(byte[] b)
Write an array of bytes to the output stream. |
(package private) void |
write(byte[] b,
int off,
int len)
Write a partial byte buffer to the output stream. |
(package private) void |
write(char[] s,
int off,
int len)
Write a char array object to the output stream. |
(package private) void |
write(double f)
Write a double value to the output stream. |
(package private) void |
write(float f)
Write a float value to the output stream. |
(package private) void |
write(int i)
Write an int value to the output stream. |
(package private) void |
write(long l)
Write a long value to the output stream. |
(package private) void |
write(short s)
Write a short value to the output stream. |
(package private) void |
write(java.lang.String s)
Write a String object to the output stream. |
(package private) void |
writeAscii(java.lang.String s)
Write a String to the output stream as translated bytes. |
(package private) void |
writeReaderBytes(java.io.Reader in,
int length)
Copy the contents of a Reader stream to the server as bytes. |
(package private) void |
writeReaderChars(java.io.Reader in,
int length)
Copy the contents of a Reader stream to the server. |
(package private) void |
writeStreamBytes(java.io.InputStream in,
int length)
Copy the contents of an InputStream to the server. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private final SharedSocket socket
private byte[] buffer
private int bufferPtr
private byte pktType
private final int streamId
private boolean isClosed
private int bufferSize
private int maxPrecision
| Constructor Detail |
RequestStream(SharedSocket socket, int streamId, int bufferSize, int maxPrecision)
socket - the shared socket object to write tostreamId - the unique id for this streambufferSize - the initial buffer size to use (the current network
packet size)maxPrecision - the maximum precision for numeric/decimal types| Method Detail |
void setBufferSize(int size)
size - The new buffer size (>= TdsCore.MIN_PKT_SIZE <= TdsCore.MAX_PKT_SIZE).int getBufferSize()
int.int getMaxPrecision()
int.byte getMaxDecimalBytes()
maxPrecision.
int getStreamId()
int.void setPacketType(byte pktType)
pktType - The packet type eg TdsCore.QUERY_PKT.
void write(byte b)
throws java.io.IOException
b - The byte value to write.
java.io.IOException
void write(byte[] b)
throws java.io.IOException
b - The byte array to write.
java.io.IOException
void write(byte[] b,
int off,
int len)
throws java.io.IOException
b - The byte array buffer.off - The offset into the byte array.len - The number of bytes to write.
java.io.IOException
void write(int i)
throws java.io.IOException
i - The int value to write.
java.io.IOException
void write(short s)
throws java.io.IOException
s - The short value to write.
java.io.IOException
void write(long l)
throws java.io.IOException
l - The long value to write.
java.io.IOException
void write(double f)
throws java.io.IOException
f - The double value to write.
java.io.IOException
void write(float f)
throws java.io.IOException
f - The float value to write.
java.io.IOException
void write(java.lang.String s)
throws java.io.IOException
s - The String to write.
java.io.IOException
void write(char[] s,
int off,
int len)
throws java.io.IOException
s - The char[] to write.
java.io.IOException
void writeAscii(java.lang.String s)
throws java.io.IOException
s - The String to write.
java.io.IOException
void writeStreamBytes(java.io.InputStream in,
int length)
throws java.io.IOException
in - The InputStream to read.length - The length of the stream.
java.io.IOException
void writeReaderChars(java.io.Reader in,
int length)
throws java.io.IOException
in - The Reader object with the data.length - The length of the data in characters.
java.io.IOException
void writeReaderBytes(java.io.Reader in,
int length)
throws java.io.IOException
NB. Only reliable where the charset is single byte.
in - The Reader object with the data.length - The length of the data in bytes.
java.io.IOException
void write(java.math.BigDecimal value)
throws java.io.IOException
value - The BigDecimal value to write.
java.io.IOException
void flush()
throws java.io.IOException
java.io.IOExceptionvoid close()
int getTdsVersion()
int.int getServerType()
int.
private void putPacket(int last)
throws java.io.IOException
last - Set to 1 if this is the last packet else 0.
java.io.IOException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.JtdsResultSetMetaData
jTDS implementation of the java.sql.ResultSetMetaData interface.
Implementation notes:
| Field Summary | |
private int |
columnCount
|
private ColInfo[] |
columns
|
private boolean |
useLOBs
|
| Fields inherited from interface java.sql.ResultSetMetaData |
columnNoNulls, columnNullable, columnNullableUnknown |
| Constructor Summary | |
(package private) |
JtdsResultSetMetaData(ColInfo[] columns,
int columnCount,
boolean useLOBs)
Construct ResultSetMetaData object over the current ColInfo array. |
| Method Summary | |
java.lang.String |
getCatalogName(int column)
|
(package private) ColInfo |
getColumn(int column)
Return the column descriptor given a column index. |
java.lang.String |
getColumnClassName(int column)
|
int |
getColumnCount()
|
int |
getColumnDisplaySize(int column)
|
java.lang.String |
getColumnLabel(int column)
|
java.lang.String |
getColumnName(int column)
|
int |
getColumnType(int column)
|
java.lang.String |
getColumnTypeName(int column)
|
int |
getPrecision(int column)
|
int |
getScale(int column)
|
java.lang.String |
getSchemaName(int column)
|
java.lang.String |
getTableName(int column)
|
boolean |
isAutoIncrement(int column)
|
boolean |
isCaseSensitive(int column)
|
boolean |
isCurrency(int column)
|
boolean |
isDefinitelyWritable(int column)
|
int |
isNullable(int column)
|
boolean |
isReadOnly(int column)
|
boolean |
isSearchable(int column)
|
boolean |
isSigned(int column)
|
boolean |
isWritable(int column)
|
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private final ColInfo[] columns
private final int columnCount
private final boolean useLOBs
| Constructor Detail |
JtdsResultSetMetaData(ColInfo[] columns, int columnCount, boolean useLOBs)
columns - The current ColInfo row descriptor array.columnCount - The number of visible columns.| Method Detail |
ColInfo getColumn(int column) throws java.sql.SQLException
column - The column index (from 1 .. n).
ColInfo.
- Throws:
java.sql.SQLException
public int getColumnCount()
throws java.sql.SQLException
getColumnCount in interface java.sql.ResultSetMetaDatajava.sql.SQLException
public int getColumnDisplaySize(int column)
throws java.sql.SQLException
getColumnDisplaySize in interface java.sql.ResultSetMetaDatajava.sql.SQLException
public int getColumnType(int column)
throws java.sql.SQLException
getColumnType in interface java.sql.ResultSetMetaDatajava.sql.SQLException
public int getPrecision(int column)
throws java.sql.SQLException
getPrecision in interface java.sql.ResultSetMetaDatajava.sql.SQLException
public int getScale(int column)
throws java.sql.SQLException
getScale in interface java.sql.ResultSetMetaDatajava.sql.SQLException
public int isNullable(int column)
throws java.sql.SQLException
isNullable in interface java.sql.ResultSetMetaDatajava.sql.SQLException
public boolean isAutoIncrement(int column)
throws java.sql.SQLException
isAutoIncrement in interface java.sql.ResultSetMetaDatajava.sql.SQLException
public boolean isCaseSensitive(int column)
throws java.sql.SQLException
isCaseSensitive in interface java.sql.ResultSetMetaDatajava.sql.SQLException
public boolean isCurrency(int column)
throws java.sql.SQLException
isCurrency in interface java.sql.ResultSetMetaDatajava.sql.SQLException
public boolean isDefinitelyWritable(int column)
throws java.sql.SQLException
isDefinitelyWritable in interface java.sql.ResultSetMetaDatajava.sql.SQLException
public boolean isReadOnly(int column)
throws java.sql.SQLException
isReadOnly in interface java.sql.ResultSetMetaDatajava.sql.SQLException
public boolean isSearchable(int column)
throws java.sql.SQLException
isSearchable in interface java.sql.ResultSetMetaDatajava.sql.SQLException
public boolean isSigned(int column)
throws java.sql.SQLException
isSigned in interface java.sql.ResultSetMetaDatajava.sql.SQLException
public boolean isWritable(int column)
throws java.sql.SQLException
isWritable in interface java.sql.ResultSetMetaDatajava.sql.SQLException
public java.lang.String getCatalogName(int column)
throws java.sql.SQLException
getCatalogName in interface java.sql.ResultSetMetaDatajava.sql.SQLException
public java.lang.String getColumnClassName(int column)
throws java.sql.SQLException
getColumnClassName in interface java.sql.ResultSetMetaDatajava.sql.SQLException
public java.lang.String getColumnLabel(int column)
throws java.sql.SQLException
getColumnLabel in interface java.sql.ResultSetMetaDatajava.sql.SQLException
public java.lang.String getColumnName(int column)
throws java.sql.SQLException
getColumnName in interface java.sql.ResultSetMetaDatajava.sql.SQLException
public java.lang.String getColumnTypeName(int column)
throws java.sql.SQLException
getColumnTypeName in interface java.sql.ResultSetMetaDatajava.sql.SQLException
public java.lang.String getSchemaName(int column)
throws java.sql.SQLException
getSchemaName in interface java.sql.ResultSetMetaDatajava.sql.SQLException
public java.lang.String getTableName(int column)
throws java.sql.SQLException
getTableName in interface java.sql.ResultSetMetaDatajava.sql.SQLException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.XASupport
This class contains static utility methods used to implement distributed transactions. For SQL Server 2000 the driver can provide true distributed transactions provided that the external stored procedure in JtdsXA.dll is installed. For other types of server only an emulation is available at this stage.
| Field Summary | |
private static java.lang.String |
TM_ID
xa_open login string unique to jTDS. |
private static int |
XA_CLOSE
|
private static int |
XA_COMMIT
|
private static int |
XA_COMPLETE
|
private static int |
XA_END
|
private static int |
XA_FORGET
|
private static int |
XA_OPEN
|
private static int |
XA_PREPARE
|
private static int |
XA_RECOVER
|
private static int |
XA_RMID
The Resource Manager ID allocated by jTDS |
private static int |
XA_ROLLBACK
|
private static int |
XA_START
|
private static int |
XA_TRACE
Set this field to 1 to enable XA tracing. |
| Constructor Summary | |
private |
XASupport()
|
| Method Summary | |
static void |
raiseXAException(int errorCode)
Construct and throw an XAException with an explanatory message and the XA error code set. |
static void |
raiseXAException(java.sql.SQLException sqle)
Construct and throw an XAException with an explanatory message derived from the
SQLException and the XA error code set to XAER_RMFAIL. |
private static byte[] |
toBytesXid(javax.transaction.xa.Xid xid)
Format an XA transaction ID into a 140 byte array. |
static void |
xa_close(java.sql.Connection connection,
int xaConId)
Invoke the xa_close routine on the SQL Server. |
static void |
xa_commit(java.sql.Connection connection,
int xaConId,
javax.transaction.xa.Xid xid,
boolean onePhase)
Invoke the xa_commit routine on the SQL Server. |
static void |
xa_end(java.sql.Connection connection,
int xaConId,
javax.transaction.xa.Xid xid,
int flags)
Invoke the xa_end routine on the SQL Server. |
static void |
xa_forget(java.sql.Connection connection,
int xaConId,
javax.transaction.xa.Xid xid)
Invoke the xa_forget routine on the SQL Server. |
static int |
xa_open(java.sql.Connection connection)
Invoke the xa_open routine on the SQL Server. |
static int |
xa_prepare(java.sql.Connection connection,
int xaConId,
javax.transaction.xa.Xid xid)
Invoke the xa_prepare routine on the SQL Server. |
static javax.transaction.xa.Xid[] |
xa_recover(java.sql.Connection connection,
int xaConId,
int flags)
Invoke the xa_recover routine on the SQL Server. |
static void |
xa_rollback(java.sql.Connection connection,
int xaConId,
javax.transaction.xa.Xid xid)
Invoke the xa_rollback routine on the SQL Server. |
static void |
xa_start(java.sql.Connection connection,
int xaConId,
javax.transaction.xa.Xid xid,
int flags)
Invoke the xa_start routine on the SQL Server. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private static final int XA_RMID
private static final java.lang.String TM_ID
private static final int XA_OPEN
private static final int XA_CLOSE
private static final int XA_START
private static final int XA_END
private static final int XA_ROLLBACK
private static final int XA_PREPARE
private static final int XA_COMMIT
private static final int XA_RECOVER
private static final int XA_FORGET
private static final int XA_COMPLETE
private static final int XA_TRACE
| Constructor Detail |
private XASupport()
| Method Detail |
public static int xa_open(java.sql.Connection connection)
throws java.sql.SQLException
connection - the parent XAConnection object
java.sql.SQLException
public static void xa_close(java.sql.Connection connection,
int xaConId)
throws java.sql.SQLException
connection - JDBC Connection to be enlisted in the transactionxaConId - the connection ID allocated by the server
java.sql.SQLException
public static void xa_start(java.sql.Connection connection,
int xaConId,
javax.transaction.xa.Xid xid,
int flags)
throws javax.transaction.xa.XAException
connection - JDBC Connection to be enlisted in the transactionxaConId - the connection ID allocated by the serverxid - the XA Transaction ID objectflags - XA Flags for start command
javax.transaction.xa.XAException - if an error condition occurs
public static void xa_end(java.sql.Connection connection,
int xaConId,
javax.transaction.xa.Xid xid,
int flags)
throws javax.transaction.xa.XAException
connection - JDBC Connection enlisted in the transactionxaConId - the connection ID allocated by the serverxid - the XA Transaction ID objectflags - XA Flags for start command
javax.transaction.xa.XAException - if an error condition occurs
public static int xa_prepare(java.sql.Connection connection,
int xaConId,
javax.transaction.xa.Xid xid)
throws javax.transaction.xa.XAException
connection - JDBC Connection enlisted in the transaction.xaConId - The connection ID allocated by the server.xid - The XA Transaction ID object.
int.
javax.transaction.xa.XAException - if an error condition occurs
public static void xa_commit(java.sql.Connection connection,
int xaConId,
javax.transaction.xa.Xid xid,
boolean onePhase)
throws javax.transaction.xa.XAException
connection - JDBC Connection enlisted in the transactionxaConId - the connection ID allocated by the serverxid - the XA Transaction ID objectonePhase - true if single phase commit required
javax.transaction.xa.XAException - if an error condition occurs
public static void xa_rollback(java.sql.Connection connection,
int xaConId,
javax.transaction.xa.Xid xid)
throws javax.transaction.xa.XAException
connection - JDBC Connection enlisted in the transactionxaConId - the connection ID allocated by the serverxid - the XA Transaction ID object
javax.transaction.xa.XAException - if an error condition occurs
public static javax.transaction.xa.Xid[] xa_recover(java.sql.Connection connection,
int xaConId,
int flags)
throws javax.transaction.xa.XAException
connection - JDBC Connection enlisted in the transactionxaConId - the connection ID allocated by the serverflags - XA Flags for start command
Xid[]
javax.transaction.xa.XAException - if an error condition occurs
public static void xa_forget(java.sql.Connection connection,
int xaConId,
javax.transaction.xa.Xid xid)
throws javax.transaction.xa.XAException
connection - JDBC Connection enlisted in the transactionxaConId - the connection ID allocated by the serverxid - the XA Transaction ID object
javax.transaction.xa.XAException - if an error condition occurs
public static void raiseXAException(java.sql.SQLException sqle)
throws javax.transaction.xa.XAException
XAException with an explanatory message derived from the
SQLException and the XA error code set to XAER_RMFAIL.
sqle - The SQLException.
javax.transaction.xa.XAException - exception derived from the code>SQLException
public static void raiseXAException(int errorCode)
throws javax.transaction.xa.XAException
XAException with an explanatory message and the XA error code set.
errorCode - the XA Error code
javax.transaction.xa.XAException - the constructed exceptionprivate static byte[] toBytesXid(javax.transaction.xa.Xid xid)
xid - the XA transaction ID
byte[]
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.ClobImpl
An in-memory or disk based representation of character data.
Implementation note:BlobBuffer class. Each character is stored in 2
sequential bytes using UTF-16LE encoding.
getSubstring, position and the
set methods refer to 16 bit characters only. The presence
of supplementary characters will cause the wrong characters to be
accessed.
| Field Summary | |
private BlobBuffer |
blobBuffer
The underlying BlobBuffer. |
private static java.lang.String |
EMPTY_CLOB
0 length String as initial value for empty
Clobs. |
| Constructor Summary | |
(package private) |
ClobImpl(ConnectionJDBC2 connection)
Constructs a new empty Clob instance. |
(package private) |
ClobImpl(ConnectionJDBC2 connection,
java.lang.String str)
Constructs a new initialized Clob instance. |
| Method Summary | |
java.io.InputStream |
getAsciiStream()
|
(package private) BlobBuffer |
getBlobBuffer()
Obtain this object's backing BlobBuffer object. |
java.io.Reader |
getCharacterStream()
|
java.lang.String |
getSubString(long pos,
int length)
|
long |
length()
|
long |
position(java.sql.Clob searchStr,
long start)
|
long |
position(java.lang.String searchStr,
long start)
|
java.io.OutputStream |
setAsciiStream(long pos)
|
java.io.Writer |
setCharacterStream(long pos)
|
int |
setString(long pos,
java.lang.String str)
|
int |
setString(long pos,
java.lang.String str,
int offset,
int len)
|
void |
truncate(long len)
|
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private static final java.lang.String EMPTY_CLOB
String as initial value for empty
Clobs.
private final BlobBuffer blobBuffer
BlobBuffer.
| Constructor Detail |
ClobImpl(ConnectionJDBC2 connection)
Clob instance.
connection - a reference to the parent connection objectClobImpl(ConnectionJDBC2 connection, java.lang.String str)
Clob instance.
connection - a reference to the parent connection objectstr - the String object to encapsulate| Method Detail |
BlobBuffer getBlobBuffer()
BlobBuffer object.
BlobBuffer
public java.io.InputStream getAsciiStream()
throws java.sql.SQLException
getAsciiStream in interface java.sql.Clobjava.sql.SQLException
public java.io.Reader getCharacterStream()
throws java.sql.SQLException
getCharacterStream in interface java.sql.Clobjava.sql.SQLException
public java.lang.String getSubString(long pos,
int length)
throws java.sql.SQLException
getSubString in interface java.sql.Clobjava.sql.SQLException
public long length()
throws java.sql.SQLException
length in interface java.sql.Clobjava.sql.SQLException
public long position(java.lang.String searchStr,
long start)
throws java.sql.SQLException
position in interface java.sql.Clobjava.sql.SQLException
public long position(java.sql.Clob searchStr,
long start)
throws java.sql.SQLException
position in interface java.sql.Clobjava.sql.SQLException
public java.io.OutputStream setAsciiStream(long pos)
throws java.sql.SQLException
setAsciiStream in interface java.sql.Clobjava.sql.SQLException
public java.io.Writer setCharacterStream(long pos)
throws java.sql.SQLException
setCharacterStream in interface java.sql.Clobjava.sql.SQLException
public int setString(long pos,
java.lang.String str)
throws java.sql.SQLException
setString in interface java.sql.Clobjava.sql.SQLException
public int setString(long pos,
java.lang.String str,
int offset,
int len)
throws java.sql.SQLException
setString in interface java.sql.Clobjava.sql.SQLException
public void truncate(long len)
throws java.sql.SQLException
truncate in interface java.sql.Clobjava.sql.SQLException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
Exceptions
ProtocolException |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.ColInfo
This class is a descriptor for result set columns.
Implementation note:
Getter/setter methods have not been provided to avoid clutter as this class is used in many places in the driver. As the class is package private this seems reasonable.
| Field Summary | |
(package private) int |
bufferSize
Column buffer (max) size |
(package private) java.lang.String |
catalog
Database owning this column |
(package private) CharsetInfo |
charsetInfo
Character set descriptor (if different from default) |
(package private) byte[] |
collation
MS SQL2000 collation |
(package private) int |
displaySize
Column display size |
(package private) boolean |
isCaseSensitive
Column name is case sensitive |
(package private) boolean |
isHidden
Column should be hidden |
(package private) boolean |
isIdentity
Column is an indentity column |
(package private) boolean |
isKey
Column may be used as a key |
(package private) boolean |
isWriteable
Column may be updated |
(package private) int |
jdbcType
JDBC type constant from java.sql.Types |
(package private) java.lang.String |
name
Column label / name |
(package private) int |
nullable
Column data type supports SQL NULL |
(package private) int |
precision
Column decimal precision |
(package private) java.lang.String |
realName
Column actual table name |
(package private) int |
scale
Column decimal scale |
(package private) java.lang.String |
schema
User owning this column |
(package private) java.lang.String |
sqlType
The SQL type name for this column. |
(package private) java.lang.String |
tableName
Table name owning this column |
(package private) int |
tdsType
Internal TDS data type |
(package private) int |
userType
Database ID for UDT |
| Constructor Summary | |
ColInfo()
|
|
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
int tdsType
int jdbcType
java.lang.String realName
java.lang.String name
java.lang.String tableName
java.lang.String catalog
java.lang.String schema
int nullable
boolean isCaseSensitive
boolean isWriteable
boolean isIdentity
boolean isKey
boolean isHidden
int userType
byte[] collation
CharsetInfo charsetInfo
int displaySize
int bufferSize
int precision
int scale
java.lang.String sqlType
| Constructor Detail |
public ColInfo()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.Messages
Support class for Messages.properties.
| Field Summary | |
private static java.lang.String |
DEFAULT_RESOURCE
Default name for resource bundle containing the messages. |
private static java.util.ResourceBundle |
defaultResource
Cached resource bundle containing the messages. |
| Constructor Summary | |
private |
Messages()
Default constructor. |
| Method Summary | |
static java.lang.String |
get(java.lang.String key)
Get runtime message using supplied key. |
static java.lang.String |
get(java.lang.String key,
java.lang.Object param1)
Get runtime message using supplied key and substitute parameter into message. |
private static java.lang.String |
get(java.lang.String key,
java.lang.Object[] arguments)
Get runtime error using supplied key and substitute parameters into message. |
(package private) static java.lang.String |
get(java.lang.String key,
java.lang.Object param1,
java.lang.Object param2)
Get runtime message using supplied key and substitute parameters into message. |
(package private) static void |
loadDriverProperties(java.util.Map propertyMap,
java.util.Map descriptionMap)
Retrieve the list of driver property names and driver property descriptions from Messages.properties and populate
them into Map objects.
|
private static java.util.ResourceBundle |
loadResourceBundle()
Load the DEFAULT_RESOURCE resource bundle. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private static final java.lang.String DEFAULT_RESOURCE
private static java.util.ResourceBundle defaultResource
ResourceBundle does caching internally but this caching
involves a lot of string operations to generate the keys used for
caching, leading to a lot of StringBuffer reallocation. In
one run through the complete jTDS test suite there were over 60000
allocations and reallocations (about one for each get()
call).
| Constructor Detail |
private Messages()
| Method Detail |
public static java.lang.String get(java.lang.String key)
key - The key of the message in Messages.properties
String.
public static java.lang.String get(java.lang.String key,
java.lang.Object param1)
key - The key of the message in Messages.propertiesparam1 - The object to insert into message.
String.
static java.lang.String get(java.lang.String key,
java.lang.Object param1,
java.lang.Object param2)
key - The key of the message in Messages.propertiesparam1 - The object to insert into message.param2 - The object to insert into message.
String.
private static java.lang.String get(java.lang.String key,
java.lang.Object[] arguments)
key - The key of the error message in Messages.propertiesarguments - The objects to insert into the message.
String.
static void loadDriverProperties(java.util.Map propertyMap,
java.util.Map descriptionMap)
Messages.properties and populate
them into Map objects.
The keys used to populate both propertyMap and
descriptionMap are guaranteed to match up as long
as the properties defined in Messages.properties
are well-formed.
propertyMap - The map of property names to be populated.descriptionMap - The map of property descriptions to be populated.private static java.util.ResourceBundle loadResourceBundle()
DEFAULT_RESOURCE resource bundle.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.DateTime
Encapsulates Sybase date/time values and provides conversions to and from Java classes.
| Field Summary | |
private static java.lang.ThreadLocal |
calendar
Per thread instance of Calendar used for conversions. |
private int |
date
The date component of the server datetime value. |
(package private) static int |
DATE_NOT_USED
Indicates date value not used. |
private java.sql.Date |
dateValue
Cached value of the datetime as a java.sql.Date. |
private short |
day
Unpacked day value. |
private short |
hour
Unpacked hour value. |
private short |
millis
Unpacked millisecond value. |
private short |
minute
Unpacked minute value. |
private short |
month
Unpacked month value. |
private short |
second
Unpacked second value. |
private java.lang.String |
stringValue
Cached value of the datetime as a String. |
private int |
time
The time component of the server datetime value. |
(package private) static int |
TIME_NOT_USED
Indicates time value not used. |
private java.sql.Time |
timeValue
Cached value of the datetime as a java.sql.Time. |
private java.sql.Timestamp |
tsValue
Cached value of the datetime as a java.sql.Timestamp. |
private boolean |
unpacked
Indicates server datetime values have been unpacked. |
private short |
year
Unpacked year value. |
| Constructor Summary | |
(package private) |
DateTime(java.sql.Date d)
Constructs a DateTime object from a java.sql.Date. |
(package private) |
DateTime(int date,
int time)
Constructs a DateTime object from the two integer components of a datetime. |
(package private) |
DateTime(short date,
short time)
Constructs a DateTime object from the two short components of a smalldatetime. |
(package private) |
DateTime(java.sql.Time t)
Constructs a DateTime object from a java.sql.Time. |
(package private) |
DateTime(java.sql.Timestamp ts)
Constructs a DateTime object from a java.sql.Timestamp. |
| Method Summary | |
(package private) int |
getDate()
Retrieves the date component of a datetime value. |
(package private) int |
getTime()
Retrieves the time component of a datetime value. |
void |
packDate()
Converts a calendar date into days since 1900 (Sybase epoch). |
void |
packTime()
Converts separate time components into a datetime time value. |
java.sql.Date |
toDate()
Retrieves the current datetime value as a Date. |
java.lang.Object |
toObject()
Retrieves the current datetime value as a Time, Date or Timestamp. |
java.lang.String |
toString()
Retrieves the current datetime value as a String. |
java.sql.Time |
toTime()
Retrieves the current datetime value as a Time. |
java.sql.Timestamp |
toTimestamp()
Retrieves the current datetime value as a Timestamp. |
private void |
unpackDateTime()
Converts a Julian datetime from the Sybase epoch of 1900-01-01 to the equivalent unpacked year/month/day etc. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
private static java.lang.ThreadLocal calendar
static final int DATE_NOT_USED
static final int TIME_NOT_USED
private int date
private int time
private short year
private short month
private short day
private short hour
private short minute
private short second
private short millis
private boolean unpacked
private java.lang.String stringValue
String.
private java.sql.Timestamp tsValue
java.sql.Timestamp.
private java.sql.Date dateValue
java.sql.Date.
private java.sql.Time timeValue
java.sql.Time.
| Constructor Detail |
DateTime(int date,
int time)
date - server date fieldtime - server time field
DateTime(short date,
short time)
date - server date fieldtime - server time fieldDateTime(java.sql.Timestamp ts) throws java.sql.SQLException
java.sql.Timestamp.
ts - Timestamp object representing the datetime
java.sql.SQLException - if the date is out of rangeDateTime(java.sql.Time t) throws java.sql.SQLException
java.sql.Time.
t - Time object representing the datetime
java.sql.SQLException - if the time (date) is out of rangeDateTime(java.sql.Date d) throws java.sql.SQLException
java.sql.Date.
d - Date object representing the datetime
java.sql.SQLException - if the Date is out of range| Method Detail |
int getDate()
intint getTime()
intprivate void unpackDateTime()
SUBROUTINE GDATE (JD, YEAR,MONTH,DAY)
C
C---COMPUTES THE GREGORIAN CALENDAR DATE (YEAR,MONTH,DAY)
C GIVEN THE JULIAN DATE (JD).
C
INTEGER JD,YEAR,MONTH,DAY,I,J,K
C
L= JD+68569
N= 4*L/146097
L= L-(146097*N+3)/4
I= 4000*(L+1)/1461001
L= L-1461*I/4+31
J= 80*L/2447
K= L-2447*J/80
L= J/11
J= J+2-12*L
I= 100*(N-49)+I+L
C
YEAR= I
MONTH= J
DAY= K
C
RETURN
END
public void packDate()
throws java.sql.SQLException
Algorithm from Fliegel, H F and van Flandern, T C (1968). Communications of the ACM, Vol 11, No 10 (October, 1968).
INTEGER FUNCTION JD (YEAR,MONTH,DAY)
C
C---COMPUTES THE JULIAN DATE (JD) GIVEN A GREGORIAN CALENDAR
C DATE (YEAR,MONTH,DAY).
C
INTEGER YEAR,MONTH,DAY,I,J,K
C
I= YEAR
J= MONTH
K= DAY
C
JD= K-32075+1461*(I+4800+(J-14)/12)/4+367*(J-2-(J-14)/12*12)
2 /12-3*((I+4900+(J-14)/12)/100)/4
C
RETURN
END
java.sql.SQLException - if the date is outside the accepted range, 1753-9999public void packTime()
public java.sql.Timestamp toTimestamp()
java.sql.Timestamppublic java.sql.Date toDate()
java.sql.Datepublic java.sql.Time toTime()
java.sql.Timepublic java.lang.Object toObject()
java.lang.Objectpublic java.lang.String toString()
String
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.Driver
jTDS implementation of the java.sql.Driver interface.
Implementation note:
Driver| Field Summary | |
static java.lang.String |
APPNAME
|
static java.lang.String |
BATCHSIZE
|
static java.lang.String |
BINDADDRESS
|
static java.lang.String |
BUFFERDIR
|
static java.lang.String |
BUFFERMAXMEMORY
|
static java.lang.String |
BUFFERMINPACKETS
|
static java.lang.String |
CACHEMETA
|
static java.lang.String |
CHARSET
|
static java.lang.String |
DATABASENAME
|
static java.lang.String |
DOMAIN
|
private static java.lang.String |
driverPrefix
URL prefix used by the driver (i.e jdbc:jtds:). |
static java.lang.String |
INSTANCE
|
static boolean |
JDBC3
Set if the JDBC specification to implement is 3.0 or greater. |
static java.lang.String |
LANGUAGE
|
static java.lang.String |
LASTUPDATECOUNT
|
static java.lang.String |
LOBBUFFER
|
static java.lang.String |
LOGFILE
|
static java.lang.String |
LOGINTIMEOUT
|
static java.lang.String |
MACADDRESS
|
(package private) static int |
MAJOR_VERSION
Driver major version. |
static java.lang.String |
MAXSTATEMENTS
|
(package private) static int |
MINOR_VERSION
Driver minor version. |
(package private) static java.lang.String |
MISC_VERSION
Driver version miscellanea (e.g "-rc2", ".1" or null). |
static java.lang.String |
NAMEDPIPE
|
static java.lang.String |
PACKETSIZE
|
static java.lang.String |
PASSWORD
|
static java.lang.String |
PORTNUMBER
|
static java.lang.String |
PREPARESQL
|
static java.lang.String |
PROCESSID
|
static java.lang.String |
PROGNAME
|
static java.lang.String |
SENDSTRINGPARAMETERSASUNICODE
|
static java.lang.String |
SERVERNAME
|
static java.lang.String |
SERVERTYPE
|
static java.lang.String |
SOKEEPALIVE
|
static java.lang.String |
SOTIMEOUT
|
static int |
SQLSERVER
Microsoft SQL Server. |
static java.lang.String |
SSL
|
static int |
SYBASE
Sybase ASE. |
static java.lang.String |
TCPNODELAY
|
static java.lang.String |
TDS
|
static int |
TDS42
TDS 4.2 protocol (SQL Server 6.5 and later and Sybase 9 and later). |
static int |
TDS50
TDS 5.0 protocol (Sybase 10 and later). |
static int |
TDS70
TDS 7.0 protocol (SQL Server 7.0 and later). |
static int |
TDS80
TDS 8.0 protocol (SQL Server 2000 and later) |
static int |
TDS81
TDS 8.1 protocol (SQL Server 2000 SP1 and later). |
static java.lang.String |
USECURSORS
|
static java.lang.String |
USEJCIFS
|
static java.lang.String |
USELOBS
|
static java.lang.String |
USENTLMV2
|
static java.lang.String |
USER
|
static java.lang.String |
WSID
|
static java.lang.String |
XAEMULATION
|
| Constructor Summary | |
Driver()
|
|
| Method Summary | |
boolean |
acceptsURL(java.lang.String url)
|
java.sql.Connection |
connect(java.lang.String url,
java.util.Properties info)
|
private static java.util.Map |
createChoicesMap()
Creates a map of driver properties whose choices
field should be set when calling
getPropertyInfo(String, Properties).
|
private static java.util.Map |
createRequiredTrueMap()
Creates a map of driver properties that should be marked as required when calling getPropertyInfo(String, Properties).
|
int |
getMajorVersion()
|
int |
getMinorVersion()
|
java.sql.DriverPropertyInfo[] |
getPropertyInfo(java.lang.String url,
java.util.Properties props)
|
static java.lang.String |
getVersion()
Returns the driver version. |
boolean |
jdbcCompliant()
|
static void |
main(java.lang.String[] args)
|
private static int |
nextToken(java.lang.String url,
int pos,
java.lang.StringBuffer token)
Extract the next lexical token from the URL. |
private static java.util.Properties |
parseURL(java.lang.String url,
java.util.Properties info)
Parse the driver URL and extract the properties. |
private java.util.Properties |
setupConnectProperties(java.lang.String url,
java.util.Properties info)
Sets up properties for the connect(String, java.util.Properties) method. |
java.lang.String |
toString()
Returns the string form of the object. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
private static java.lang.String driverPrefix
jdbc:jtds:).
static final int MAJOR_VERSION
static final int MINOR_VERSION
static final java.lang.String MISC_VERSION
null).
public static final boolean JDBC3
public static final int TDS42
public static final int TDS50
public static final int TDS70
public static final int TDS80
public static final int TDS81
public static final int SQLSERVER
public static final int SYBASE
public static final java.lang.String APPNAME
public static final java.lang.String BATCHSIZE
public static final java.lang.String BINDADDRESS
public static final java.lang.String BUFFERDIR
public static final java.lang.String BUFFERMAXMEMORY
public static final java.lang.String BUFFERMINPACKETS
public static final java.lang.String CACHEMETA
public static final java.lang.String CHARSET
public static final java.lang.String DATABASENAME
public static final java.lang.String DOMAIN
public static final java.lang.String INSTANCE
public static final java.lang.String LANGUAGE
public static final java.lang.String LASTUPDATECOUNT
public static final java.lang.String LOBBUFFER
public static final java.lang.String LOGFILE
public static final java.lang.String LOGINTIMEOUT
public static final java.lang.String MACADDRESS
public static final java.lang.String MAXSTATEMENTS
public static final java.lang.String NAMEDPIPE
public static final java.lang.String PACKETSIZE
public static final java.lang.String PASSWORD
public static final java.lang.String PORTNUMBER
public static final java.lang.String PREPARESQL
public static final java.lang.String PROGNAME
public static final java.lang.String SERVERNAME
public static final java.lang.String SERVERTYPE
public static final java.lang.String SOTIMEOUT
public static final java.lang.String SOKEEPALIVE
public static final java.lang.String PROCESSID
public static final java.lang.String SSL
public static final java.lang.String TCPNODELAY
public static final java.lang.String TDS
public static final java.lang.String USECURSORS
public static final java.lang.String USEJCIFS
public static final java.lang.String USENTLMV2
public static final java.lang.String USELOBS
public static final java.lang.String USER
public static final java.lang.String SENDSTRINGPARAMETERSASUNICODE
public static final java.lang.String WSID
public static final java.lang.String XAEMULATION
| Constructor Detail |
public Driver()
| Method Detail |
public int getMajorVersion()
getMajorVersion in interface java.sql.Driverpublic int getMinorVersion()
getMinorVersion in interface java.sql.Driverpublic static final java.lang.String getVersion()
Per [908906] 0.7: Static Version information, please.
public java.lang.String toString()
Per [887120] DriverVersion.getDriverVersion(); this will return a short version name.
Added back to driver per [1006449] 0.9rc1: Driver version broken
public boolean jdbcCompliant()
jdbcCompliant in interface java.sql.Driver
public boolean acceptsURL(java.lang.String url)
throws java.sql.SQLException
acceptsURL in interface java.sql.Driverjava.sql.SQLException
public java.sql.Connection connect(java.lang.String url,
java.util.Properties info)
throws java.sql.SQLException
connect in interface java.sql.Driverjava.sql.SQLException
public java.sql.DriverPropertyInfo[] getPropertyInfo(java.lang.String url,
java.util.Properties props)
throws java.sql.SQLException
getPropertyInfo in interface java.sql.Driverjava.sql.SQLException
private java.util.Properties setupConnectProperties(java.lang.String url,
java.util.Properties info)
throws java.sql.SQLException
connect(String, java.util.Properties) method.
url - the URL of the database to which to connectinfo - a list of arbitrary string tag/value pairs as
connection arguments.
java.sql.SQLException - if an error occurs parsing the URLprivate static java.util.Map createChoicesMap()
choices
field should be set when calling
getPropertyInfo(String, Properties).
The values in the map are the String[] objects
that should be set to the choices field.
DriverPropertyInfo objects whose
choices should be set.private static java.util.Map createRequiredTrueMap()
getPropertyInfo(String, Properties).
Note that only the key of the map is used to determine whether
the required field should be set to true.
If the key does not exist in the map, then the required
field is set to false.
DriverPropertyInfo objects where
required should be set to true.
private static java.util.Properties parseURL(java.lang.String url,
java.util.Properties info)
url - the URL to parseinfo - any existing properties already loaded in a
Properties object
Properties object
private static int nextToken(java.lang.String url,
int pos,
java.lang.StringBuffer token)
url - The URL being parsedpos - The current position in the URL string.token - The buffer containing the extracted token.
int.public static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbc.ProcEntry
Stores information about a cached stored procedure or statement handle.
| Field Summary | |
private ColInfo[] |
colMetaData
Column meta data (Sybase only). |
static int |
CURSOR
The entry references a prepared cursor handle. |
private java.lang.String |
name
Stored procedure name or statement handle. |
private ParamInfo[] |
paramMetaData
Parameter meta data (Sybase only). |
static int |
PREP_FAILED
The entry references a failed prepare. |
static int |
PREPARE
The entry references a prepared statement handle. |
static int |
PROCEDURE
The entry references a stored procedure. |
private int |
refCount
Usage count for this statement. |
private int |
type
Type of statement referenced by this entry. |
| Constructor Summary | |
ProcEntry()
|
|
| Method Summary | |
void |
addRef()
Increments the usage count. |
void |
appendDropSQL(java.lang.StringBuffer sql)
Retrieves the SQL to drop this statement. |
ColInfo[] |
getColMetaData()
Retrieves the column meta data array. |
ParamInfo[] |
getParamMetaData()
Retrieves the parameter meta data array. |
int |
getRefCount()
Retreives the usage count. |
int |
getType()
Retrieves the statement implementation type. |
void |
release()
Decrements the usage count. |
void |
setColMetaData(ColInfo[] colMetaData)
Sets the column meta data. |
void |
setHandle(int handle)
Sets the prepared statement handle. |
void |
setName(java.lang.String name)
Sets the procedure name. |
void |
setParamMetaData(ParamInfo[] paramMetaData)
Sets the parameter meta data. |
void |
setType(int type)
Sets the statement implementation type. |
java.lang.String |
toString()
Retrieves the procedure or handle name. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
public static final int PROCEDURE
public static final int PREPARE
public static final int CURSOR
public static final int PREP_FAILED
private java.lang.String name
private ColInfo[] colMetaData
private ParamInfo[] paramMetaData
private int type
private int refCount
| Constructor Detail |
public ProcEntry()
| Method Detail |
public final java.lang.String toString()
Stringpublic void setName(java.lang.String name)
name - the procedure namepublic void setHandle(int handle)
handle - the sp_prepare handle valuepublic ColInfo[] getColMetaData()
ColInfo[]public void setColMetaData(ColInfo[] colMetaData)
colMetaData - the column meta datapublic ParamInfo[] getParamMetaData()
ParamInfo[]public void setParamMetaData(ParamInfo[] paramMetaData)
paramMetaData - the parameter meta data arraypublic void setType(int type)
type - the type code (one of PROCEDURE,PREPARE,CURSOR)public int getType()
intpublic void appendDropSQL(java.lang.StringBuffer sql)
public void addRef()
public void release()
public int getRefCount()
int
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjava.lang.Throwable
java.lang.Exception
net.sourceforge.jtds.jdbc.ProtocolException
Exception class used to report errors in the TDS protocol.
| Field Summary |
| Fields inherited from class java.lang.Exception |
|
| Fields inherited from class java.lang.Throwable |
|
| Constructor Summary | |
ProtocolException(java.lang.String message)
Construct a ProtocolException with message. |
|
| Methods inherited from class java.lang.Throwable |
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public ProtocolException(java.lang.String message)
message - The explanatory message.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.SanityTest
Some simple tests just to make sure everything is working properly.
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
SanityTest(java.lang.String name)
|
|
| Method Summary | |
static void |
main(java.lang.String[] args)
|
void |
testCursorRSCreate()
|
void |
testCursorRSScroll()
|
void |
testCursorStatements()
Basic test of cursor mechanisms. |
void |
testNullImage()
|
void |
testNullText()
|
void |
testSanity()
A simple test to make sure everything seems to be OK |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public SanityTest(java.lang.String name)
| Method Detail |
public void testSanity()
throws java.lang.Exception
java.lang.Exception
public void testCursorStatements()
throws java.lang.Exception
java.lang.Exception
public void testCursorRSCreate()
throws java.lang.Exception
java.lang.Exception
public void testCursorRSScroll()
throws java.lang.Exception
java.lang.Exception
public void testNullImage()
throws java.lang.Exception
java.lang.Exception
public void testNullText()
throws java.lang.Exception
java.lang.Exceptionpublic static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.DatabaseTestCase
net.sourceforge.jtds.test.CSUnitTest
| Field Summary | |
(package private) static java.io.PrintStream |
output
|
| Fields inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
|
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
CSUnitTest(java.lang.String name)
|
|
| Method Summary | |
(package private) static java.lang.String |
longString(char ch)
|
static void |
main(java.lang.String[] args)
|
void |
testCallStoredProcedures0028()
|
void |
testDataTypes0027()
|
void |
testDataTypesByResultSetMetaData0030()
|
void |
testExceptionByUpdate0033()
|
void |
testGetAsciiStream0018()
|
void |
testInsertConflict0049()
|
void |
testMaxRows0003()
|
void |
testMoneyHandling0019()
|
void |
testSpHelpSysUsers0032()
|
void |
testTextColumns0031()
|
void |
testxx0029()
|
void |
testxx0050()
|
void |
testxx0051()
|
void |
testxx0052()
|
void |
testxx0053()
|
void |
testxx0055()
|
void |
testxx0057()
|
void |
testxx0059()
|
void |
testxx005x()
|
| Methods inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
compareBytes, dropFunction, dropProcedure, dropProcedure, dropTable, getLongString, getLongString, getType, getTypemap |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
static java.io.PrintStream output
| Constructor Detail |
public CSUnitTest(java.lang.String name)
| Method Detail |
public static void main(java.lang.String[] args)
public void testMaxRows0003()
throws java.lang.Exception
java.lang.Exception
public void testGetAsciiStream0018()
throws java.lang.Exception
java.lang.Exception
public void testMoneyHandling0019()
throws java.lang.Exception
java.lang.Exception
public void testDataTypes0027()
throws java.lang.Exception
java.lang.Exception
public void testCallStoredProcedures0028()
throws java.lang.Exception
java.lang.Exception
public void testxx0029()
throws java.lang.Exception
java.lang.Exception
public void testDataTypesByResultSetMetaData0030()
throws java.lang.Exception
java.lang.Exception
public void testTextColumns0031()
throws java.lang.Exception
java.lang.Exception
public void testSpHelpSysUsers0032()
throws java.lang.Exception
java.lang.Exceptionstatic java.lang.String longString(char ch)
public void testExceptionByUpdate0033()
throws java.lang.Exception
java.lang.Exception
public void testInsertConflict0049()
throws java.lang.Exception
java.lang.Exception
public void testxx0050()
throws java.lang.Exception
java.lang.Exception
public void testxx0051()
throws java.lang.Exception
java.lang.Exception
public void testxx0055()
throws java.lang.Exception
java.lang.Exception
public void testxx0052()
throws java.lang.Exception
java.lang.Exception
public void testxx0053()
throws java.lang.Exception
java.lang.Exception
public void testxx005x()
throws java.lang.Exception
java.lang.Exception
public void testxx0057()
throws java.lang.Exception
java.lang.Exception
public void testxx0059()
throws java.lang.Exception
java.lang.Exception
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.UnitTestBase
net.sourceforge.jtds.test.SupportUnitTest
Unit tests for the Support class.
| Field Summary | |
private java.lang.String |
osName
|
private static java.lang.String |
SYSTEM_PROPRETY_OS_NAME
|
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
SupportUnitTest(java.lang.String name)
Constructor. |
|
| Method Summary | |
protected void |
setUp()
|
protected void |
tearDown()
|
void |
testIsWindowsOS_Linux()
|
void |
testIsWindowsOS_MacOSX()
|
void |
testIsWindowsOS_Windows_XP()
|
void |
testIsWindowsOS_windows()
|
void |
testIsWindowsOS_Windows()
|
| Methods inherited from class net.sourceforge.jtds.test.UnitTestBase |
assertEquals, invokeConstructor, invokeGetInstanceField, invokeInstanceMethod, invokeSetInstanceField, invokeStaticMethod, ucFirst |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
private static final java.lang.String SYSTEM_PROPRETY_OS_NAME
private java.lang.String osName
| Constructor Detail |
public SupportUnitTest(java.lang.String name)
name - The name of the test.| Method Detail |
protected void setUp()
throws java.lang.Exception
java.lang.Exception
protected void tearDown()
throws java.lang.Exception
java.lang.Exceptionpublic void testIsWindowsOS_Linux()
public void testIsWindowsOS_MacOSX()
public void testIsWindowsOS_windows()
public void testIsWindowsOS_Windows()
public void testIsWindowsOS_Windows_XP()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.DatabaseTestCase
net.sourceforge.jtds.test.ClientSideCursorTest
Test case to illustrate use of Cached cursor result set.
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
|
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
ClientSideCursorTest(java.lang.String name)
|
|
| Method Summary | |
static void |
main(java.lang.String[] args)
|
void |
testCachedCursor()
General test of scrollable cursor functionality. |
void |
testOptimisticUpdates()
Test optimistic updates throw exception if row is changed on disk. |
void |
testPositionedUpdate()
Test support for JDBC 1 style positioned updates with named cursors. |
void |
testUpdateNoKeys()
Test updateable result set where table is not keyed. |
| Methods inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
compareBytes, dropFunction, dropProcedure, dropProcedure, dropTable, getLongString, getLongString, getType, getTypemap |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public ClientSideCursorTest(java.lang.String name)
| Method Detail |
public void testCachedCursor()
throws java.lang.Exception
java.lang.Exception
public void testPositionedUpdate()
throws java.lang.Exception
java.lang.Exception
public void testOptimisticUpdates()
throws java.lang.Exception
java.lang.Exception
public void testUpdateNoKeys()
throws java.lang.Exception
java.lang.Exceptionpublic static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
net.sourceforge.jtds.test.JtdsDataSourceUnitTest.Test_JtdsDataSource_fields
Class used to test JtdsDataSource.
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary |
|
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
JtdsDataSourceUnitTest.Test_JtdsDataSource_fields()
Default constructor. |
|
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, setUp, tearDown, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public JtdsDataSourceUnitTest.Test_JtdsDataSource_fields()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.DatabaseTestCase
net.sourceforge.jtds.test.MetaDataTestCase
net.sourceforge.jtds.test.DatabaseMetaDataTest
Test DatabaseMetaData.
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
|
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
DatabaseMetaDataTest(java.lang.String name)
|
|
| Method Summary | |
static void |
main(java.lang.String[] args)
|
void |
testBooleanOptions()
Test meta data functions that return boolean values. |
void |
testColumnClassName()
|
void |
testColumnMetaData()
Test to check DatabaseMetaData.getColumns and ResultSetMetaData is equivalent. |
void |
testDefaultValue()
Test for bug [1825743], default value not returned for column with default value. |
void |
testGetColumnsMetaData()
Test for bug [1120168] jTDS 101 - TDS data type 0 invalid. |
void |
testGetTables()
Test for bug [998765] Exception with Sybase and metaData.getTables() |
void |
testGetTableTypesOrder()
Test for bug [974036] Bug in 0.8rc1 DatabaseMetaData method getTableTypes() |
void |
testIntOptions()
Test meta data function that return integer values. |
void |
testProcedureColumns()
Test for bug [1184376] Sybase getProcedureColumns bug |
void |
testProcedureUseLOBsFalse()
Test for bug [1245775] Column type inconsistency when useLOBs=false. |
void |
testResultSetMetadate()
Test for bug [1833720], invalid table names for large result sets. |
void |
testResultSets()
Test meta data functions that return result sets. |
void |
testStringOptions()
Test meta data functions that return strings. |
void |
testTableMetaData()
Test for bug [1023984] Protocol error processing table meta data. |
| Methods inherited from class net.sourceforge.jtds.test.MetaDataTestCase |
checkColumnNames |
| Methods inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
compareBytes, dropFunction, dropProcedure, dropProcedure, dropTable, getLongString, getLongString, getType, getTypemap |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public DatabaseMetaDataTest(java.lang.String name)
| Method Detail |
public void testBooleanOptions()
throws java.lang.Exception
java.lang.Exception
public void testStringOptions()
throws java.lang.Exception
java.lang.Exception
public void testIntOptions()
throws java.lang.Exception
java.lang.Exception
public void testResultSets()
throws java.lang.Exception
java.lang.Exception
public void testGetTableTypesOrder()
throws java.lang.Exception
java.lang.Exception
public void testGetTables()
throws java.lang.Exception
java.lang.Exception
public void testGetColumnsMetaData()
throws java.lang.Exception
java.lang.Exception
public void testTableMetaData()
throws java.lang.Exception
Test to demonstrate failure to process the TDS table name token correctly. Must be run with TDS=8.0.
java.lang.Exception
public void testColumnClassName()
throws java.sql.SQLException
java.sql.SQLException
public void testColumnMetaData()
throws java.lang.Exception
java.lang.Exception - if an error condition occurs
public void testResultSetMetadate()
throws java.lang.Exception
java.lang.Exception
public void testProcedureColumns()
throws java.lang.Exception
java.lang.Exception
public void testProcedureUseLOBsFalse()
throws java.lang.Exception
java.lang.Exception
public void testDefaultValue()
throws java.sql.SQLException
java.sql.SQLExceptionpublic static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.CallableStatementTest
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
CallableStatementTest(java.lang.String name)
|
|
| Method Summary | |
static void |
main(java.lang.String[] args)
Test that output result sets, return values and output parameters are correctly handled for a remote procedure call. |
void |
testBigDecimal()
Test for bug [1236078] Procedure doesn't get called for some BigDecimal values - invalid bug. |
void |
testCallableError1()
Test for bug [991640] java.sql.Date error and RAISERROR problem |
void |
testCallableRegisterOutParameter1()
Test for bug [974284] retval on callable statement isn't handled correctly |
void |
testCallableRegisterOutParameter2()
Test for bug [994888] Callable statement and Float output parameter |
void |
testCallableRegisterOutParameter3()
Test for bug [994988] Network error when null is returned via int output parm |
void |
testCallableRegisterOutParameter4()
Test for bug [983432] Prepared call doesn't work with jTDS 0.8 |
void |
testCallableSetNull1()
Test for reature request [956800] setNull(): Not implemented. |
void |
testCallableStatement()
|
void |
testCallableStatement1()
|
void |
testCallableStatementCall1()
|
void |
testCallableStatementCall2()
|
void |
testCallableStatementCall3()
|
void |
testCallableStatementCall4()
Test for bug [974801] stored procedure error in Northwind |
void |
testCallableStatementExec1()
|
void |
testCallableStatementExec2()
|
void |
testCallableStatementExec3()
|
void |
testCallableStatementExec4()
|
void |
testCallableStatementExec5()
|
void |
testCallableStatementExec6()
|
void |
testCallableStatementExec7()
|
void |
testCallableStatementExec8()
|
void |
testCallableStatementExec9()
Test for bug [978175] 0.8: Stored Procedure call doesn't work anymore |
void |
testCallableStatementParsing1()
|
void |
testCallableStatementParsing2()
Test for bug [938632] String index out of bounds error in 0.8rc1. |
void |
testCallableStatementParsing3()
Test for bug [1006845] Stored procedure with 18 parameters. |
void |
testCallableStatementParsing4()
Test for incorrect exception thrown/no exception thrown when invalid call escape is used. |
void |
testCallableStatementParsing5()
Test for bug [1052942] Error processing JDBC call escape. |
void |
testCallableStatementParsing6()
Test for incorrect exception thrown/no exception thrown when invalid call escape is used. |
void |
testCallableStatementParsing7()
Test for incorrect exception thrown/no exception thrown when invalid call escape is used. |
void |
testErrorOutputParams()
Test for bug [1047208] SQLException chaining not implemented correctly: checks that all errors are returned and that output variables are also returned. |
void |
testInOutParameters()
Test for separation of IN and INOUT/OUT parameter values |
void |
testNonRpcProc1()
Test that procedure calls with both literal parameters and parameterr markers are executed correctly (bug [1078927] Callable statement fails). |
void |
testNonRpcProc2()
Test that procedure calls with both literal parameters and parameterr markers are executed correctly (bug [1078927] Callable statement fails). |
void |
testProcessUpdateCounts1()
Test that procedure outputs are available immediately for procedures that do not return ResultSets (i.e that update counts are cached). |
void |
testProcessUpdateCounts2()
Test that procedure outputs are available immediately after processing the last ResultSet returned by the procedure (i.e that update counts are cached). |
void |
testProcessUpdateCounts3()
Test that procedure outputs are available immediately after processing the last ResultSet returned by the procedure (i.e that update counts are cached) even if getMoreResults() is not called. |
void |
testProcessUpdateCounts4()
Test that procedure outputs are available immediately after processing the last ResultSet returned by the procedure (i.e that update counts are cached) even if getMoreResults() and ResultSet.close() are not called. |
void |
testSemicolonProcedures()
Test that procedure names containing semicolons are parsed correctly. |
void |
testTsEscape()
Test for bug [ 1062671 ] SQLParser unable to parse CONVERT(char,{ts ?} |
void |
testWritetext()
Test for bug [1152329] Spurious output params assigned (TIMESTMP). |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public CallableStatementTest(java.lang.String name)
| Method Detail |
public void testCallableStatement()
throws java.lang.Exception
java.lang.Exception
public void testCallableStatement1()
throws java.lang.Exception
java.lang.Exception
public void testCallableStatementCall1()
throws java.lang.Exception
java.lang.Exception
public void testCallableStatementCall2()
throws java.lang.Exception
java.lang.Exception
public void testCallableStatementCall3()
throws java.lang.Exception
java.lang.Exception
public void testCallableStatementCall4()
throws java.lang.Exception
java.lang.Exception
public void testCallableStatementExec1()
throws java.lang.Exception
java.lang.Exception
public void testCallableStatementExec2()
throws java.lang.Exception
java.lang.Exception
public void testCallableStatementExec3()
throws java.lang.Exception
java.lang.Exception
public void testCallableStatementExec4()
throws java.lang.Exception
java.lang.Exception
public void testCallableStatementExec5()
throws java.lang.Exception
java.lang.Exception
public void testCallableStatementExec6()
throws java.lang.Exception
java.lang.Exception
public void testCallableStatementExec7()
throws java.lang.Exception
java.lang.Exception
public void testCallableStatementExec8()
throws java.lang.Exception
java.lang.Exception
public void testCallableStatementExec9()
throws java.lang.Exception
java.lang.Exception
public void testCallableStatementParsing1()
throws java.lang.Exception
java.lang.Exception
public void testCallableStatementParsing2()
throws java.lang.Exception
java.lang.Exception
public void testCallableStatementParsing3()
throws java.lang.Exception
java.lang.Exception
public void testCallableStatementParsing4()
throws java.sql.SQLException
java.sql.SQLException
public void testCallableStatementParsing5()
throws java.lang.Exception
} causes the parser to fail).
java.lang.Exception
public void testCallableStatementParsing6()
throws java.sql.SQLException
java.sql.SQLException
public void testCallableStatementParsing7()
throws java.sql.SQLException
java.sql.SQLException
public void testCallableSetNull1()
throws java.lang.Exception
java.lang.Exception
public void testCallableRegisterOutParameter1()
throws java.lang.Exception
java.lang.Exception
public void testCallableRegisterOutParameter2()
throws java.lang.Exception
java.lang.Exception
public void testCallableRegisterOutParameter3()
throws java.lang.Exception
java.lang.Exception
public void testCallableRegisterOutParameter4()
throws java.lang.Exception
java.lang.Exception
public void testCallableError1()
throws java.lang.Exception
java.lang.Exception
public void testProcessUpdateCounts1()
throws java.sql.SQLException
java.sql.SQLException
public void testProcessUpdateCounts2()
throws java.sql.SQLException
java.sql.SQLException
public void testProcessUpdateCounts3()
throws java.sql.SQLException
java.sql.SQLException
public void testProcessUpdateCounts4()
throws java.sql.SQLException
java.sql.SQLException
public void testTsEscape()
throws java.lang.Exception
java.lang.Exception
public void testInOutParameters()
throws java.lang.Exception
java.lang.Exception
public void testSemicolonProcedures()
throws java.lang.Exception
java.lang.Exception
public void testNonRpcProc1()
throws java.lang.Exception
java.lang.Exception
public void testNonRpcProc2()
throws java.lang.Exception
java.lang.Exception
public void testWritetext()
throws java.lang.Exception
java.lang.Exception
public void testErrorOutputParams()
throws java.lang.Exception
java.lang.Exception
public void testBigDecimal()
throws java.lang.Exception
java.lang.Exceptionpublic static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.DatabaseTestCase
net.sourceforge.jtds.test.MetaDataTestCase
Base class for meta data test cases.
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
|
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
MetaDataTestCase(java.lang.String name)
|
|
| Method Summary | |
protected boolean |
checkColumnNames(java.sql.ResultSet rs,
java.lang.String[] names)
Utility method to check column names and number. |
| Methods inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
compareBytes, dropFunction, dropProcedure, dropProcedure, dropTable, getLongString, getLongString, getType, getTypemap |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public MetaDataTestCase(java.lang.String name)
| Method Detail |
protected boolean checkColumnNames(java.sql.ResultSet rs,
java.lang.String[] names)
throws java.sql.SQLException
rs - the result set to checknames - the list of column names to compare to result set
boolean value true if the columns match
java.sql.SQLException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.UnitTestBase
net.sourceforge.jtds.test.MessagesPropertiesUnitTest.TestPropertyHasDescription
Tests that a given property key has a matching description key in
Messages.properties.
| Field Summary | |
private java.util.ResourceBundle |
messages
|
private java.lang.String |
property
|
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
MessagesPropertiesUnitTest.TestPropertyHasDescription(java.lang.String property,
java.util.ResourceBundle messages)
Constructor. |
|
| Method Summary | |
protected void |
runTest()
Runs the test that a given property key has a matching description key in Messages.properties. |
static junit.framework.Test |
suite()
Provides a null test suite so that JUnit will not try to instantiate this class directly. |
| Methods inherited from class net.sourceforge.jtds.test.UnitTestBase |
assertEquals, invokeConstructor, invokeGetInstanceField, invokeInstanceMethod, invokeSetInstanceField, invokeStaticMethod, ucFirst |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, setName, setUp, tearDown, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
private final java.util.ResourceBundle messages
private final java.lang.String property
| Constructor Detail |
public MessagesPropertiesUnitTest.TestPropertyHasDescription(java.lang.String property,
java.util.ResourceBundle messages)
property - The property name to test.messages - The resource bundle containing all of the messages.| Method Detail |
public static final junit.framework.Test suite()
null).
protected void runTest()
throws java.lang.Throwable
Messages.properties.
java.lang.Throwable - on error.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.UnitTestBase
net.sourceforge.jtds.test.DefaultPropertiesUnitTest
Unit tests for the DefaultProperties class.
| Field Summary |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
DefaultPropertiesUnitTest(java.lang.String name)
Constructor. |
|
| Method Summary | |
void |
test_addDefaultPropertyIfNotSet_DefaultKeyNotSet()
Tests that DefaultProperties.addDefaultPropertyIfNotSet(java.util.Properties, java.lang.String, java.lang.String, java.util.Map)
does not set a default property if the defaultKey is not set. |
void |
test_addDefaultPropertyIfNotSet_DefaultKeySet_PropertyAlreadySet()
Tests that DefaultProperties.addDefaultPropertyIfNotSet(java.util.Properties, java.lang.String, java.lang.String, java.util.Map)
does not set a default property if the property is already set. |
void |
test_addDefaultPropertyIfNotSet_DefaultKeySet_PropertyNotSet()
Tests that DefaultProperties.addDefaultPropertyIfNotSet(java.util.Properties, java.lang.String, java.lang.String, java.util.Map)
sets a default property if the property is not already set. |
void |
test_addDefaultPropertyIfNotSet_PropertyAlreadySet()
Tests that DefaultProperties.addDefaultPropertyIfNotSet(java.util.Properties, java.lang.String, java.lang.String)
does not set a default property if the property is already set. |
void |
test_addDefaultPropertyIfNotSet_PropertyNotSet()
Tests that DefaultProperties.addDefaultPropertyIfNotSet(java.util.Properties, java.lang.String, java.lang.String)
sets a default property if the property is not already set. |
void |
test_getNamedPipePath_DEFAULT()
|
void |
test_getNamedPipePath_INVALID()
|
void |
test_getNamedPipePath_SQLSERVER()
|
void |
test_getNamedPipePath_SYBASE()
|
void |
test_getServerType_intToString_Null()
|
void |
test_getServerType_intToString_SQLSERVER()
|
void |
test_getServerType_intToString_SYBASE()
|
void |
test_getServerType_StringToInteger_Null()
|
void |
test_getServerType_StringToInteger_SQLSERVER()
|
void |
test_getServerType_StringToInteger_SYBASE()
|
void |
test_getTdsVersion_StringToInteger_Null()
|
void |
test_getTdsVersion_StringToInteger_TDS42()
|
void |
test_getTdsVersion_StringToInteger_TDS50()
|
void |
test_getTdsVersion_StringToInteger_TDS70()
|
void |
test_getTdsVersion_StringToInteger_TDS80()
|
| Methods inherited from class net.sourceforge.jtds.test.UnitTestBase |
assertEquals, invokeConstructor, invokeGetInstanceField, invokeInstanceMethod, invokeSetInstanceField, invokeStaticMethod, ucFirst |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, setUp, tearDown, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public DefaultPropertiesUnitTest(java.lang.String name)
name - The name of the test.| Method Detail |
public void test_addDefaultPropertyIfNotSet_PropertyNotSet()
DefaultProperties.addDefaultPropertyIfNotSet(java.util.Properties, java.lang.String, java.lang.String)
sets a default property if the property is not already set.
public void test_addDefaultPropertyIfNotSet_PropertyAlreadySet()
DefaultProperties.addDefaultPropertyIfNotSet(java.util.Properties, java.lang.String, java.lang.String)
does not set a default property if the property is already set.
public void test_addDefaultPropertyIfNotSet_DefaultKeyNotSet()
DefaultProperties.addDefaultPropertyIfNotSet(java.util.Properties, java.lang.String, java.lang.String, java.util.Map)
does not set a default property if the defaultKey is not set.
public void test_addDefaultPropertyIfNotSet_DefaultKeySet_PropertyNotSet()
DefaultProperties.addDefaultPropertyIfNotSet(java.util.Properties, java.lang.String, java.lang.String, java.util.Map)
sets a default property if the property is not already set.
public void test_addDefaultPropertyIfNotSet_DefaultKeySet_PropertyAlreadySet()
DefaultProperties.addDefaultPropertyIfNotSet(java.util.Properties, java.lang.String, java.lang.String, java.util.Map)
does not set a default property if the property is already set.
public void test_getServerType_intToString_Null()
public void test_getServerType_intToString_SQLSERVER()
public void test_getServerType_intToString_SYBASE()
public void test_getServerType_StringToInteger_Null()
public void test_getServerType_StringToInteger_SQLSERVER()
public void test_getServerType_StringToInteger_SYBASE()
public void test_getTdsVersion_StringToInteger_Null()
public void test_getTdsVersion_StringToInteger_TDS42()
public void test_getTdsVersion_StringToInteger_TDS50()
public void test_getTdsVersion_StringToInteger_TDS70()
public void test_getTdsVersion_StringToInteger_TDS80()
public void test_getNamedPipePath_DEFAULT()
public void test_getNamedPipePath_INVALID()
public void test_getNamedPipePath_SQLSERVER()
public void test_getNamedPipePath_SYBASE()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.DatabaseTestCase
net.sourceforge.jtds.test.ConnectionJDBC3Test
JDBC 3.0-only tests for Connection.
| Nested Class Summary | |
static class |
ConnectionJDBC3Test.testTimerStopHelper
Helper class for test for bug [2871274]. |
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
|
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
ConnectionJDBC3Test(java.lang.String name)
|
|
| Method Summary | |
void |
testSavepointRelease()
Test that temporary procedures created within transactions with savepoints which are released are still kept in the procedure cache. |
void |
testTimerStop()
Test for bug [2871274], TimerThread prevents classloader from being GCed. |
void |
testUnclosedSocket()
Test for bug [1755448], login failure leaves unclosed sockets. |
| Methods inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
compareBytes, dropFunction, dropProcedure, dropProcedure, dropTable, getLongString, getLongString, getType, getTypemap |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public ConnectionJDBC3Test(java.lang.String name)
| Method Detail |
public void testSavepointRelease()
throws java.sql.SQLException
java.sql.SQLExceptionpublic void testUnclosedSocket()
public void testTimerStop()
throws java.lang.Throwable
java.lang.Throwable
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use MetaDataTestCase | |
| net.sourceforge.jtds.test | |
| Uses of MetaDataTestCase in net.sourceforge.jtds.test |
| Subclasses of MetaDataTestCase in net.sourceforge.jtds.test | |
class |
DatabaseMetaDataJDBC3Test
Test JDBC3 extensions to DatabaseMetaData. |
class |
DatabaseMetaDataTest
Test DatabaseMetaData. |
class |
DatabaseMetaDataTypeInfoTest
Tests for DatabaseMetaData.getTypeInfo(). |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use DefaultPropertiesTestLibrary | |
| net.sourceforge.jtds.test | |
| Uses of DefaultPropertiesTestLibrary in net.sourceforge.jtds.test |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use TestBase | |
| net.sourceforge.jtds.test | |
| Uses of TestBase in net.sourceforge.jtds.test |
| Subclasses of TestBase in net.sourceforge.jtds.test | |
class |
AsTest
|
class |
BatchTest
Simple test suite to exercise batch execution. |
class |
CallableStatementJDBC3Test
Test the JDBC 3.0 features of CallableStatement. |
class |
CallableStatementTest
|
class |
ClientSideCursorTest
Test case to illustrate use of Cached cursor result set. |
class |
ConnectionJDBC3Test
JDBC 3.0-only tests for Connection. |
class |
CSUnitTest
|
class |
DatabaseMetaDataJDBC3Test
Test JDBC3 extensions to DatabaseMetaData. |
class |
DatabaseMetaDataTest
Test DatabaseMetaData. |
class |
DatabaseMetaDataTypeInfoTest
Tests for DatabaseMetaData.getTypeInfo(). |
class |
DatabaseTestCase
|
class |
EncodingTest
|
class |
GenKeyTest
Test case to illustrate JDBC 3 GetGeneratedKeys() function. |
class |
JDBC3Test
Test for miscellaneous JDBC 3.0 features. |
class |
LargeLOBTest
|
class |
LOBTest
|
class |
MetaDataTestCase
Base class for meta data test cases. |
class |
NtlmAuthTest
Unit test for NTLM challenge/response calculation |
class |
PreparedStatementTest
|
class |
ReadTextTest
Test case to illustrate use of READTEXT for text and image columns. |
class |
ResultSetTest
|
class |
SAfeTest
|
class |
SanityTest
Some simple tests just to make sure everything is working properly. |
class |
SavepointTest
|
class |
StatementTest
|
class |
SunTest
Test case to illustrate errors reported by SUN JBDC compatibility test suite. |
class |
Tds5Test
Test case to illustrate use of TDS 5 support. |
class |
Tds8Test
Test case to illustrate use of TDS 8 support |
class |
TimestampTest
test getting timestamps from the database. |
class |
TimeZoneTest
Tests timezone conversions when setting and getting data to and from the database. |
class |
TlsTest
Test for SSL TLS. |
class |
UpdateTest
|
class |
XaTest
Test suite for XA Distributed Transactions. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use UnitTestBase | |
| net.sourceforge.jtds.test | |
| Uses of UnitTestBase in net.sourceforge.jtds.test |
| Subclasses of UnitTestBase in net.sourceforge.jtds.test | |
class |
ConnectionJDBC2UnitTest
Unit test for the ConnectionJDBC2 class. |
class |
DefaultPropertiesUnitTest
Unit tests for the DefaultProperties class. |
class |
DriverUnitTest
Unit tests for the Driver class. |
class |
JtdsDataSourceUnitTest
Unit tests for the JtdsDataSource class. |
static class |
JtdsDataSourceUnitTest.Test_JtdsDataSource_getConnection
|
class |
JtdsObjectFactoryUnitTest
Unit tests for the JtdsObjectFactory class. |
class |
MessagesPropertiesUnitTest
Unit tests for the Messages.properties file. |
static class |
MessagesPropertiesUnitTest.TestDescriptionHasProperty
Tests that a given description key has a matching property key in Messages.properties. |
static class |
MessagesPropertiesUnitTest.TestPropertyHasDescription
Tests that a given property key has a matching description key in Messages.properties. |
class |
NamedPipeUnitTest
Unit tests for the SharedNamedPipe class. |
class |
SupportUnitTest
Unit tests for the Support class. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use DatabaseTestCase | |
| net.sourceforge.jtds.test | |
| Uses of DatabaseTestCase in net.sourceforge.jtds.test |
| Subclasses of DatabaseTestCase in net.sourceforge.jtds.test | |
class |
AsTest
|
class |
BatchTest
Simple test suite to exercise batch execution. |
class |
ClientSideCursorTest
Test case to illustrate use of Cached cursor result set. |
class |
ConnectionJDBC3Test
JDBC 3.0-only tests for Connection. |
class |
CSUnitTest
|
class |
DatabaseMetaDataJDBC3Test
Test JDBC3 extensions to DatabaseMetaData. |
class |
DatabaseMetaDataTest
Test DatabaseMetaData. |
class |
DatabaseMetaDataTypeInfoTest
Tests for DatabaseMetaData.getTypeInfo(). |
class |
MetaDataTestCase
Base class for meta data test cases. |
class |
ResultSetTest
|
class |
SAfeTest
|
class |
SunTest
Test case to illustrate errors reported by SUN JBDC compatibility test suite. |
class |
Tds8Test
Test case to illustrate use of TDS 8 support |
class |
TimestampTest
test getting timestamps from the database. |
class |
TlsTest
Test for SSL TLS. |
class |
XaTest
Test suite for XA Distributed Transactions. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use DefaultPropertiesTester | |
| net.sourceforge.jtds.test | |
| Uses of DefaultPropertiesTester in net.sourceforge.jtds.test |
| Fields in net.sourceforge.jtds.test declared as DefaultPropertiesTester | |
private DefaultPropertiesTester |
DefaultPropertiesTestLibrary.tester
Object used to run all of the tests. |
| Methods in net.sourceforge.jtds.test that return DefaultPropertiesTester | |
protected DefaultPropertiesTester |
DefaultPropertiesTestLibrary.getTester()
Getter for DefaultPropertiesTestLibrary.tester. |
| Methods in net.sourceforge.jtds.test with parameters of type DefaultPropertiesTester | |
void |
DefaultPropertiesTestLibrary.setTester(DefaultPropertiesTester tester)
Setter for #tester. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
net.sourceforge.jtds.test.DriverUnitTest.Test_Driver_getPropertyInfo
Class used to test Driver.getPropertyInfo(String, Properties).
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary |
|
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
DriverUnitTest.Test_Driver_getPropertyInfo()
Default constructor. |
|
| Method Summary | |
static junit.framework.Test |
suite(java.lang.String name)
Construct a test suite for this library. |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, setUp, tearDown, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public DriverUnitTest.Test_Driver_getPropertyInfo()
| Method Detail |
public static junit.framework.Test suite(java.lang.String name)
name - The name of the tests.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.DatabaseTestCase
net.sourceforge.jtds.test.SAfeTest
| Field Summary | |
(package private) int |
done
|
(package private) boolean |
failed
|
(package private) int |
started
|
| Fields inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
|
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
SAfeTest(java.lang.String name)
|
|
| Method Summary | |
private static void |
insertBigDecimal(java.sql.PreparedStatement stmt,
double val,
boolean scaleFlag)
Helper method for testBigDecimal0007. |
static void |
main(java.lang.String[] args)
|
void |
testBatchUpdates0015()
Test batch updates for both plain and prepared statements. |
void |
testBigDecimal0007()
Test BigDecimals created from double values (i.e with very
large scales). |
void |
testBigDecimal1()
Test for bug [939206] TdsException: can't sent this BigDecimal |
void |
testBitFields0005()
Check that values returned from bit fields are correct (not just 0) (bug #841670). |
void |
testBytesToString()
Test that getString() on a varbinary column returns a hex string. |
void |
testCallableStatement0006()
Test that CallableStatements with return values work correctly. |
void |
testCallableStatementVarchar0010()
Test VARCHAR output parameters returned by CallableStatements. |
void |
testCancel0001()
Test cancelling. |
void |
testCancel0002()
Test cancelling. |
void |
testCancel0003()
Test for bug [1120442] Statement hangs in socket read after Statement.cancel(). |
void |
testCursorResultSetConcurrency0003()
Test CursorResultSet concurrency. |
void |
testCursorResultSetEmpty0004()
Check that meta data information is fetched even for empty cursor-based result sets (bug #613199). |
void |
testDataTruncException()
Test DataTruncation exception. |
void |
testDatetimeRounding1()
Test for bug [983561] getDatetimeValue truncates fractional milliseconds |
void |
testDeleteRow0009()
Test ResultSet.deleteRow() on updateable result sets. |
void |
testExecuteUpdateSelect()
Tests that executeUpdate("SELECT ...") |
void |
testFloat1()
Test for bug [963799] float values change when written to the database |
void |
testFnEscape()
Test for bug related with [1368058] Calling StoredProcedure with functions ({fn} escape can't handle special characters, e.g. underscore). |
void |
testFnEscapeNesting()
Test for bug #1116046 {fn } escape can't handle nested functions. |
void |
testGetMultiScrollRs()
Test return of multiple scrollable result sets from one execute. |
void |
testInsertRow0012()
Test ResultSet.insertRow() on updateable result sets. |
void |
testLongToVarchar0008()
Test writing long values to VARCHAR fields. |
void |
testMaxFieldSize()
Test Statement.setMaxFieldSize(). |
void |
testNullLengthStrings0001()
Test whether NULL values, 0-length strings and single space strings are treated right. |
void |
testNullOutputParameters()
Test that null output parameters are handled correctly.
|
void |
testOldDates0016()
Test that dates prior to 06/15/1940 0:00:00 are stored and retrieved correctly. |
void |
testOutOfOrderClose0013()
Test how an "out-of-order" close behaves (e.g close the Connection first, then the Statement anf
finally the ResultSet). |
void |
testPlainResultSetPosition0004()
Check that the isBeforeFirst, isAfterLast,
isFirst and isLast methods work for
forward-only, read-only result sets (bug [1039876] MS SQL
JtdsResultSet.isAfterLast() always returns false). |
void |
testPreparedAndCallableCursors0014()
Test cursor-based ResultSets obtained from
PreparedStatements and CallableStatements. |
void |
testQueryTimeout()
Test for bug [1222199] Delayed exception thrown in statement close. |
void |
testSocketConcurrency1()
|
void |
testSocketConcurrency2()
|
void |
testSocketConcurrency3()
|
void |
testSocketConcurrency4()
Test running SELECT queries on one Statement at the same
time as cancel() is called on a concurrent
Statement. |
void |
testTableParsing()
Test that the SQL parser doesn't try to parse the table name unless necessary (or that it is able to parse function calls if it does). |
void |
testThreadInterrupt()
Test for bug [1596743] executeQuery absorbs thread interrupt status |
void |
testUnterminatedCommentParsing()
Test for bug [1187927] Driver Hangs on Statement.execute(). |
void |
testUpdateRow0011()
Test ResultSet.updateRow() on updateable result sets. |
| Methods inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
compareBytes, dropFunction, dropProcedure, dropProcedure, dropTable, getLongString, getLongString, getType, getTypemap |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
volatile int started
volatile int done
volatile boolean failed
| Constructor Detail |
public SAfeTest(java.lang.String name)
| Method Detail |
public static void main(java.lang.String[] args)
public void testNullLengthStrings0001()
throws java.lang.Exception
java.lang.Exception
public void testCancel0001()
throws java.lang.Exception
java.lang.Exception
public void testCancel0002()
throws java.lang.Exception
java.lang.Exception
public void testCancel0003()
throws java.lang.Exception
java.lang.Exception
public void testQueryTimeout()
throws java.lang.Exception
java.lang.Exception
public void testCursorResultSetConcurrency0003()
throws java.lang.Exception
CursorResultSet concurrency. Create a number of threads that execute concurrent queries using
scrollable result sets. All requests should be run on the same connection (Tds instance).
java.lang.Exception
public void testCursorResultSetEmpty0004()
throws java.lang.Exception
java.lang.Exception
public void testPlainResultSetPosition0004()
throws java.lang.Exception
isBeforeFirst, isAfterLast,
isFirst and isLast methods work for
forward-only, read-only result sets (bug [1039876] MS SQL
JtdsResultSet.isAfterLast() always returns false).
java.lang.Exception - if an error condition occurs
public void testBitFields0005()
throws java.lang.Exception
java.lang.Exception
public void testCallableStatement0006()
throws java.lang.Exception
CallableStatements with return values work correctly.
java.lang.Exception
private static void insertBigDecimal(java.sql.PreparedStatement stmt,
double val,
boolean scaleFlag)
throws java.lang.Exception
testBigDecimal0007. Inserts a BigDecimal
value obtained from a double value.
stmt - PreparedStatement instanceval - the double value to insertscaleFlag - if true scale the value to 4, otherwise
leave it as it is
java.lang.Exception
public void testBigDecimal0007()
throws java.lang.Exception
BigDecimals created from double values (i.e with very
large scales).
java.lang.Exception
public void testLongToVarchar0008()
throws java.lang.Exception
long values to VARCHAR fields. There was a
regression introduced in release 0.6 that caused long
fields to be sent with non-zero scale and appear with decimals when
written into VARCHAR fields.
java.lang.Exception
public void testDeleteRow0009()
throws java.lang.Exception
ResultSet.deleteRow() on updateable result sets.
java.lang.Exception
public void testCallableStatementVarchar0010()
throws java.lang.Exception
An issue existed, caused by the fact that the parameter was sent to SQL Server as a short VARCHAR (not XORed with 0x80) limiting its length to 255 characters. See bug [815348] for more details.
java.lang.Exception
public void testUpdateRow0011()
throws java.lang.Exception
ResultSet.updateRow() on updateable result sets.
java.lang.Exception
public void testInsertRow0012()
throws java.lang.Exception
ResultSet.insertRow() on updateable result sets.
java.lang.Exception
public void testOutOfOrderClose0013()
throws java.lang.Exception
Connection first, then the Statement anf
finally the ResultSet).
java.lang.Exception
public void testPreparedAndCallableCursors0014()
throws java.lang.Exception
ResultSets obtained from
PreparedStatements and CallableStatements.
java.lang.Exception
public void testBatchUpdates0015()
throws java.lang.Exception
java.lang.Exception
public void testOldDates0016()
throws java.lang.Exception
java.lang.Exception
public void testBigDecimal1()
throws java.lang.Exception
java.lang.Exception
public void testFloat1()
throws java.lang.Exception
java.lang.Exception
public void testDatetimeRounding1()
throws java.lang.Exception
java.lang.Exceptionpublic void testSocketConcurrency1()
public void testSocketConcurrency2()
public void testSocketConcurrency3()
public void testSocketConcurrency4()
throws java.lang.Exception
Statement at the same
time as cancel() is called on a concurrent
Statement.
java.lang.Exception
public void testNullOutputParameters()
throws java.sql.SQLException
null output parameters are handled correctly.
It seems that if a non-nullable type is sent as input value and the
output value is NULL, SQL Server (not Sybase) gets confused and returns
the same type but a single 0 byte as value instead of the equivalent
nullable type (e.g. instead of returning an INTN with
length 0, which means it's null, it returns an INT4
followed by a single 0 byte). The output parameter packet length is also
incorrect, which indicates that SQL Server is confused.
Currently jTDS always sends RPC parameters as nullable types, but this
test is necessary to ensure that it will always remain so.
java.sql.SQLException
public void testTableParsing()
throws java.sql.SQLException
java.sql.SQLException
public void testFnEscape()
throws java.lang.Exception
java.lang.Exception
public void testFnEscapeNesting()
throws java.lang.Exception
java.lang.Exception
public void testDataTruncException()
throws java.lang.Exception
DataTruncation exception.
java.lang.Exception
public void testMaxFieldSize()
throws java.lang.Exception
Statement.setMaxFieldSize().
java.lang.Exception
public void testGetMultiScrollRs()
throws java.lang.Exception
java.lang.Exception
public void testUnterminatedCommentParsing()
throws java.lang.Exception
java.lang.Exception
public void testBytesToString()
throws java.lang.Exception
java.lang.Exception
public void testExecuteUpdateSelect()
throws java.lang.Exception
executeUpdate("SELECT ...") fails.
java.lang.Exception
public void testThreadInterrupt()
throws java.lang.Exception
java.lang.Exception
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.NtlmAuthTest
Unit test for NTLM challenge/response calculation
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
NtlmAuthTest(java.lang.String name)
|
|
| Method Summary | |
static byte[] |
hexToBytes(java.lang.String hex)
|
void |
testChallengeResponse()
Tests the NT challenge/response against a known-good value. |
void |
testLMv2()
|
void |
testLMv2CapturedData()
|
void |
testNTLMv2()
|
void |
testNTLMv2CapturedData()
|
void |
testTimestampConversion()
|
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public NtlmAuthTest(java.lang.String name)
| Method Detail |
public static byte[] hexToBytes(java.lang.String hex)
public void testChallengeResponse()
throws java.lang.Exception
java.lang.Exception
public void testLMv2()
throws java.lang.Exception
java.lang.Exception
public void testNTLMv2()
throws java.lang.Exception
java.lang.Exception
public void testTimestampConversion()
throws java.lang.Exception
java.lang.Exception
public void testLMv2CapturedData()
throws java.lang.Exception
java.lang.Exception
public void testNTLMv2CapturedData()
throws java.lang.Exception
java.lang.Exception
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.UnitTestBase
net.sourceforge.jtds.test.ConnectionJDBC2UnitTest
Unit test for the ConnectionJDBC2 class.
| Nested Class Summary | |
static class |
ConnectionJDBC2UnitTest.Test_ConnectionJDBC2_unpackProperties
Class used to test net.sourceforge.jtds.jdbc.ConnectionJDBC2.unpackProperties(Properties). |
| Field Summary |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
ConnectionJDBC2UnitTest(java.lang.String name)
Constructor. |
|
| Method Summary | |
private void |
assertSQLExceptionForBadWholeNumberProperty(java.lang.String key)
Assert that an SQLException is thrown when ConnectionJDBC2.unpackProperties(Properties) is called
with an invalid integer (or long) string set on a property.
|
private java.sql.Connection |
getConnectionOverrideProperties(java.util.Properties override)
Creates a Connection, overriding the default properties
with the ones provided. |
static junit.framework.Test |
suite()
Construct a test suite for this class. |
void |
test_unpackProperties_invalidIntegerProperty()
Test that an SQLException is thrown when
parsing invalid integer (and long) properties. |
void |
testAutoCommit()
Test for bug [1296482] setAutoCommit() behaviour. |
void |
testForceCharset1()
Test correct behavior of the charset property.
|
void |
testForceCharset2()
Test correct behavior of the charset property.
|
| Methods inherited from class net.sourceforge.jtds.test.UnitTestBase |
assertEquals, invokeConstructor, invokeGetInstanceField, invokeInstanceMethod, invokeSetInstanceField, invokeStaticMethod, ucFirst |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, setUp, tearDown, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public ConnectionJDBC2UnitTest(java.lang.String name)
name - The name of the test.| Method Detail |
public static junit.framework.Test suite()
DefaultPropertiesTestLibrary after creating an
anonymous DefaultPropertiesTester object.
public void test_unpackProperties_invalidIntegerProperty()
SQLException is thrown when
parsing invalid integer (and long) properties.
private void assertSQLExceptionForBadWholeNumberProperty(java.lang.String key)
ConnectionJDBC2.unpackProperties(Properties) is called
with an invalid integer (or long) string set on a property.
Note that because Java 1.3 is still supported, the
RuntimeException that is caught may not contain the
original Throwable cause, only the original message.
key - The message key used to retrieve the property name.
private java.sql.Connection getConnectionOverrideProperties(java.util.Properties override)
throws java.lang.Exception
Connection, overriding the default properties
with the ones provided.
override - the overriding properties
Connection object
java.lang.Exception
public void testForceCharset1()
throws java.lang.Exception
charset property.
Values should be stored and retrieved using the requested charset rather
than the server's as long as Unicode is not used.
java.lang.Exception
public void testForceCharset2()
throws java.lang.Exception
charset property.
Stored procedure output parameters should be decoded using the specified
charset rather than the server's as long as they are non-Unicode.
java.lang.Exception
public void testAutoCommit()
throws java.lang.Exception
"If the value of auto-commit is changed in the middle of a transaction, the current transaction is committed."
java.lang.Exception
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
net.sourceforge.jtds.test.ConnectionJDBC2UnitTest.Test_ConnectionJDBC2_unpackProperties
Class used to test net.sourceforge.jtds.jdbc.ConnectionJDBC2.unpackProperties(Properties).
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary |
|
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
ConnectionJDBC2UnitTest.Test_ConnectionJDBC2_unpackProperties()
Default constructor. |
|
| Method Summary | |
static junit.framework.Test |
suite(java.lang.String name)
Construct a test suite for this library. |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, setUp, tearDown, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public ConnectionJDBC2UnitTest.Test_ConnectionJDBC2_unpackProperties()
| Method Detail |
public static junit.framework.Test suite(java.lang.String name)
name - The name of the tests.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.TimeZoneTest
Tests timezone conversions when setting and getting data to and from the database.
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
TimeZoneTest(java.lang.String name)
|
|
| Method Summary | |
static void |
main(java.lang.String[] args)
|
void |
testTimeZone()
Test timezone calendar conversions. |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public TimeZoneTest(java.lang.String name)
| Method Detail |
public void testTimeZone()
throws java.lang.Exception
java.lang.Exceptionpublic static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.UnitTestBase
net.sourceforge.jtds.test.JtdsDataSourceUnitTest
Unit tests for the JtdsDataSource class.
| Nested Class Summary | |
static class |
JtdsDataSourceUnitTest.Test_JtdsDataSource_addNonNullProperties
Class used to test JtdsDataSource.addNonNullProperties(Properties, String, String). |
static class |
JtdsDataSourceUnitTest.Test_JtdsDataSource_fields
Class used to test JtdsDataSource. |
static class |
JtdsDataSourceUnitTest.Test_JtdsDataSource_getConnection
|
static class |
JtdsDataSourceUnitTest.Test_JtdsDataSource_getReference
Class used to test JtdsDataSource.getReference(). |
| Field Summary |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
JtdsDataSourceUnitTest(java.lang.String name)
Constructor. |
|
| Method Summary | |
static junit.framework.Test |
suite()
Construct a test suite for this class. |
void |
testPublicConstructor()
Tests that the public constructor works. |
| Methods inherited from class net.sourceforge.jtds.test.UnitTestBase |
assertEquals, invokeConstructor, invokeGetInstanceField, invokeInstanceMethod, invokeSetInstanceField, invokeStaticMethod, ucFirst |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, setUp, tearDown, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public JtdsDataSourceUnitTest(java.lang.String name)
name - The name of the test.| Method Detail |
public static junit.framework.Test suite()
JtdsDataSourceUnitTest.Test_JtdsDataSource_getConnection.
public void testPublicConstructor()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.DatabaseTestCase
net.sourceforge.jtds.test.MetaDataTestCase
net.sourceforge.jtds.test.DatabaseMetaDataJDBC3Test
Test JDBC3 extensions to DatabaseMetaData.
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
|
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
DatabaseMetaDataJDBC3Test(java.lang.String name)
|
|
| Method Summary | |
static void |
main(java.lang.String[] args)
|
void |
testBooleanOptions()
Test meta data functions that return boolean values. |
void |
testIntOptions()
Test meta data function that return integer values. |
void |
testResultSets()
Test meta data functions that return result sets. |
| Methods inherited from class net.sourceforge.jtds.test.MetaDataTestCase |
checkColumnNames |
| Methods inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
compareBytes, dropFunction, dropProcedure, dropProcedure, dropTable, getLongString, getLongString, getType, getTypemap |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public DatabaseMetaDataJDBC3Test(java.lang.String name)
| Method Detail |
public void testBooleanOptions()
throws java.lang.Exception
java.lang.Exception
public void testIntOptions()
throws java.lang.Exception
java.lang.Exception
public void testResultSets()
throws java.lang.Exception
java.lang.Exceptionpublic static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.DatabaseTestCase
net.sourceforge.jtds.test.BatchTest
Simple test suite to exercise batch execution.
| Nested Class Summary | |
private class |
BatchTest.ConcurrentBatchingHelper
Helper thread used by testConcurrentBatching() to execute a batch within a transaction that is
then rolled back. |
| Field Summary | |
private static int |
EXECUTE_FAILED
|
private static int |
SUCCESS_NO_INFO
|
| Fields inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
|
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
BatchTest(java.lang.String name)
|
|
| Method Summary | |
private static java.lang.String |
array2String(int[] a)
|
static void |
main(java.lang.String[] args)
|
void |
testBatch()
Test batched statements. |
void |
testBatchDupKey()
Test for bug [1371295] SQL Server continues after duplicate key error. |
void |
testBatchEsc()
Test for bug [1180169] JDBC escapes not allowed with Sybase addBatch. |
void |
testBatchUpdateCounts()
test for bug [2827931] that implicitly also tests for bug [1811383] example for statement that produces multiple update counts unexpectedly: IF sessionproperty('ARITHABORT') = 0 SET ARITHABORT ON |
void |
testCallStmtBatch()
Test batched callable statements. |
void |
testCallStmtBatch2()
Test batched callable statements where the call includes literal parameters which prevent the use of RPC calls. |
void |
testCallStmtNoParams()
Test batched callable statements where the call has no parameters. |
void |
testConcurrentBatching()
Test batched prepared statement concurrency. |
void |
testDataTruncation()
this is a test for the data truncation problem described in bug [2731952] |
void |
testLargeBatch()
Test large batch behavior. |
void |
testNoCount()
The first statement in this batch does not return an update count. |
void |
testPrepStmtBatch()
Test batched prepared statements. |
void |
testPrepStmtBatchDupKey()
Test for bug [1371295] SQL Server continues after duplicate key error. |
void |
testPrepStmtNoParams()
Test for PreparedStatement batch with no parameters. |
void |
testPrepStmtVariableParams()
Test for PreparedStatement batch with variable parameter types. |
void |
testResultSetError()
This test should generate an error as the second statement in the batch returns a result set. |
| Methods inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
compareBytes, dropFunction, dropProcedure, dropProcedure, dropTable, getLongString, getLongString, getType, getTypemap |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
private static int SUCCESS_NO_INFO
private static int EXECUTE_FAILED
| Constructor Detail |
public BatchTest(java.lang.String name)
| Method Detail |
public void testResultSetError()
throws java.lang.Exception
java.lang.Exception
public void testNoCount()
throws java.lang.Exception
java.lang.Exception
public void testBatch()
throws java.lang.Exception
java.lang.Exception
public void testPrepStmtBatch()
throws java.lang.Exception
java.lang.Exception
public void testCallStmtBatch()
throws java.lang.Exception
java.lang.Exception
public void testCallStmtBatch2()
throws java.lang.Exception
java.lang.Exception
public void testLargeBatch()
throws java.lang.Exception
java.lang.Exception
public void testBatchEsc()
throws java.lang.Exception
java.lang.Exception
public void testPrepStmtBatchDupKey()
throws java.lang.Exception
java.lang.Exception
public void testBatchDupKey()
throws java.lang.Exception
java.lang.Exception
public void testPrepStmtNoParams()
throws java.lang.Exception
java.lang.Exception
public void testPrepStmtVariableParams()
throws java.lang.Exception
java.lang.Exception
public void testCallStmtNoParams()
throws java.lang.Exception
java.lang.Exception
public void testConcurrentBatching()
throws java.lang.Exception
java.lang.Exception
public void testDataTruncation()
throws java.sql.SQLException
java.sql.SQLException
public void testBatchUpdateCounts()
throws java.sql.SQLException
java.sql.SQLExceptionprivate static java.lang.String array2String(int[] a)
public static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
net.sourceforge.jtds.test.JtdsObjectFactoryUnitTest.Test_JtdsObjectFactory_getObjectInstance_DefaultValues
Class used to test JtdsObjectFactory.getObjectInstance(Object, Name, Context, Hashtable).
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary |
|
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
JtdsObjectFactoryUnitTest.Test_JtdsObjectFactory_getObjectInstance_DefaultValues()
Default constructor. |
|
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, setUp, tearDown, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public JtdsObjectFactoryUnitTest.Test_JtdsObjectFactory_getObjectInstance_DefaultValues()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.EncodingTest
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
EncodingTest(java.lang.String name)
|
|
| Method Summary | |
static void |
main(java.lang.String[] args)
|
void |
testBytesToVarchar()
Test for bug [101956] updateBytes converted to hex in varchar NB Test assumes server using iso_1 character set. |
void |
testSybaseISO_1()
Test for bug [1293415] Charset iso_1 is broken for Sybase. |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public EncodingTest(java.lang.String name)
| Method Detail |
public void testBytesToVarchar()
throws java.lang.Exception
java.lang.Exception
public void testSybaseISO_1()
throws java.lang.Exception
java.lang.Exceptionpublic static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.LargeLOBTest
| Field Summary | |
private static int |
LOB_LENGTH
|
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
LargeLOBTest(java.lang.String name)
|
|
| Method Summary | |
static void |
main(java.lang.String[] args)
|
static junit.framework.Test |
suite()
Only run the test suite if the "jTDS.runLargeLOBTest" system property is defined, as the test takes A LOT of time to execute. |
void |
testLargeBlob1()
Test for bug [945507] closing statement after selecting a large IMAGE - Exception |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
private static final int LOB_LENGTH
| Constructor Detail |
public LargeLOBTest(java.lang.String name)
| Method Detail |
public static junit.framework.Test suite()
public void testLargeBlob1()
throws java.lang.Exception
java.lang.Exceptionpublic static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.DatabaseTestCase
net.sourceforge.jtds.test.ResultSetTest
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
|
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
ResultSetTest(java.lang.String name)
|
|
| Method Summary | |
private static java.lang.String |
array2String(java.lang.Object[] a)
|
static void |
main(java.lang.String[] args)
|
void |
testAbsoluteLargeValue()
Test that calling absolute() with very large positive
values positions the cursor after the last row and with very large
negative values positions the cursor before the first row. |
void |
testAbsoluteMinusOne()
Test that absolute(-1) works the same as last(). |
void |
testCancelResultSet()
Test for bug [1246270] Closing a statement after canceling it throws an exception. |
void |
testConcurrentResultSets()
Test for bug [2051585], TDS Protocol error when 2 ResultSets on the same connection are being iterated at the same time. |
void |
testCursorFallback()
Test that the cursor fallback logic correctly discriminates between "real" sql errors and cursor open failures. |
void |
testCursorFetch()
Test the behavior of sp_cursorfetch with fetch sizes
greater than 1.
|
void |
testCursorMaxRows()
Test that Statement.setMaxRows() works on cursor
ResultSets. |
void |
testCursorPrevious()
Test that ResultSet.previous() works correctly on cursor
ResultSets. |
void |
testCursorWarning()
Test for bug [1022445] Cursor downgrade warning not raised. |
void |
testDatePerformance()
Test for bug [1840116], Select statement very slow with date parameter. |
void |
testDeleteRowMarksDeleted()
Test that deleted rows are not removed but rather marked as deleted. |
void |
testDistinctBug()
Test bug with Sybase where readonly scrollable result set based on a SELECT DISTINCT returns duplicate rows. |
void |
testDynamicCursors()
Test if dynamic cursors ( ResultSet.TYPE_SCROLL_SENSITIVE+1)
see others' updates. |
void |
testEmptyInsertRow()
Test that insertRow() works with no values set. |
void |
testGetByName()
Test whether retrieval by name returns the first occurence (that's what the spec requires). |
void |
testGetObject1()
Test BIT data type. |
void |
testGetObject2()
Test TINYINT data type. |
void |
testGetObject3()
Test SMALLINT data type. |
void |
testGetObject4()
Test INT data type. |
void |
testGetObject5()
Test BIGINT data type. |
void |
testInsertRowVisible()
Test that inserted rows are visible in a scroll sensitive ResultSet and that they show up at the end. |
void |
testMaxRows()
Check whether Statement.setMaxRows() works okay, bug
[1812686]. |
void |
testMoreThan255Columns()
Test if COL_INFO packets are processed correctly for ResultSets with over 255 columns. |
void |
testNegativeOverflow()
Test for bug [2860742], getByte() causes overflow error for negative values. |
void |
testNumericOverflow()
Test for bug [1855125], numeric overflow not reported by jTDS. |
void |
testOutOfMemory()
Test the behavior of the ResultSet/Statement/Connection when the JVM runs out of memory (hopefully) in the middle of a packet. |
void |
testPessimisticConcurrency()
Test pessimistic concurrency for SQL Server (for Sybase optimistic concurrency will always be used). |
void |
testRelative()
Test for bug [1182066] regression bug resultset: relative() not working as expected. |
void |
testRelativeLargeValue()
Test that calling absolute() with very large positive
values positions the cursor after the last row and with very large
negative values positions the cursor before the first row. |
void |
testResultSetColumnName1()
Test for bug [1009233] ResultSet getColumnName, getColumnLabel return wrong values |
void |
testResultSetMetaData()
Test for fixed bugs in ResultSetMetaData: isNullable() always returns columnNoNulls. |
void |
testResultSetScroll1()
Test for bug [961594] ResultSet. |
void |
testResultSetScroll2()
Test for bug [945462] getResultSet() return null if you use scrollable/updatable. |
void |
testResultSetScroll3()
Test for bug [1028881] statement.execute() causes wrong ResultSet type. |
void |
testResultSetUpdate1()
Test for bug [1008208] 0.9-rc1 updateNull doesn't work. |
void |
testRowstat()
Test for bug [1329765] Pseudo column ROWSTAT is back with SQL 2005 (September CTP). |
void |
testSetObjectScale()
Test for bug [1075977] setObject() causes SQLException.
|
void |
testUnicodeStream()
Test that read() works ok on the stream returned by
ResultSet.getUnicodeStream() (i.e. it doesn't always fill
the buffer, regardless of whether there's available data or not). |
void |
testUpdateableClientCursor()
Test for bug [1197603] Cursor downgrade error in CachedResultSet -- updateable result sets were incorrectly downgraded to read only forward only ones when client side cursors were used. |
void |
testUpdateRowDuplicatesRow()
Test that updated rows are marked as deleted and the new values inserted at the end of the ResultSet if the primary key is updated. |
void |
testUpdateRowNoChanges()
Test for bug [1170777] resultSet.updateRow() fails if no row has been changed. |
void |
testUpdateRowPosition()
Test that after updateRow() the cursor is positioned correctly. |
void |
testUpdateRowUpdatesRow()
Test that updated rows are modified in place if the primary key is not updated. |
void |
testZeroFetchSize()
Test for bug [1232733] setFetchSize(0) causes exception. |
| Methods inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
compareBytes, dropFunction, dropProcedure, dropProcedure, dropTable, getLongString, getLongString, getType, getTypemap |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public ResultSetTest(java.lang.String name)
| Method Detail |
public void testGetObject1()
throws java.lang.Exception
java.lang.Exception
public void testGetObject2()
throws java.lang.Exception
java.lang.Exception
public void testGetObject3()
throws java.lang.Exception
java.lang.Exception
public void testGetObject4()
throws java.lang.Exception
java.lang.Exception
public void testGetObject5()
throws java.lang.Exception
java.lang.Exception
public void testResultSetScroll1()
throws java.lang.Exception
java.lang.Exception
public void testResultSetScroll2()
throws java.lang.Exception
java.lang.Exception
public void testResultSetScroll3()
throws java.lang.Exception
java.lang.Exception
public void testResultSetUpdate1()
throws java.lang.Exception
java.lang.Exception
public void testResultSetColumnName1()
throws java.lang.Exception
java.lang.Exception
public void testResultSetMetaData()
throws java.lang.Exception
java.lang.Exception
public void testCursorWarning()
throws java.lang.Exception
java.lang.Exception
public void testCursorFallback()
throws java.lang.Exception
java.lang.Exception
public void testCancelResultSet()
throws java.lang.Exception
java.lang.Exception
public void testGetByName()
throws java.lang.Exception
java.lang.Exception
public void testMoreThan255Columns()
throws java.lang.Exception
ResultSets with over 255 columns.
java.lang.Exception
public void testEmptyInsertRow()
throws java.lang.Exception
insertRow() works with no values set.
java.lang.Exception
public void testInsertRowVisible()
throws java.lang.Exception
ResultSet and that they show up at the end.
java.lang.Exception
public void testUpdateRowDuplicatesRow()
throws java.lang.Exception
ResultSet if the primary key is updated.
java.lang.Exception
public void testUpdateRowUpdatesRow()
throws java.lang.Exception
java.lang.Exception
public void testDeleteRowMarksDeleted()
throws java.lang.Exception
java.lang.Exception
public void testUpdateRowNoChanges()
throws java.lang.Exception
java.lang.Exception
public void testCursorFetch()
throws java.lang.Exception
sp_cursorfetch with fetch sizes
greater than 1.
Assertions tested:
ResultSet the requested number of rows is returned,
starting with row 1 and the error code returned is non-zero (2).
java.lang.Exception
public void testAbsoluteMinusOne()
throws java.lang.Exception
absolute(-1) works the same as last().
java.lang.Exception
public void testAbsoluteLargeValue()
throws java.sql.SQLException
absolute() with very large positive
values positions the cursor after the last row and with very large
negative values positions the cursor before the first row.
java.sql.SQLException
public void testRelativeLargeValue()
throws java.sql.SQLException
absolute() with very large positive
values positions the cursor after the last row and with very large
negative values positions the cursor before the first row.
java.sql.SQLException
public void testUnicodeStream()
throws java.lang.Exception
read() works ok on the stream returned by
ResultSet.getUnicodeStream() (i.e. it doesn't always fill
the buffer, regardless of whether there's available data or not).
java.lang.Exception
public void testMaxRows()
throws java.lang.Exception
Statement.setMaxRows() works okay, bug
[1812686].
java.lang.Exception
public void testCursorMaxRows()
throws java.lang.Exception
Statement.setMaxRows() works on cursor
ResultSets.
java.lang.Exception
public void testSetObjectScale()
throws java.lang.Exception
setObject() causes SQLException.
Conversion of float values to String adds
grouping to the value, which cannot then be parsed.
java.lang.Exception
public void testCursorPrevious()
throws java.lang.Exception
ResultSet.previous() works correctly on cursor
ResultSets.
java.lang.Exception
public void testOutOfMemory()
throws java.sql.SQLException
java.sql.SQLException
public void testRelative()
throws java.lang.Exception
java.lang.Exception
public void testUpdateRowPosition()
throws java.lang.Exception
java.lang.Exception
public void testUpdateableClientCursor()
throws java.lang.Exception
java.lang.Exception
public void testDistinctBug()
throws java.lang.Exception
java.lang.Exception
public void testPessimisticConcurrency()
throws java.lang.Exception
java.lang.Exception
public void testDynamicCursors()
throws java.lang.Exception
ResultSet.TYPE_SCROLL_SENSITIVE+1)
see others' updates. SQL Server only.
java.lang.Exception
public void testZeroFetchSize()
throws java.lang.Exception
java.lang.Exception
public void testRowstat()
throws java.lang.Exception
java.lang.Exception
public void testConcurrentResultSets()
throws java.lang.Exception
java.lang.Exceptionprivate static java.lang.String array2String(java.lang.Object[] a)
public void testNumericOverflow()
throws java.sql.SQLException
java.sql.SQLException
public void testNegativeOverflow()
throws java.sql.SQLException
java.sql.SQLException
public void testDatePerformance()
throws java.sql.SQLException
java.sql.SQLExceptionpublic static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.DatabaseTestCase
net.sourceforge.jtds.test.SunTest
Test case to illustrate errors reported by SUN JBDC compatibility test suite.
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
|
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
SunTest(java.lang.String name)
|
|
| Method Summary | |
static void |
main(java.lang.String[] args)
|
static junit.framework.Test |
suite()
|
void |
testCharToLong()
Generic test for SUN bugs: bigint null parameter values sent as integer size. |
void |
testCharToReal()
Generic test for errors caused by promotion out parameters of Float to Double by driver. |
void |
testConversionToLongvarchar()
Test conversion of various types to LONGVARCHAR. |
void |
testDateTime()
Generic Tests for SUN bugs such as Can't convert VARCHAR to Timestamp Can't convert VARCHAR to Time Can't convert VARCHAR to Date Internal time representation causes equals to fail |
void |
testDateTimeFn()
Test for bug [ 1008126 ] Metadata getTimeDateFunctions() wrong |
void |
testGetFloatObject()
Generic test for SUN bug where Float was promoted to Double by driver leading to ClassCastExceptions in the tests. |
void |
testGetMetaData()
Test for SUN bug [ PrepStmt1.getMetaData() ] Driver loops if select contains commas. |
void |
testGetProcedures()
Test for SUN bug [ dbMeta8.testGetProcedures ] The wrong column names are returned by getProcedures(). |
void |
testNestedEscapes()
Test nested escapes |
void |
testPrepStmtError()
Test for bug [ 1012301 ] 0.9-rc1: Prepared statement execution error. |
void |
testSetDateObject()
Test for bug [ 1012307 ] PreparedStatement.setObject(java.util.Date) not working. |
void |
testSetFetchDirectiion()
Test for SUN bug [ stmt2.testSetFetchDirection04 ] fetch direction constant not validated. |
void |
testSetFetchSize()
Test for SUN bug [ resultSet1.testSetFetchSize02 ] attempt to set non zero fetch size rejected. |
void |
testSqlComments()
Test for bug [ 1011650 ] 0.9-rc1: comments get parsed |
void |
testStringFn()
Test for scalar string functions. |
| Methods inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
compareBytes, dropFunction, dropProcedure, dropProcedure, dropTable, getLongString, getLongString, getType, getTypemap |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public SunTest(java.lang.String name)
| Method Detail |
public static junit.framework.Test suite()
public void testGetMetaData()
throws java.lang.Exception
java.lang.Exception
public void testDateTime()
throws java.lang.Exception
java.lang.Exception
public void testCharToReal()
throws java.lang.Exception
java.lang.Exception
public void testCharToLong()
throws java.lang.Exception
java.lang.Exception
public void testGetProcedures()
throws java.lang.Exception
java.lang.Exception
public void testGetFloatObject()
throws java.lang.Exception
java.lang.Exception
public void testSetFetchSize()
throws java.lang.Exception
java.lang.Exception
public void testSetFetchDirectiion()
throws java.lang.Exception
java.lang.Exception
public void testSetDateObject()
throws java.lang.Exception
java.lang.Exception
public void testPrepStmtError()
throws java.lang.Exception
java.lang.Exception
public void testSqlComments()
throws java.lang.Exception
java.lang.Exception
public void testDateTimeFn()
throws java.lang.Exception
java.lang.Exception
public void testStringFn()
throws java.lang.Exception
java.lang.Exception
public void testNestedEscapes()
throws java.lang.Exception
java.lang.Exception
public void testConversionToLongvarchar()
throws java.sql.SQLException
java.sql.SQLExceptionpublic static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjava.io.InputStream
net.sourceforge.jtds.test.LOBTest.RealInputStream
Implements an InputStream that only returns a limited
number of bytes on read (less than the requested number of bytes).
Used for testing Blob insert behavior.
| Field Summary | |
(package private) static int |
LENGTH
Length of the stream. |
private int |
pos
Current position in the stream. |
| Fields inherited from class java.io.InputStream |
|
| Constructor Summary | |
(package private) |
LOBTest.RealInputStream()
|
| Method Summary | |
int |
read()
|
int |
read(byte[] b)
|
int |
read(byte[] b,
int off,
int len)
|
| Methods inherited from class java.io.InputStream |
available, close, mark, markSupported, reset, skip |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
static final int LENGTH
private int pos
| Constructor Detail |
LOBTest.RealInputStream()
| Method Detail |
public int read()
public int read(byte[] b)
public int read(byte[] b,
int off,
int len)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV PACKAGE NEXT PACKAGE | FRAMES NO FRAMES | ||||||||||
| Class Summary | |
| AsTest | |
| BatchTest | Simple test suite to exercise batch execution. |
| CallableStatementJDBC3Test | Test the JDBC 3.0 features of CallableStatement. |
| CallableStatementTest | |
| ClientSideCursorTest | Test case to illustrate use of Cached cursor result set. |
| ConnectionJDBC2UnitTest | Unit test for the ConnectionJDBC2 class. |
| ConnectionJDBC2UnitTest.Test_ConnectionJDBC2_unpackProperties | Class used to test net.sourceforge.jtds.jdbc.ConnectionJDBC2.unpackProperties(Properties). |
| ConnectionJDBC3Test | JDBC 3.0-only tests for Connection. |
| ConnectionJDBC3Test.testTimerStopHelper | Helper class for test for bug [2871274]. |
| CSUnitTest | |
| DatabaseMetaDataJDBC3Test | Test JDBC3 extensions to DatabaseMetaData. |
| DatabaseMetaDataTest | Test DatabaseMetaData. |
| DatabaseMetaDataTypeInfoTest | Tests for DatabaseMetaData.getTypeInfo(). |
| DatabaseTestCase | |
| DefaultPropertiesTester | Abstract class used to test the default properties set on a variety of methods. |
| DefaultPropertiesTestLibrary | Library for testing default properties. |
| DefaultPropertiesUnitTest | Unit tests for the DefaultProperties class. |
| DriverUnitTest | Unit tests for the Driver class. |
| DriverUnitTest.Test_Driver_getPropertyInfo | Class used to test Driver.getPropertyInfo(String, Properties). |
| DriverUnitTest.Test_Driver_setupConnectProperties | Class used to test Driver.setupConnectProperties(String, java.util.Properties). |
| EncodingTest | |
| GenKeyTest | Test case to illustrate JDBC 3 GetGeneratedKeys() function. |
| JDBC3Test | Test for miscellaneous JDBC 3.0 features. |
| JtdsDataSourceUnitTest | Unit tests for the JtdsDataSource class. |
| JtdsDataSourceUnitTest.Test_JtdsDataSource_addNonNullProperties | Class used to test JtdsDataSource.addNonNullProperties(Properties, String, String). |
| JtdsDataSourceUnitTest.Test_JtdsDataSource_fields | Class used to test JtdsDataSource. |
| JtdsDataSourceUnitTest.Test_JtdsDataSource_getConnection | |
| JtdsDataSourceUnitTest.Test_JtdsDataSource_getReference | Class used to test JtdsDataSource.getReference(). |
| JtdsObjectFactoryUnitTest | Unit tests for the JtdsObjectFactory class. |
| JtdsObjectFactoryUnitTest.Test_JtdsObjectFactory_getObjectInstance_DefaultValues | Class used to test JtdsObjectFactory.getObjectInstance(Object, Name, Context, Hashtable). |
| LargeLOBTest | |
| LOBTest | |
| LOBTest.RealInputStream | Implements an InputStream that only returns a limited
number of bytes on read (less than the requested number of bytes).
|
| MessagesPropertiesUnitTest | Unit tests for the Messages.properties file. |
| MessagesPropertiesUnitTest.TestDescriptionHasProperty | Tests that a given description key has a matching property key in
Messages.properties. |
| MessagesPropertiesUnitTest.TestPropertyHasDescription | Tests that a given property key has a matching description key in
Messages.properties. |
| MetaDataTestCase | Base class for meta data test cases. |
| NamedPipeUnitTest | Unit tests for the SharedNamedPipe class. |
| NtlmAuthTest | Unit test for NTLM challenge/response calculation |
| PreparedStatementTest | |
| PreparedStatementTest.TestMultiThread | Inner class used by PreparedStatementTest.testMultiThread() to
test concurrency. |
| ReadTextTest | Test case to illustrate use of READTEXT for text and image columns. |
| ResultSetTest | |
| SAfeTest | |
| SanityTest | Some simple tests just to make sure everything is working properly. |
| SavepointTest | |
| StatementTest | |
| SunTest | Test case to illustrate errors reported by SUN JBDC compatibility test suite. |
| SupportUnitTest | Unit tests for the Support class. |
| Tds5Test | Test case to illustrate use of TDS 5 support. |
| Tds8Test | Test case to illustrate use of TDS 8 support |
| TestBase | |
| TimestampTest | test getting timestamps from the database. |
| TimeZoneTest | Tests timezone conversions when setting and getting data to and from the database. |
| TlsTest | Test for SSL TLS. |
| TypeInfoTest | Tests for the TypeInfo class. |
| UnitTestBase | Base class for unit tests which do not connect to a database. |
| UpdateTest | |
| XaTest | Test suite for XA Distributed Transactions. |
|
|||||||||||
| PREV PACKAGE NEXT PACKAGE | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
net.sourceforge.jtds.test.JtdsDataSourceUnitTest.Test_JtdsDataSource_addNonNullProperties
Class used to test JtdsDataSource.addNonNullProperties(Properties, String, String).
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary |
|
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
JtdsDataSourceUnitTest.Test_JtdsDataSource_addNonNullProperties()
Default constructor. |
|
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, setUp, tearDown, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public JtdsDataSourceUnitTest.Test_JtdsDataSource_addNonNullProperties()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
net.sourceforge.jtds.test.JtdsDataSourceUnitTest.Test_JtdsDataSource_getReference
Class used to test JtdsDataSource.getReference().
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary |
|
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
JtdsDataSourceUnitTest.Test_JtdsDataSource_getReference()
Default constructor. |
|
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, setUp, tearDown, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public JtdsDataSourceUnitTest.Test_JtdsDataSource_getReference()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
Library for testing default properties.
Uses aDefaultPropertiesTester object to test different methods
in different classes.
To extend this class, the programmer must implement the following items:
#tester field in a public default
constructor that takes no arguments.public static Test suite() method that takes one or more
arguments. (The suite() method in this class should
not be overridden.)
| Field Summary | |
private boolean |
onlySqlServerTests
If true, only run tests for SQL Server, not Sybase. |
private boolean |
onlyTds70Tests
If true, only run tests for TDS 7.0. |
private DefaultPropertiesTester |
tester
Object used to run all of the tests. |
private static java.lang.String |
URL_SQLSERVER
Test JDBC URL for SQL Server. |
private static java.lang.String |
URL_SYBASE
Test JDBC URL for Sybase. |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
DefaultPropertiesTestLibrary()
Default constructor. |
|
| Method Summary | |
private void |
assertDefaultPropertyByServerType(java.lang.String url,
java.lang.String key,
java.lang.String fieldName,
java.lang.String expected)
Assert that the expected property value is set using
a given url. |
private void |
assertDefaultPropertyByTdsVersion(java.lang.String url,
java.lang.String tdsVersion,
java.lang.String key,
java.lang.String fieldName,
java.lang.String expected)
Assert that the expected property value is set using
a given url and tdsVersion property. |
protected DefaultPropertiesTester |
getTester()
Getter for tester. |
boolean |
isOnlySqlServerTests()
Getter for #onlySqlServerTests. |
boolean |
isOnlyTds70Tests()
Getter for #onlyTds70Tests. |
protected void |
setOnlySqlServerTests(boolean onlySqlServerTests)
Setter for onlySqlServerTests. |
protected void |
setOnlyTds70Tests(boolean onlyTds70Tests)
Setter for onlyTds70Tests. |
void |
setTester(DefaultPropertiesTester tester)
Setter for #tester. |
static junit.framework.Test |
suite()
Provides a null test suite so that JUnit will not try to instantiate this class directly. |
void |
test_appName()
Test the appName property. |
void |
test_batchSize()
Test the batchSize property. |
void |
test_bindAddress()
Test the bindAddress property. |
void |
test_bufferDir()
Test the bufferDir property. |
void |
test_bufferMaxMemory()
Test the bufferMaxMemory property. |
void |
test_bufferMinPackets()
Test the bufferMinPackets property. |
void |
test_cacheMetaData()
Test the cacheMetaData property. |
void |
test_databaseName()
Test the databaseName property. |
void |
test_lastUpdateCount()
Test the lastUpdateCount property. |
void |
test_lobBuffer()
Test the lobBuffer property. |
void |
test_loginTimeout()
Test the loginTimeout property. |
void |
test_macAddress()
Test the macAddress property. |
void |
test_namedPipe()
Test the namedPipe property. |
void |
test_packetSize()
Test the packetSize property. |
void |
test_portNumber()
Test the portNumber property.
|
void |
test_prepareSql()
Test the prepareSql property. |
void |
test_processId()
Test the processId property. |
void |
test_progName()
Test the progName property. |
void |
test_sendStringParametersAsUnicode()
Test the sendStringParametersAsUnicode property. |
void |
test_serverType()
Test the serverType property.
|
void |
test_socketKeepAlive()
Test the socketKeepAlive property. |
void |
test_socketTimeout()
Test the socketTimeout property. |
void |
test_tcpNoDelay()
Test the tcpNoDelay property. |
void |
test_tds()
Test the tds (version) property. |
void |
test_useCursors()
Test the useCursors property. |
void |
test_useJCIFS()
Test the useJCIFS property. |
void |
test_useLOBs()
Test the useLOBs property. |
void |
test_wsid()
Test the wsid property. |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, setUp, tearDown, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
private static final java.lang.String URL_SQLSERVER
private static final java.lang.String URL_SYBASE
private DefaultPropertiesTester tester
private boolean onlySqlServerTests
private boolean onlyTds70Tests
| Constructor Detail |
public DefaultPropertiesTestLibrary()
#tester
field in a public default constructor.
| Method Detail |
public static final junit.framework.Test suite()
null).public void test_serverType()
serverType property.
Different values are set depending on whether SQL Server or
Sybase is used.
public void test_tds()
tds (version) property.
public void test_portNumber()
portNumber property.
Different values are set depending on whether SQL Server or
Sybase is used.
public void test_databaseName()
databaseName property.
public void test_appName()
appName property.
public void test_bindAddress()
bindAddress property.
public void test_lastUpdateCount()
lastUpdateCount property.
public void test_lobBuffer()
lobBuffer property.
public void test_loginTimeout()
loginTimeout property.
public void test_socketTimeout()
socketTimeout property.
public void test_socketKeepAlive()
socketKeepAlive property.
public void test_processId()
processId property.
public void test_macAddress()
macAddress property.
public void test_namedPipe()
namedPipe property.
public void test_packetSize()
packetSize property.
public void test_prepareSql()
prepareSql property.
public void test_progName()
progName property.
public void test_sendStringParametersAsUnicode()
sendStringParametersAsUnicode property.
public void test_batchSize()
batchSize property.
public void test_bufferDir()
bufferDir property.
public void test_bufferMaxMemory()
bufferMaxMemory property.
public void test_bufferMinPackets()
bufferMinPackets property.
public void test_cacheMetaData()
cacheMetaData property.
public void test_tcpNoDelay()
tcpNoDelay property.
public void test_useCursors()
useCursors property.
public void test_useJCIFS()
useJCIFS property.
public void test_useLOBs()
useLOBs property.
public void test_wsid()
wsid property.
private void assertDefaultPropertyByTdsVersion(java.lang.String url,
java.lang.String tdsVersion,
java.lang.String key,
java.lang.String fieldName,
java.lang.String expected)
expected property value is set using
a given url and tdsVersion property.
url - The JDBC URL.tdsVersion - The TDS version.key - The message key.fieldName - The field name used in the class.expected - The expected value of the property.
private void assertDefaultPropertyByServerType(java.lang.String url,
java.lang.String key,
java.lang.String fieldName,
java.lang.String expected)
expected property value is set using
a given url.
url - The JDBC URL.key - The message key.fieldName - The field name used in the class.expected - The expected value of the property.protected DefaultPropertiesTester getTester()
public void setTester(DefaultPropertiesTester tester)
#tester.
tester - The value to set #tester to.public boolean isOnlySqlServerTests()
#onlySqlServerTests.
#onlySqlServerTests.protected void setOnlySqlServerTests(boolean onlySqlServerTests)
onlySqlServerTests.
onlySqlServerTests - The value to set onlySqlServerTests to.public boolean isOnlyTds70Tests()
#onlyTds70Tests.
#onlyTds70Tests.protected void setOnlyTds70Tests(boolean onlyTds70Tests)
onlyTds70Tests.
onlyTds70Tests - The value to set onlyTds70Tests to.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.DatabaseTestCase
net.sourceforge.jtds.test.XaTest
Test suite for XA Distributed Transactions. These tests are derived from examples found in the following article at DevX.
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
|
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
XaTest(java.lang.String name)
|
|
| Method Summary | |
javax.sql.XADataSource |
getDataSource()
Obtain an XADataSource. |
static void |
main(java.lang.String[] args)
|
void |
testLocalTran()
Demonstrate interleaving local transactions and distributed transactions. |
void |
testXaCommit()
Test to demonstrate the XA_COMMIT function. |
void |
testXAJoinTran()
Test to demonstrate the use of the XA_JOIN command. |
void |
testXaOnePhaseCommit()
Test to demonstrate the single phase XA_COMMIT function. |
void |
testXARecover()
Test to demonstrate the use of the XA_RECOVER command. |
void |
testXaRollback()
Test to demonstrate the use of the XA_ROLLBACK command. |
| Methods inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
compareBytes, dropFunction, dropProcedure, dropProcedure, dropTable, getLongString, getLongString, getType, getTypemap |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public XaTest(java.lang.String name)
| Method Detail |
public javax.sql.XADataSource getDataSource()
throws java.sql.SQLException
XADataSource.
- Throws:
java.sql.SQLException - if an error condition occurs
public void testXaCommit()
throws java.lang.Exception
java.lang.Exception - if an error condition occurs
public void testXaOnePhaseCommit()
throws java.lang.Exception
java.lang.Exception - if an error condition occurs
public void testXaRollback()
throws java.lang.Exception
java.lang.Exception - if an error condition occurs
public void testLocalTran()
throws java.lang.Exception
java.lang.Exception - if an error condition occurs
public void testXAJoinTran()
throws java.lang.Exception
java.lang.Exception - if an error condition occurs
public void testXARecover()
throws java.lang.Exception
java.lang.Exception - if an error condition occurspublic static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.JDBC3Test
Test for miscellaneous JDBC 3.0 features.
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
JDBC3Test(java.lang.String name)
|
|
| Method Summary | |
void |
testGetParamMetaData()
Test for bug [1222205] getParameterMetaData returns not implemented. |
void |
testMultipleResults()
Test return of multiple open result sets from one execute. |
void |
testSocketConcurrency5()
Test closing a ResultSet when it's out of scope.
|
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public JDBC3Test(java.lang.String name)
| Method Detail |
public void testMultipleResults()
throws java.lang.Exception
java.lang.Exception
public void testSocketConcurrency5()
throws java.lang.Exception
ResultSet when it's out of scope.
If a finalize() method which tries to call close() is added to
JtdsResultSet the next() calls will be executed concurrently with any
other result processing, with no synchronization whatsoever.
java.lang.Exception
public void testGetParamMetaData()
throws java.sql.SQLException
java.sql.SQLException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
| Field Summary | |
(package private) java.sql.Connection |
con
|
private static java.lang.String |
CONNECTION_PROPERTIES
|
static java.util.Properties |
props
|
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
TestBase(java.lang.String name)
|
|
| Method Summary | |
void |
compareInputStreams(java.io.InputStream is1,
java.io.InputStream is2)
|
void |
compareReaders(java.io.Reader r1,
java.io.Reader r2)
|
protected void |
connect()
|
private void |
disconnect()
|
void |
dump(java.sql.ResultSet rs)
|
void |
dumpRow(java.sql.ResultSet rs)
|
java.sql.Connection |
getConnection()
|
java.sql.Connection |
getConnection(java.util.Properties override)
|
private static java.util.Properties |
loadProperties(java.lang.String fileName)
|
void |
makeObjects(java.sql.Statement stmt,
int count)
|
protected void |
makeTestTables(java.sql.Statement stmt)
|
void |
setUp()
|
void |
tearDown()
|
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
private static final java.lang.String CONNECTION_PROPERTIES
public static final java.util.Properties props
java.sql.Connection con
| Constructor Detail |
public TestBase(java.lang.String name)
| Method Detail |
public void setUp()
throws java.lang.Exception
java.lang.Exception
public void tearDown()
throws java.lang.Exception
java.lang.Exception
public java.sql.Connection getConnection()
throws java.lang.Exception
java.lang.Exception
public java.sql.Connection getConnection(java.util.Properties override)
throws java.lang.Exception
java.lang.Exception
private void disconnect()
throws java.lang.Exception
java.lang.Exception
protected void connect()
throws java.lang.Exception
java.lang.Exception
public void dump(java.sql.ResultSet rs)
throws java.sql.SQLException
java.sql.SQLException
public void dumpRow(java.sql.ResultSet rs)
throws java.sql.SQLException
java.sql.SQLExceptionprivate static java.util.Properties loadProperties(java.lang.String fileName)
protected void makeTestTables(java.sql.Statement stmt)
throws java.sql.SQLException
java.sql.SQLException
public void makeObjects(java.sql.Statement stmt,
int count)
throws java.sql.SQLException
java.sql.SQLException
public void compareInputStreams(java.io.InputStream is1,
java.io.InputStream is2)
throws java.io.IOException
java.io.IOException
public void compareReaders(java.io.Reader r1,
java.io.Reader r2)
throws java.io.IOException
java.io.IOException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.DefaultPropertiesTestLibrary
net.sourceforge.jtds.test.DriverUnitTest.Test_Driver_setupConnectProperties
Class used to test Driver.setupConnectProperties(String, java.util.Properties).
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.DefaultPropertiesTestLibrary |
|
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
DriverUnitTest.Test_Driver_setupConnectProperties()
Default constructor. |
|
| Method Summary | |
static junit.framework.Test |
suite(java.lang.String name)
Construct a test suite for this library. |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, setUp, tearDown, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public DriverUnitTest.Test_Driver_setupConnectProperties()
| Method Detail |
public static junit.framework.Test suite(java.lang.String name)
name - The name of the tests.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.UnitTestBase
net.sourceforge.jtds.test.MessagesPropertiesUnitTest.TestDescriptionHasProperty
Tests that a given description key has a matching property key in
Messages.properties.
| Field Summary | |
private java.util.ResourceBundle |
messages
|
private java.lang.String |
property
|
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
MessagesPropertiesUnitTest.TestDescriptionHasProperty(java.lang.String property,
java.util.ResourceBundle messages)
Constructor. |
|
| Method Summary | |
protected void |
runTest()
Runs the test that a given description key has a matching property key in Messages.properties. |
static junit.framework.Test |
suite()
Provides a null test suite so that JUnit will not try to instantiate this class directly. |
| Methods inherited from class net.sourceforge.jtds.test.UnitTestBase |
assertEquals, invokeConstructor, invokeGetInstanceField, invokeInstanceMethod, invokeSetInstanceField, invokeStaticMethod, ucFirst |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, setName, setUp, tearDown, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
private final java.util.ResourceBundle messages
private final java.lang.String property
| Constructor Detail |
public MessagesPropertiesUnitTest.TestDescriptionHasProperty(java.lang.String property,
java.util.ResourceBundle messages)
property - The property name to test.messages - The resource bundle containing all of the messages.| Method Detail |
public static final junit.framework.Test suite()
null).
protected void runTest()
throws java.lang.Throwable
Messages.properties.
java.lang.Throwable - on error.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TypeInfoTest
Tests for the TypeInfo class.
| Field Summary |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
TypeInfoTest(java.lang.String testName)
|
|
| Method Summary | |
private void |
assertComparesLessThan(TypeInfo t1,
TypeInfo t2)
|
static void |
main(java.lang.String[] args)
|
void |
testCharTypes()
|
void |
testCompareToDifferentDataType()
|
void |
testCompareToIdentity()
|
void |
testVarcharTypes()
|
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, setUp, tearDown, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public TypeInfoTest(java.lang.String testName)
| Method Detail |
public void testCharTypes()
public void testVarcharTypes()
public void testCompareToDifferentDataType()
public void testCompareToIdentity()
private void assertComparesLessThan(TypeInfo t1, TypeInfo t2)
public static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.UnitTestBase
net.sourceforge.jtds.test.JtdsObjectFactoryUnitTest
Unit tests for the JtdsObjectFactory class.
| Nested Class Summary | |
static class |
JtdsObjectFactoryUnitTest.Test_JtdsObjectFactory_getObjectInstance_DefaultValues
Class used to test JtdsObjectFactory.getObjectInstance(Object, Name, Context, Hashtable). |
| Field Summary |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
JtdsObjectFactoryUnitTest(java.lang.String name)
Constructor. |
|
| Method Summary | |
static junit.framework.Test |
suite()
Construct a test suite for this class. |
void |
testNoProperties()
Tests that the factory can correctly rebuild a DataSource with no properties set (i.e. all values should be null and no NPE should be thrown). |
| Methods inherited from class net.sourceforge.jtds.test.UnitTestBase |
assertEquals, invokeConstructor, invokeGetInstanceField, invokeInstanceMethod, invokeSetInstanceField, invokeStaticMethod, ucFirst |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, setUp, tearDown, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public JtdsObjectFactoryUnitTest(java.lang.String name)
name - The name of the test.| Method Detail |
public static junit.framework.Test suite()
DefaultPropertiesTestLibrary after creating an anonymous
DefaultPropertiesTester object.
public void testNoProperties()
throws java.lang.Exception
java.lang.Exception
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.test.ConnectionJDBC3Test.testTimerStopHelper
Helper class for test for bug [2871274].
| Constructor Summary | |
ConnectionJDBC3Test.testTimerStopHelper()
Constructor for helper class, simply starts method test(). |
|
| Method Summary | |
private static java.util.Properties |
loadProperties()
Loads the connection properties from config file. |
void |
test()
The actual test, creates and closes a number of connections. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Constructor Detail |
public ConnectionJDBC3Test.testTimerStopHelper()
throws java.lang.Throwable
test().
| Method Detail |
public void test()
throws java.lang.Exception
java.lang.Exception
private static java.util.Properties loadProperties()
throws java.lang.Exception
java.lang.Exception
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.UnitTestBase
Base class for unit tests which do not connect to a database.
| Field Summary |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
UnitTestBase(java.lang.String name)
Constructor. |
|
| Method Summary | |
protected void |
assertEquals(java.lang.String message,
java.lang.Object[] expected,
java.lang.Object[] actual)
Compare two arrays element-by-element. |
private void |
failNotEquals(java.lang.String message,
java.lang.Object[] expected,
java.lang.Object[] actual)
|
private java.lang.String |
format(java.lang.Object[] object)
Format an Object[] object to a String. |
static java.lang.Object |
invokeConstructor(java.lang.Class klass,
java.lang.Class[] classes,
java.lang.Object[] objects)
Invoke a constructor on a class using reflection. |
static java.lang.Object |
invokeGetInstanceField(java.lang.Object instance,
java.lang.String fieldName)
Get the value of an instance field on an object using reflection. |
static java.lang.Object |
invokeInstanceMethod(java.lang.Object instance,
java.lang.String methodName,
java.lang.Class[] classes,
java.lang.Object[] objects)
Invoke an instance method on an object using reflection. |
static void |
invokeSetInstanceField(java.lang.Object instance,
java.lang.String fieldName,
java.lang.Object fieldValue)
Set the value of an instance field on an object using reflection. |
static java.lang.Object |
invokeStaticMethod(java.lang.Class klass,
java.lang.String methodName,
java.lang.Class[] classes,
java.lang.Object[] objects)
Invoke a static method on a class using reflection. |
protected static java.lang.String |
ucFirst(java.lang.String s)
Changes the first character of a string to uppercase. |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, setUp, tearDown, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public UnitTestBase(java.lang.String name)
name - The name of the test.| Method Detail |
public static java.lang.Object invokeConstructor(java.lang.Class klass,
java.lang.Class[] classes,
java.lang.Object[] objects)
klass - The class.classes - The classes in the parameter list.objects - The objects to be used as parameters.
public static java.lang.Object invokeGetInstanceField(java.lang.Object instance,
java.lang.String fieldName)
instance - The instance of the object.fieldName - The name of the field.
public static void invokeSetInstanceField(java.lang.Object instance,
java.lang.String fieldName,
java.lang.Object fieldValue)
instance - The instance of the object.fieldName - The name of the field.fieldValue - The value to set the field to.
public static java.lang.Object invokeInstanceMethod(java.lang.Object instance,
java.lang.String methodName,
java.lang.Class[] classes,
java.lang.Object[] objects)
instance - The instance of the object.methodName - The name of the method.classes - The classes in the parameter list.objects - The objects to be used as parameters.
public static java.lang.Object invokeStaticMethod(java.lang.Class klass,
java.lang.String methodName,
java.lang.Class[] classes,
java.lang.Object[] objects)
klass - The class.methodName - The name of the method.classes - The classes in the parameter list.objects - The objects to be used as parameters.
protected void assertEquals(java.lang.String message,
java.lang.Object[] expected,
java.lang.Object[] actual)
Assert.assertEquals(String, Object, Object) method
does not handle them properly.
message - The message to print upon failure.expected - The expected value.actual - The actual value.
private void failNotEquals(java.lang.String message,
java.lang.Object[] expected,
java.lang.Object[] actual)
Assert.failNotEquals(java.lang.String, java.lang.Object, java.lang.Object)private java.lang.String format(java.lang.Object[] object)
Object[] object to a String.
object - The object to be formatted.
protected static java.lang.String ucFirst(java.lang.String s)
s - The string to be processed.
s if it is null or zero length,
else the string with the first character changed to uppercase.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.DatabaseTestCase
| Field Summary | |
private static java.util.Map |
typemap
|
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
DatabaseTestCase(java.lang.String name)
|
|
| Method Summary | |
(package private) static int |
compareBytes(byte[] a1,
byte[] a2)
|
protected void |
dropFunction(java.lang.String procname)
|
protected void |
dropProcedure(java.sql.Statement stmt,
java.lang.String procname)
|
protected void |
dropProcedure(java.lang.String procname)
|
protected void |
dropTable(java.lang.String tableName)
|
protected java.lang.String |
getLongString(char ch)
|
protected java.lang.String |
getLongString(int length)
|
protected static int |
getType(java.lang.Object o)
|
protected static java.util.Map |
getTypemap()
|
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
private static java.util.Map typemap
| Constructor Detail |
public DatabaseTestCase(java.lang.String name)
| Method Detail |
protected void dropTable(java.lang.String tableName)
throws java.sql.SQLException
java.sql.SQLException
protected void dropProcedure(java.lang.String procname)
throws java.sql.SQLException
java.sql.SQLException
protected void dropProcedure(java.sql.Statement stmt,
java.lang.String procname)
throws java.sql.SQLException
java.sql.SQLException
protected void dropFunction(java.lang.String procname)
throws java.sql.SQLException
java.sql.SQLException
static int compareBytes(byte[] a1,
byte[] a2)
protected static java.util.Map getTypemap()
protected static int getType(java.lang.Object o)
throws java.sql.SQLException
java.sql.SQLExceptionprotected java.lang.String getLongString(int length)
protected java.lang.String getLongString(char ch)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use net.sourceforge.jtds.test | |
| net.sourceforge.jtds.test | |
| Classes in net.sourceforge.jtds.test used by net.sourceforge.jtds.test | |
| DatabaseTestCase
|
|
| DefaultPropertiesTester
Abstract class used to test the default properties set on a variety of methods. |
|
| DefaultPropertiesTestLibrary
Library for testing default properties. |
|
| MetaDataTestCase
Base class for meta data test cases. |
|
| TestBase
|
|
| UnitTestBase
Base class for unit tests which do not connect to a database. |
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.DatabaseTestCase
net.sourceforge.jtds.test.Tds8Test
Test case to illustrate use of TDS 8 support
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
|
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
Tds8Test(java.lang.String name)
|
|
| Method Summary | |
static void |
main(java.lang.String[] args)
|
static junit.framework.Test |
suite()
|
void |
testBigInt1()
|
void |
testBigInt2()
Test BIGINT data type. |
void |
testColumnCollations()
Test column collations. |
void |
testEncoding1251Test1()
Test for bug [981958] PreparedStatement doesn't work correctly |
void |
testMetaData()
|
void |
testNullBoolean()
Test for bug [1042272] jTDS doesn't allow null value into Boolean. |
void |
testSQL2005MetaData()
Test for enhanced database metadata for SQL 2005. |
void |
testSqlVariant()
|
void |
testUserFn()
|
| Methods inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
compareBytes, dropFunction, dropProcedure, dropProcedure, dropTable, getLongString, getLongString, getType, getTypemap |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public Tds8Test(java.lang.String name)
| Method Detail |
public static junit.framework.Test suite()
public void testBigInt1()
throws java.lang.Exception
java.lang.Exception
public void testBigInt2()
throws java.lang.Exception
java.lang.Exception
public void testSqlVariant()
throws java.lang.Exception
java.lang.Exception
public void testUserFn()
throws java.lang.Exception
java.lang.Exception
public void testMetaData()
throws java.lang.Exception
java.lang.Exception
public void testNullBoolean()
throws java.lang.Exception
java.lang.Exception
public void testColumnCollations()
throws java.lang.Exception
java.lang.Exception
public void testEncoding1251Test1()
throws java.lang.Exception
java.lang.Exception
public void testSQL2005MetaData()
throws java.lang.Exception
java.lang.Exceptionpublic static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.UnitTestBase
net.sourceforge.jtds.test.DriverUnitTest
Unit tests for the Driver class.
| Nested Class Summary | |
static class |
DriverUnitTest.Test_Driver_getPropertyInfo
Class used to test Driver.getPropertyInfo(String, Properties). |
static class |
DriverUnitTest.Test_Driver_setupConnectProperties
Class used to test Driver.setupConnectProperties(String, java.util.Properties). |
| Field Summary |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
DriverUnitTest(java.lang.String name)
Constructor. |
|
| Method Summary | |
private void |
loadDriverPropertyInfoMap(java.util.Map driverPropertyInfoMap)
Retrieve the DriverPropertyInfo array from
Driver.getPropertyInfo(String, Properties) and convert it
into a Map using the name property for the keys. |
static junit.framework.Test |
suite()
Construct a test suite for this class. |
void |
test_getPropertyInfo_Choices()
Tests that the DriverPropertyInfo array returned from
Driver.getPropertyInfo(String, Properties) contains
the correct choices value on each of the objects. |
void |
test_getPropertyInfo_MatchesMessagesProperties()
Tests that the DriverPropertyInfo array returned from
Driver.getPropertyInfo(String, Properties)
matches the list of properties defined in Messages.properties. |
void |
test_getPropertyInfo_Required()
Tests that the DriverPropertyInfo array returned from
Driver.getPropertyInfo(String, Properties) contains
the correct required value on each of the objects. |
void |
test_getPropertyInfo_ThrowsSQLExceptionWithNonNullProperties()
Tests that passing in a non-null properties argument to Driver.getPropertyInfo(String, Properties)
causes the url to be parsed, which then throws a SQLException. |
void |
test_getPropertyInfo_ThrowsSQLExceptionWithNullProperties()
Tests that passing in a null properties argument to Driver.getPropertyInfo(String, Properties)
causes the url to be parsed, which then throws a SQLException. |
| Methods inherited from class net.sourceforge.jtds.test.UnitTestBase |
assertEquals, invokeConstructor, invokeGetInstanceField, invokeInstanceMethod, invokeSetInstanceField, invokeStaticMethod, ucFirst |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, setUp, tearDown, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public DriverUnitTest(java.lang.String name)
name - The name of the test.| Method Detail |
public static junit.framework.Test suite()
DefaultPropertiesTestLibrary after creating
anonymous DefaultPropertiesTester objects.
public void test_getPropertyInfo_ThrowsSQLExceptionWithNullProperties()
Driver.getPropertyInfo(String, Properties)
causes the url to be parsed, which then throws a SQLException.
public void test_getPropertyInfo_ThrowsSQLExceptionWithNonNullProperties()
Driver.getPropertyInfo(String, Properties)
causes the url to be parsed, which then throws a SQLException.
public void test_getPropertyInfo_MatchesMessagesProperties()
DriverPropertyInfo array returned from
Driver.getPropertyInfo(String, Properties)
matches the list of properties defined in Messages.properties.
public void test_getPropertyInfo_Choices()
DriverPropertyInfo array returned from
Driver.getPropertyInfo(String, Properties) contains
the correct choices value on each of the objects.
public void test_getPropertyInfo_Required()
DriverPropertyInfo array returned from
Driver.getPropertyInfo(String, Properties) contains
the correct required value on each of the objects.
private void loadDriverPropertyInfoMap(java.util.Map driverPropertyInfoMap)
DriverPropertyInfo array from
Driver.getPropertyInfo(String, Properties) and convert it
into a Map using the name property for the keys.
driverPropertyInfoMap - The map of DriverPropertyInfo objects to be populated.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.LOBTest
| Nested Class Summary | |
(package private) static class |
LOBTest.RealInputStream
Implements an InputStream that only returns a limited
number of bytes on read (less than the requested number of bytes).
|
| Field Summary | |
private static byte[] |
blobData
|
private static java.lang.String |
clobData
|
private static int |
LOB_LENGTH
|
private static byte[] |
newBlobData
|
private static java.lang.String |
newClobData
|
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
LOBTest(java.lang.String name)
|
|
| Method Summary | |
private boolean |
compare(byte[] b1,
byte[] b2)
Compares long byte arrays. |
boolean |
compare(java.lang.String s1,
java.lang.String s2)
Compare long Strings. |
private byte[] |
getBlobTestData()
|
private java.lang.String |
getClobTestData()
|
private byte[] |
getNewBlobTestData()
|
private java.lang.String |
getNewClobTestData()
|
static void |
main(java.lang.String[] args)
|
void |
testBlobEmpty()
Test for bug [1062395] Empty (but not null) blobs should return byte[0]. |
void |
testBlobGet1()
BLOB TESTS ** |
void |
testBlobGet2()
|
void |
testBlobGetBytes1()
Test for bug [989399] blob.getBytes() from 0. |
void |
testBlobGetBytes2()
|
void |
testBlobGetBytes3()
|
void |
testBlobLength1()
|
void |
testBlobMethods()
Test for bug [1172405] BLOB/CLOB position methods fail. |
void |
testBlobSet1()
|
void |
testBlobSet2()
|
void |
testBlobSet3()
|
void |
testBlobSet4()
|
void |
testBlobSet5()
|
void |
testBlobSet6()
|
void |
testBlobSet7()
|
void |
testBlobSet8()
Test inserting from an InputStream that doesn't fill the
buffer on read().
|
void |
testBlobSetNull1()
|
void |
testBlobSetNull10()
|
void |
testBlobSetNull11()
|
void |
testBlobSetNull2()
|
void |
testBlobSetNull3()
|
void |
testBlobSetNull4()
Test for bug [985956] Cannot setObject(null) on image. |
void |
testBlobSetNull5()
|
void |
testBlobSetNull6()
|
void |
testBlobSetNull7()
|
void |
testBlobSetNull8()
|
void |
testBlobSetNull9()
|
void |
testBlobTruncate1()
|
void |
testBlobUpdate1()
|
void |
testBlobUpdate2()
|
void |
testBlobUpdate3()
|
void |
testBlobUpdate4()
|
void |
testBlobUpdate5()
Test Long blob manipulation including updates to the middle of the Blob. |
void |
testClobCaching()
|
void |
testClobEmpty()
Test for bug [1062395] Empty (but not null) blobs should return byte[0]. |
void |
testClobGet1()
CLOB TESTS ** |
void |
testClobGet2()
|
void |
testClobGetSubString1()
|
void |
testClobGetSubString2()
|
void |
testClobGetSubString3()
|
void |
testClobLength1()
|
void |
testClobMethods()
Test for bug [1172405] BLOB/CLOB position methods fail. |
void |
testClobSet1()
|
void |
testClobSet2()
|
void |
testClobSet3()
|
void |
testClobSet4()
|
void |
testClobSet5()
|
void |
testClobSet6()
|
void |
testClobSet7()
|
void |
testClobSet8()
|
void |
testClobSetNull1()
|
void |
testClobSetNull10()
|
void |
testClobSetNull11()
|
void |
testClobSetNull12()
|
void |
testClobSetNull13()
|
void |
testClobSetNull14()
|
void |
testClobSetNull2()
|
void |
testClobSetNull3()
|
void |
testClobSetNull4()
|
void |
testClobSetNull5()
|
void |
testClobSetNull6()
|
void |
testClobSetNull7()
|
void |
testClobSetNull8()
|
void |
testClobSetNull9()
|
void |
testClobTruncate1()
|
void |
testClobUpdate1()
|
void |
testClobUpdate2()
|
void |
testClobUpdate3()
|
void |
testClobUpdate4()
|
void |
testClobUpdate5()
|
void |
testClobUpdate6()
Test long Clob manipulation including indexed writes. |
void |
testZeroLengthStreams()
Test for incorrect handling of zero length streams (bug [1096086] Zero length streams generate null values). |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
private static final int LOB_LENGTH
private static final byte[] blobData
private static final byte[] newBlobData
private static final java.lang.String clobData
private static final java.lang.String newClobData
| Constructor Detail |
public LOBTest(java.lang.String name)
| Method Detail |
public void testBlobGet1()
throws java.lang.Exception
java.lang.Exception
public void testBlobGet2()
throws java.lang.Exception
java.lang.Exception
public void testBlobSet1()
throws java.lang.Exception
java.lang.Exception
public void testBlobSet2()
throws java.lang.Exception
java.lang.Exception
public void testBlobSet3()
throws java.lang.Exception
java.lang.Exception
public void testBlobSet4()
throws java.lang.Exception
java.lang.Exception
public void testBlobSet5()
throws java.lang.Exception
java.lang.Exception
public void testBlobSet6()
throws java.lang.Exception
java.lang.Exception
public void testBlobSet7()
throws java.lang.Exception
java.lang.Exception
public void testBlobSet8()
throws java.lang.Exception
InputStream that doesn't fill the
buffer on read().
For bug #1008816 - "More data in stream ..." error when inserting an image.
java.lang.Exception - if an error condition occurs
public void testBlobUpdate1()
throws java.lang.Exception
java.lang.Exception
public void testBlobUpdate2()
throws java.lang.Exception
java.lang.Exception
public void testBlobUpdate3()
throws java.lang.Exception
java.lang.Exception
public void testBlobUpdate4()
throws java.lang.Exception
java.lang.Exception
public void testBlobUpdate5()
throws java.lang.Exception
Blob.
java.lang.Exception
public void testBlobSetNull1()
throws java.lang.Exception
java.lang.Exception
public void testBlobSetNull2()
throws java.lang.Exception
java.lang.Exception
public void testBlobSetNull3()
throws java.lang.Exception
java.lang.Exception
public void testBlobSetNull4()
throws java.lang.Exception
java.lang.Exception
public void testBlobSetNull5()
throws java.lang.Exception
java.lang.Exception
public void testBlobSetNull6()
throws java.lang.Exception
java.lang.Exception
public void testBlobSetNull7()
throws java.lang.Exception
java.lang.Exception
public void testBlobSetNull8()
throws java.lang.Exception
java.lang.Exception
public void testBlobSetNull9()
throws java.lang.Exception
java.lang.Exception
public void testBlobSetNull10()
throws java.lang.Exception
java.lang.Exception
public void testBlobSetNull11()
throws java.lang.Exception
java.lang.Exception
public void testBlobGetBytes1()
throws java.lang.Exception
java.lang.Exception
public void testBlobGetBytes2()
throws java.lang.Exception
java.lang.Exception
public void testBlobGetBytes3()
throws java.lang.Exception
java.lang.Exception
public void testBlobLength1()
throws java.lang.Exception
java.lang.Exception
public void testBlobTruncate1()
throws java.lang.Exception
java.lang.Exception
public void testBlobEmpty()
throws java.lang.Exception
java.lang.Exception
public void testClobGet1()
throws java.lang.Exception
java.lang.Exception
public void testClobGet2()
throws java.lang.Exception
java.lang.Exception
public void testClobSet1()
throws java.lang.Exception
java.lang.Exception
public void testClobSet2()
throws java.lang.Exception
java.lang.Exception
public void testClobSet3()
throws java.lang.Exception
java.lang.Exception
public void testClobSet4()
throws java.lang.Exception
java.lang.Exception
public void testClobSet5()
throws java.lang.Exception
java.lang.Exception
public void testClobSet6()
throws java.lang.Exception
java.lang.Exception
public void testClobSet7()
throws java.lang.Exception
java.lang.Exception
public void testClobSet8()
throws java.lang.Exception
java.lang.Exception
public void testClobUpdate1()
throws java.lang.Exception
java.lang.Exception
public void testClobUpdate2()
throws java.lang.Exception
java.lang.Exception
public void testClobUpdate3()
throws java.lang.Exception
java.lang.Exception
public void testClobUpdate4()
throws java.lang.Exception
java.lang.Exception
public void testClobUpdate5()
throws java.lang.Exception
java.lang.Exception
public void testClobUpdate6()
throws java.lang.Exception
Clob manipulation including indexed writes.
java.lang.Exception
public void testClobSetNull1()
throws java.lang.Exception
java.lang.Exception
public void testClobSetNull2()
throws java.lang.Exception
java.lang.Exception
public void testClobSetNull3()
throws java.lang.Exception
java.lang.Exception
public void testClobSetNull4()
throws java.lang.Exception
java.lang.Exception
public void testClobSetNull5()
throws java.lang.Exception
java.lang.Exception
public void testClobSetNull6()
throws java.lang.Exception
java.lang.Exception
public void testClobSetNull7()
throws java.lang.Exception
java.lang.Exception
public void testClobSetNull8()
throws java.lang.Exception
java.lang.Exception
public void testClobSetNull9()
throws java.lang.Exception
java.lang.Exception
public void testClobSetNull10()
throws java.lang.Exception
java.lang.Exception
public void testClobSetNull11()
throws java.lang.Exception
java.lang.Exception
public void testClobSetNull12()
throws java.lang.Exception
java.lang.Exception
public void testClobSetNull13()
throws java.lang.Exception
java.lang.Exception
public void testClobSetNull14()
throws java.lang.Exception
java.lang.Exception
public void testClobGetSubString1()
throws java.lang.Exception
java.lang.Exception
public void testClobGetSubString2()
throws java.lang.Exception
java.lang.Exception
public void testClobGetSubString3()
throws java.lang.Exception
java.lang.Exception
public void testClobLength1()
throws java.lang.Exception
java.lang.Exception
public void testClobTruncate1()
throws java.lang.Exception
java.lang.Exception
public void testClobEmpty()
throws java.lang.Exception
java.lang.Exception
public void testClobCaching()
throws java.lang.Exception
java.lang.Exception
public void testZeroLengthStreams()
throws java.lang.Exception
java.lang.Exception
public void testBlobMethods()
throws java.lang.Exception
java.lang.Exception
public void testClobMethods()
throws java.lang.Exception
java.lang.Exceptionprivate byte[] getBlobTestData()
private byte[] getNewBlobTestData()
private java.lang.String getClobTestData()
private java.lang.String getNewClobTestData()
private boolean compare(byte[] b1,
byte[] b2)
public boolean compare(java.lang.String s1,
java.lang.String s2)
Strings.
public static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.Tds5Test
Test case to illustrate use of TDS 5 support.
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
Tds5Test(java.lang.String name)
|
|
| Method Summary | |
private boolean |
isVersion12orHigher()
|
private boolean |
isVersion15orHigher()
|
static void |
main(java.lang.String[] args)
|
static junit.framework.Test |
suite()
|
void |
testBigint()
Test Sybase ASE 15+ bigint data type. |
void |
testColMetaData()
Test the new column meta data made available in Sybase 12 |
void |
testDateTime()
Test the new date and time data types in Sybase 12+ |
void |
testImageText()
Test for bug [1161609] Text or image data truncated on Sybase 12.5 |
void |
testLongData()
Test varchar and varbinary fields longer than 255 bytes. |
void |
testNullUniText()
|
void |
testResultSetMetaData()
Test that resultset meta data is correct for short varchar/varbinary types. |
void |
testResultSetMetaData2()
Test that resultset meta data is correct for long varchar/varbinary types. |
void |
testResultSetMetaData3()
Test Sybase ASE misc data type metadata. |
void |
testResultSetMetaData4()
Test Sybase ASE 15+ misc data type metadata. |
void |
testStreamImage()
Test writing image data from InputStream |
void |
testStreamText()
Test writing text data from Reader |
void |
testStreamUniText()
Test writing unitext data from Reader |
void |
testUniText()
Test writing unitext data from memory |
void |
testUnsignedBigInt()
Test Sybase ASE 15+ unsigned bigint data type. |
void |
testUnsignedInt()
Test Sybase ASE 15+ unsigned int data type. |
void |
testUnsignedSmallInt()
Test Sybase ASE 15+ unsigned smallint data type. |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public Tds5Test(java.lang.String name)
| Method Detail |
public static junit.framework.Test suite()
public void testColMetaData()
throws java.lang.Exception
java.lang.Exception
public void testDateTime()
throws java.lang.Exception
java.lang.Exception
public void testLongData()
throws java.lang.Exception
java.lang.Exception
public void testImageText()
throws java.lang.Exception
java.lang.Exception
public void testStreamImage()
throws java.lang.Exception
java.lang.Exception
public void testStreamText()
throws java.lang.Exception
java.lang.Exception
public void testStreamUniText()
throws java.lang.Exception
java.lang.Exception
public void testUniText()
throws java.lang.Exception
java.lang.Exception
public void testNullUniText()
throws java.lang.Exception
java.lang.Exception
public void testBigint()
throws java.lang.Exception
java.lang.Exception
public void testUnsignedSmallInt()
throws java.lang.Exception
java.lang.Exception
public void testUnsignedInt()
throws java.lang.Exception
java.lang.Exception
public void testUnsignedBigInt()
throws java.lang.Exception
java.lang.Exception
public void testResultSetMetaData2()
throws java.lang.Exception
java.lang.Exception
public void testResultSetMetaData()
throws java.lang.Exception
java.lang.Exception
public void testResultSetMetaData3()
throws java.lang.Exception
java.lang.Exception
public void testResultSetMetaData4()
throws java.lang.Exception
java.lang.Exception
private boolean isVersion12orHigher()
throws java.lang.Exception
java.lang.Exception
private boolean isVersion15orHigher()
throws java.lang.Exception
java.lang.Exceptionpublic static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.CallableStatementJDBC3Test
Test the JDBC 3.0 features of CallableStatement.
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
CallableStatementJDBC3Test(java.lang.String name)
|
|
| Method Summary | |
static void |
main(java.lang.String[] args)
|
void |
testCallableRegisterOutParameter1()
Test for bug [946171] null boolean in CallableStatement bug |
void |
testCallableRegisterOutParameter2()
Test for bug [992715] wasnull() always returns false |
void |
testNamedParameters0001()
Test named parameters. |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public CallableStatementJDBC3Test(java.lang.String name)
| Method Detail |
public void testNamedParameters0001()
throws java.lang.Exception
java.lang.Exception
public void testCallableRegisterOutParameter1()
throws java.lang.Exception
java.lang.Exception
public void testCallableRegisterOutParameter2()
throws java.lang.Exception
java.lang.Exceptionpublic static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.UpdateTest
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
UpdateTest(java.lang.String name)
|
|
| Method Summary | |
static void |
main(java.lang.String[] args)
|
void |
testTemp()
|
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public UpdateTest(java.lang.String name)
| Method Detail |
public void testTemp()
throws java.lang.Exception
java.lang.Exceptionpublic static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.SavepointTest
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
SavepointTest(java.lang.String name)
|
|
| Method Summary | |
static void |
main(java.lang.String[] args)
|
void |
testSavepoint1()
tests if rolling back to a savepoint restores the correct DB state |
void |
testSavepoint2()
rollback zu einem savepoint, dann test, ob weiter mit dem safepoint-objekt gearbeitet werden kann |
void |
testSavepoint3()
|
void |
testSavepoint4()
Test to ensure savepoint ids restart at 1. |
void |
testSavepoint5()
Test to ensure savepoints can be created even when no statements have been issued. |
void |
testSavepoint6()
test for bug [2818256] ensure a savepoint is still valid after rollback |
void |
testSavepoint7()
roll back to one savepoint and ensure earlier savepoints are still valid |
void |
testSavepoint8()
Test to ensure savepoints cannot be created in auto-commit mode (Bug [2021839]). |
void |
testSavepoint9()
Test for bug [2021839], connection is rolled back instead of being committed if setSavepoint is the first operation. |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public SavepointTest(java.lang.String name)
| Method Detail |
public void testSavepoint1()
throws java.lang.Exception
java.lang.Exception
public void testSavepoint2()
throws java.lang.Exception
java.lang.Exception
public void testSavepoint3()
throws java.lang.Exception
java.lang.Exception
public void testSavepoint4()
throws java.lang.Exception
java.lang.Exception
public void testSavepoint5()
throws java.lang.Exception
java.lang.Exception
public void testSavepoint6()
throws java.lang.Exception
java.lang.Exception
public void testSavepoint7()
throws java.lang.Exception
java.lang.Exceptionpublic void testSavepoint8()
public void testSavepoint9()
throws java.lang.Exception
java.lang.Exceptionpublic static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.UnitTestBase
net.sourceforge.jtds.test.JtdsDataSourceUnitTest.Test_JtdsDataSource_getConnection
| Field Summary |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
JtdsDataSourceUnitTest.Test_JtdsDataSource_getConnection(java.lang.String name)
|
|
| Method Summary | |
static junit.framework.Test |
suite()
Provides a null test suite so that JUnit will not try to instantiate this class directly. |
void |
testDefaultTdsVersion()
Test connecting without specifying TDS version. |
void |
testNoHost()
Test connecting without specifying a host. |
void |
testNormal()
Test connecting with the settings in connection.properties. |
void |
testNoUser()
Test connecting without specifying a user. |
| Methods inherited from class net.sourceforge.jtds.test.UnitTestBase |
assertEquals, invokeConstructor, invokeGetInstanceField, invokeInstanceMethod, invokeSetInstanceField, invokeStaticMethod, ucFirst |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, setUp, tearDown, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public JtdsDataSourceUnitTest.Test_JtdsDataSource_getConnection(java.lang.String name)
| Method Detail |
public static final junit.framework.Test suite()
null).public void testNoHost()
public void testNoUser()
public void testNormal()
Should also test bug [1051595] jtdsDataSource connects only to localhost.
public void testDefaultTdsVersion()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.DatabaseTestCase
net.sourceforge.jtds.test.MetaDataTestCase
net.sourceforge.jtds.test.DatabaseMetaDataTypeInfoTest
Tests for DatabaseMetaData.getTypeInfo().
| Field Summary | |
private java.sql.ResultSet |
typeInfoRs
|
| Fields inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
|
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
DatabaseMetaDataTypeInfoTest(java.lang.String testName)
|
|
| Method Summary | |
private void |
checkOrder(java.util.List typeNames,
java.lang.String firstTypeName,
java.lang.String secondTypeName)
|
private java.util.List |
getTypeNamesInOrder()
|
static void |
main(java.lang.String[] args)
|
void |
setUp()
|
void |
tearDown()
|
void |
testColumnNames()
|
void |
testNvarcharNormalized()
|
void |
testOrderedByDatatype()
Check types ordered by data type. |
void |
testOrderedByTypeMapping()
Check that types with the same JDBC data type are ordered by closest match to the standard JDBC type. |
| Methods inherited from class net.sourceforge.jtds.test.MetaDataTestCase |
checkColumnNames |
| Methods inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
compareBytes, dropFunction, dropProcedure, dropProcedure, dropTable, getLongString, getLongString, getType, getTypemap |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
private java.sql.ResultSet typeInfoRs
| Constructor Detail |
public DatabaseMetaDataTypeInfoTest(java.lang.String testName)
| Method Detail |
public static void main(java.lang.String[] args)
public void setUp()
throws java.lang.Exception
public void tearDown()
throws java.lang.Exception
public void testOrderedByDatatype()
throws java.lang.Exception
java.lang.Exception
public void testOrderedByTypeMapping()
throws java.lang.Exception
java.lang.Exception
public void testColumnNames()
throws java.lang.Exception
java.lang.Exception
public void testNvarcharNormalized()
throws java.lang.Exception
java.lang.Exception
private void checkOrder(java.util.List typeNames,
java.lang.String firstTypeName,
java.lang.String secondTypeName)
private java.util.List getTypeNamesInOrder()
throws java.sql.SQLException
java.sql.SQLException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.StatementTest
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
StatementTest(java.lang.String name)
|
|
| Method Summary | |
static void |
main(java.lang.String[] args)
|
void |
testQueryTimeout()
Test for bug [1694194], queryTimeout does not work on MSSQL2005 when property 'useCursors' is set to 'true'. |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public StatementTest(java.lang.String name)
| Method Detail |
public void testQueryTimeout()
throws java.lang.Exception
This test requires property 'queryTimeout' to be set to true.
java.lang.Exceptionpublic static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.PreparedStatementTest
| Nested Class Summary | |
(package private) static class |
PreparedStatementTest.TestMultiThread
Inner class used by testMultiThread() to
test concurrency. |
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
PreparedStatementTest(java.lang.String name)
|
|
| Method Summary | |
static void |
main(java.lang.String[] args)
|
void |
testArithmeticOverflow()
Test for bug [1374127], Arithmetic overflow at sql_variant. |
void |
testBigDecBadParamSpec()
Test for bug [1094621] Decimal conversion error: A prepared statement with a decimal parameter that is -1E38 will fail as a result of the driver generating a parameter specification of decimal(38,10) rather than decimal(38,0). |
void |
testEscapedParams()
Test for parameter markers in function escapes. |
void |
testFloatValues()
Tests that float (single precision - 32 bit) values are not converted to double (thus loosing precision). |
void |
testIllegalParameters()
Test for bug [1111516 ] Illegal Parameters in PreparedStatement. |
void |
testLongStatement()
Test for bug [1022968] Long SQL expression error. |
void |
testManyParametersStatement()
Test for bug [1047330] prep statement with more than 2100 params fails. |
void |
testMaxRows()
Test for bug [1010660] 0.9-rc1 setMaxRows causes unlimited temp stored procedures. |
void |
testMetaData()
Test for bad truncation in prepared statements on metadata retrieval (patch [1076383] ResultSetMetaData for more complex statements for SQL Server). |
void |
testMetaDataClearsResultSet()
Test for bug [1050660] PreparedStatement.getMetaData() clears resultset. |
void |
testMissingWhitespace()
Test for bug [ 1059916 ] whitespace needed in preparedStatement. |
void |
testMultiByteCharTruncation()
Test for bug [2814376] varchar-type is truncated in non-unicode environment. |
void |
testMultiThread()
Test Connection concurrency by running
PreparedStatements and rollbacks at the same time to see
whether handles are not lost in the process. |
void |
testNegativeScale()
|
void |
testNoPrepare()
Test that statements which cannot be prepared are remembered. |
void |
testOuterJoinParameters()
Test for bug [1071397] Error in prepared statement (parameters in outer join escapes are not recognized). |
void |
testPreparedStatement()
|
void |
testPreparedStatementAddBatch1()
|
void |
testPreparedStatementParsing1()
Test for [924030] EscapeProcesser problem with "{}" brackets |
void |
testPreparedStatementParsing2()
Test for bug [1008882] Some queries with parameters cannot be executed with 0.9-rc1 |
void |
testPreparedStatementParsing3()
Test for "invalid parameter index" error. |
void |
testPreparedStatementRollback1()
Test for [931090] ArrayIndexOutOfBoundsException in rollback() |
void |
testPreparedStatementSetObject1()
Test for bug [938494] setObject(i, o, NUMERIC/DECIMAL) cuts off decimal places |
void |
testPreparedStatementSetObject2()
Test for bug [938494] setObject(i, o, NUMERIC/DECIMAL) cuts off decimal places |
void |
testPreparedStatementSetObject3()
Test for bug [938494] setObject(i, o, NUMERIC/DECIMAL) cuts off decimal places |
void |
testPreparedStatementSetObject4()
Test for bug [938494] setObject(i, o, NUMERIC/DECIMAL) cuts off decimal places |
void |
testPreparedStatementSetObject5()
Test for bug [938494] setObject(i, o, NUMERIC/DECIMAL) cuts off decimal places |
void |
testPreparedStatementSetObject6()
Test for bug [1204658] Conversion from Number to BigDecimal causes data corruption. |
void |
testPrepareFailWarning()
Test for bug [1180777] collation-related execption on update. |
void |
testPrepareModes()
Test that preparedstatement logic copes with commit modes and database changes. |
void |
testPrepareSQL0()
Test for bug [1623668] Lost apostrophes in statement parameter values(prepareSQL=0) |
void |
testScrollablePreparedStatement()
|
void |
testUpdateCount1()
Test for bug [985754] row count is always 0 |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public PreparedStatementTest(java.lang.String name)
| Method Detail |
public void testPreparedStatement()
throws java.lang.Exception
java.lang.Exception
public void testScrollablePreparedStatement()
throws java.lang.Exception
java.lang.Exception
public void testPreparedStatementAddBatch1()
throws java.lang.Exception
java.lang.Exception
public void testPreparedStatementParsing1()
throws java.lang.Exception
java.lang.Exception
public void testPreparedStatementParsing2()
throws java.lang.Exception
java.lang.Exception
public void testPreparedStatementParsing3()
throws java.lang.Exception
java.lang.Exception
public void testPreparedStatementRollback1()
throws java.lang.Exception
java.lang.Exception
public void testPreparedStatementSetObject1()
throws java.lang.Exception
java.lang.Exception
public void testPreparedStatementSetObject2()
throws java.lang.Exception
java.lang.Exception
public void testPreparedStatementSetObject3()
throws java.lang.Exception
java.lang.Exception
public void testPreparedStatementSetObject4()
throws java.lang.Exception
java.lang.Exception
public void testPreparedStatementSetObject5()
throws java.lang.Exception
java.lang.Exception
public void testPreparedStatementSetObject6()
throws java.lang.Exception
java.lang.Exception
public void testUpdateCount1()
throws java.lang.Exception
java.lang.Exception
public void testEscapedParams()
throws java.lang.Exception
java.lang.Exception
public void testMissingWhitespace()
throws java.lang.Exception
java.lang.Exception
public void testLongStatement()
throws java.lang.Exception
java.lang.Exception
public void testManyParametersStatement()
throws java.lang.Exception
java.lang.Exception
public void testMaxRows()
throws java.sql.SQLException
java.sql.SQLException
public void testMetaDataClearsResultSet()
throws java.lang.Exception
java.lang.Exception
public void testMetaData()
throws java.lang.Exception
java.lang.Exception
public void testOuterJoinParameters()
throws java.sql.SQLException
java.sql.SQLException
public void testMultiThread()
throws java.lang.Exception
Connection concurrency by running
PreparedStatements and rollbacks at the same time to see
whether handles are not lost in the process.
java.lang.Exception
public void testBigDecBadParamSpec()
throws java.lang.Exception
java.lang.Exception
public void testIllegalParameters()
throws java.lang.Exception
java.lang.Exception
public void testPrepareFailWarning()
throws java.sql.SQLException
java.sql.SQLException
public void testPrepareModes()
throws java.lang.Exception
java.lang.Exception
public void testNoPrepare()
throws java.lang.Exception
java.lang.Exception
public void testFloatValues()
throws java.lang.Exception
java.lang.Exception
public void testNegativeScale()
throws java.lang.Exception
java.lang.Exception
public void testPrepareSQL0()
throws java.lang.Exception
java.lang.Exception
public void testMultiByteCharTruncation()
throws java.lang.Exception
java.lang.Exception
public void testArithmeticOverflow()
throws java.lang.Exception
java.lang.Exceptionpublic static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjava.lang.Thread
net.sourceforge.jtds.test.BatchTest.ConcurrentBatchingHelper
Helper thread used by testConcurrentBatching() to execute a batch within a transaction that is
then rolled back. Starting a couple of these threads concurrently should show whether there are any race
conditions WRT preparation and execution in the batching implementation.
| Field Summary | |
private java.sql.Connection |
con
Connection on which to do the work. |
private java.util.Vector |
exceptions
Container to store any exceptions into. |
| Fields inherited from class java.lang.Thread |
MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY |
| Constructor Summary | |
(package private) |
BatchTest.ConcurrentBatchingHelper(java.sql.Connection con,
java.util.Vector exceptions)
|
| Method Summary | |
void |
run()
|
| Methods inherited from class java.lang.Thread |
activeCount, checkAccess, countStackFrames, currentThread, destroy, dumpStack, enumerate, getContextClassLoader, getName, getPriority, getThreadGroup, holdsLock, interrupt, interrupted, isAlive, isDaemon, isInterrupted, join, join, join, resume, setContextClassLoader, setDaemon, setName, setPriority, sleep, sleep, start, stop, stop, suspend, toString, yield |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
private java.sql.Connection con
private java.util.Vector exceptions
| Constructor Detail |
BatchTest.ConcurrentBatchingHelper(java.sql.Connection con,
java.util.Vector exceptions)
| Method Detail |
public void run()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.test.DefaultPropertiesTester
Abstract class used to test the default properties set on a variety of methods.
Implements the Command pattern.
| Constructor Summary | |
DefaultPropertiesTester()
|
|
| Method Summary | |
abstract void |
assertDefaultProperty(java.lang.String message,
java.lang.String url,
java.util.Properties properties,
java.lang.String fieldName,
java.lang.String key,
java.lang.String expected)
Asserts that a default property is set properly. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Constructor Detail |
public DefaultPropertiesTester()
| Method Detail |
public abstract void assertDefaultProperty(java.lang.String message,
java.lang.String url,
java.util.Properties properties,
java.lang.String fieldName,
java.lang.String key,
java.lang.String expected)
message - The message to display if the default property is not set.url - The JDBC url.properties - The initial properties set before testing the method.fieldName - The field name of the object if using reflection.key - The message key used to obtain the property name.expected - The expected value.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.UnitTestBase
net.sourceforge.jtds.test.MessagesPropertiesUnitTest
Unit tests for the Messages.properties file.
| Nested Class Summary | |
static class |
MessagesPropertiesUnitTest.TestDescriptionHasProperty
Tests that a given description key has a matching property key in Messages.properties. |
static class |
MessagesPropertiesUnitTest.TestPropertyHasDescription
Tests that a given property key has a matching description key in Messages.properties. |
| Field Summary |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
MessagesPropertiesUnitTest(java.lang.String name)
Constructor. |
|
| Method Summary | |
static junit.framework.Test |
suite()
Construct a test suite for this class. |
| Methods inherited from class net.sourceforge.jtds.test.UnitTestBase |
assertEquals, invokeConstructor, invokeGetInstanceField, invokeInstanceMethod, invokeSetInstanceField, invokeStaticMethod, ucFirst |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, setUp, tearDown, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public MessagesPropertiesUnitTest(java.lang.String name)
name - The name of the test.| Method Detail |
public static junit.framework.Test suite()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.DatabaseTestCase
net.sourceforge.jtds.test.AsTest
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
|
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
AsTest(java.lang.String name)
|
|
| Method Summary | |
private void |
checkTime(long time)
|
static void |
main(java.lang.String[] args)
|
void |
testBatch1()
|
void |
testBigDecimal()
|
void |
testBigInt()
|
void |
testBinary()
|
void |
testBoolean()
|
void |
testBug457955()
|
void |
testBugAttTest2()
|
void |
testProc1()
|
void |
testProc2()
|
void |
testSpecTime()
|
| Methods inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
compareBytes, dropFunction, dropProcedure, dropProcedure, dropTable, getLongString, getLongString, getType, getTypemap |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public AsTest(java.lang.String name)
| Method Detail |
public static void main(java.lang.String[] args)
public void testProc1()
throws java.lang.Exception
java.lang.Exception
public void testProc2()
throws java.lang.Exception
java.lang.Exception
public void testBatch1()
throws java.lang.Exception
java.lang.Exception
public void testBug457955()
throws java.lang.Exception
java.lang.Exception
public void testBugAttTest2()
throws java.lang.Exception
java.lang.Exception
public void testBigInt()
throws java.lang.Throwable
java.lang.Throwable
public void testBoolean()
throws java.lang.Throwable
java.lang.Throwable
public void testBinary()
throws java.lang.Throwable
java.lang.Throwable
private void checkTime(long time)
throws java.lang.Throwable
java.lang.Throwable
public void testSpecTime()
throws java.lang.Throwable
java.lang.Throwable
public void testBigDecimal()
throws java.lang.Throwable
java.lang.Throwable
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.ReadTextTest
Test case to illustrate use of READTEXT for text and image columns.
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
ReadTextTest(java.lang.String name)
|
|
| Method Summary | |
static void |
main(java.lang.String[] args)
|
void |
testReadText()
|
private void |
validateReadTextResult(java.sql.ResultSet rs,
java.lang.String data,
byte[] byteBuf)
|
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public ReadTextTest(java.lang.String name)
| Method Detail |
public void testReadText()
throws java.lang.Exception
java.lang.Exception
private void validateReadTextResult(java.sql.ResultSet rs,
java.lang.String data,
byte[] byteBuf)
throws java.lang.Exception
java.lang.Exceptionpublic static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.DatabaseTestCase
net.sourceforge.jtds.test.TlsTest
Test for SSL TLS.
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
|
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
TlsTest(java.lang.String name)
|
|
| Method Summary | |
static void |
main(java.lang.String[] args)
|
void |
testTLSResume()
Test for problem resuming TLS session with SQL Server (bug [1102505] SSL TLS resume failure). |
| Methods inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
compareBytes, dropFunction, dropProcedure, dropProcedure, dropTable, getLongString, getLongString, getType, getTypemap |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public TlsTest(java.lang.String name)
| Method Detail |
public void testTLSResume()
throws java.lang.Exception
java.lang.Exceptionpublic static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjava.lang.Thread
net.sourceforge.jtds.test.PreparedStatementTest.TestMultiThread
Inner class used by PreparedStatementTest.testMultiThread() to
test concurrency.
| Field Summary | |
(package private) static java.sql.Connection |
con
|
(package private) static java.lang.Exception |
error
|
(package private) static int |
live
|
(package private) static int |
LOOP_MAX
|
(package private) static int |
ROWS_MAX
|
(package private) static int |
THREAD_MAX
|
(package private) int |
threadId
|
| Fields inherited from class java.lang.Thread |
MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY |
| Constructor Summary | |
(package private) |
PreparedStatementTest.TestMultiThread(int n)
|
| Method Summary | |
void |
run()
|
(package private) static void |
startThreads(java.sql.Connection con)
|
| Methods inherited from class java.lang.Thread |
activeCount, checkAccess, countStackFrames, currentThread, destroy, dumpStack, enumerate, getContextClassLoader, getName, getPriority, getThreadGroup, holdsLock, interrupt, interrupted, isAlive, isDaemon, isInterrupted, join, join, join, resume, setContextClassLoader, setDaemon, setName, setPriority, sleep, sleep, start, stop, stop, suspend, toString, yield |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
static java.sql.Connection con
static final int THREAD_MAX
static final int LOOP_MAX
static final int ROWS_MAX
static int live
static java.lang.Exception error
int threadId
| Constructor Detail |
PreparedStatementTest.TestMultiThread(int n)
| Method Detail |
public void run()
static void startThreads(java.sql.Connection con)
throws java.lang.Exception
java.lang.Exception
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.DatabaseTestCase
net.sourceforge.jtds.test.TimestampTest
test getting timestamps from the database.
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
|
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
TimestampTest(java.lang.String name)
|
|
| Method Summary | |
(package private) java.lang.Object[][] |
getDatatypes()
|
long |
getTimeInMs(java.sql.ResultSet rs)
Java 1.3 Timestamp.getDate() does not add the nano seconds to the millisecond value returned. |
static void |
main(java.lang.String[] args)
|
void |
test1899Date()
Test for bug [1234531] Dates before 01/01/1900 broken due to DateTime value markers. |
void |
testBigint0000()
|
void |
testBlob0021()
|
void |
testConnection0038()
|
void |
testConnection0039()
|
void |
testDateTimeDegeneration()
Test for bug [2508201], date field is changed by 3 milliseconds. |
void |
testDatetimeRounding1()
Test for bug [994916] datetime decoding in TdsData.java |
void |
testDatetimeRounding10()
Test for bug [994916] datetime decoding in TdsData.java |
void |
testDatetimeRounding2()
Test for bug [994916] datetime decoding in TdsData.java |
void |
testDatetimeRounding3()
Test for bug [994916] datetime decoding in TdsData.java |
void |
testDatetimeRounding4()
Test for bug [994916] datetime decoding in TdsData.java |
void |
testDatetimeRounding5()
Test for bug [994916] datetime decoding in TdsData.java |
void |
testDatetimeRounding6()
Test for bug [994916] datetime decoding in TdsData.java |
void |
testDatetimeRounding7()
Test for bug [994916] datetime decoding in TdsData.java |
void |
testDatetimeRounding8()
Test for bug [994916] datetime decoding in TdsData.java |
void |
testDatetimeRounding9()
Test for bug [994916] datetime decoding in TdsData.java |
void |
testDayOfWeek()
Test for bug [1226210] {fn dayofweek()} depends on the language. |
void |
testDecimalConversion0058()
|
void |
testEmptyResults0011()
|
void |
testEmptyResults0012()
|
void |
testEmptyResults0013()
|
void |
testEra()
Test for bugs [2181003]/[2349058], an attempt to set a BC date invalidates driver state/DateTime allows invalid dates through. |
void |
testErrors0036()
|
void |
testEscape(java.lang.String sql,
java.lang.String expected)
|
void |
testEscapes0006()
|
void |
testEscaping()
|
void |
testForBrowse0014()
|
void |
testGetBoolean0025()
|
void |
testGetString()
Test for bug [1235845] getTimestamp() returns illegal value after getString(). |
void |
testMetaData0046()
|
void |
testMissingParameter0016()
|
void |
testMultipleResults0015()
|
void |
testNestedStatements0022()
|
void |
testNestedStatements0026()
SAfe Tests whether cursor-based statements still work ok when nested. |
void |
testOutputParams()
|
void |
testPreparedStatement0007()
|
void |
testPreparedStatement0008()
|
void |
testPreparedStatement0009()
|
void |
testPreparedStatement0040()
|
void |
testPreparedStatement0041()
|
void |
testPreparedStatement0042()
|
void |
testPrimaryKeyFloat0023()
|
void |
testPrimaryKeyReal0024()
|
void |
testResultSet0043()
|
void |
testResultSet0044()
|
void |
testResultSet0045()
|
void |
testStatements0020()
|
void |
testTimestampRange()
Test for bug [1040475] Possible bug when converting to and from datetime. |
void |
testTimestamps0001()
|
void |
testTimestamps0004()
|
void |
testTimestamps0037()
|
void |
testTimestamps0047()
|
void |
testTimestamps0048()
|
void |
testTimestampTimeZone()
Test for bug [1036059] getTimestamp with Calendar applies tzone offset wrong way. |
void |
testTransactions0010()
|
void |
testWriteDate()
Test that java.sql.Date objects are inserted and retrieved
correctly (ie no time component). |
| Methods inherited from class net.sourceforge.jtds.test.DatabaseTestCase |
compareBytes, dropFunction, dropProcedure, dropProcedure, dropTable, getLongString, getLongString, getType, getTypemap |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public TimestampTest(java.lang.String name)
| Method Detail |
public static void main(java.lang.String[] args)
public void testBigint0000()
throws java.lang.Exception
java.lang.Exception
public void testTimestamps0001()
throws java.lang.Exception
java.lang.Exception
public void testTimestamps0004()
throws java.lang.Exception
java.lang.Exception
public void testEscape(java.lang.String sql,
java.lang.String expected)
throws java.lang.Exception
java.lang.Exception
public void testEscapes0006()
throws java.lang.Exception
java.lang.Exception
public void testPreparedStatement0007()
throws java.lang.Exception
java.lang.Exception
public void testPreparedStatement0008()
throws java.lang.Exception
java.lang.Exception
public void testPreparedStatement0009()
throws java.lang.Exception
java.lang.Exception
public void testTransactions0010()
throws java.lang.Exception
java.lang.Exception
public void testEmptyResults0011()
throws java.lang.Exception
java.lang.Exception
public void testEmptyResults0012()
throws java.lang.Exception
java.lang.Exception
public void testEmptyResults0013()
throws java.lang.Exception
java.lang.Exception
public void testForBrowse0014()
throws java.lang.Exception
java.lang.Exception
public void testMultipleResults0015()
throws java.lang.Exception
java.lang.Exception
public void testMissingParameter0016()
throws java.lang.Exception
java.lang.Exceptionjava.lang.Object[][] getDatatypes()
public void testOutputParams()
throws java.lang.Exception
java.lang.Exception
public void testStatements0020()
throws java.lang.Exception
java.lang.Exception
public void testBlob0021()
throws java.lang.Exception
java.lang.Exception
public void testNestedStatements0022()
throws java.lang.Exception
java.lang.Exception
public void testPrimaryKeyFloat0023()
throws java.lang.Exception
java.lang.Exception
public void testPrimaryKeyReal0024()
throws java.lang.Exception
java.lang.Exception
public void testGetBoolean0025()
throws java.lang.Exception
java.lang.Exception
public void testNestedStatements0026()
throws java.lang.Exception
testNestedStatements0022, which tests
the same with plain (non-cursor-based) statements (and unfortunately
fails).
java.lang.Exception - if an Exception occurs (very relevant, huh?)
public void testErrors0036()
throws java.lang.Exception
java.lang.Exception
public void testTimestamps0037()
throws java.lang.Exception
java.lang.Exception
public void testConnection0038()
throws java.lang.Exception
java.lang.Exception
public void testConnection0039()
throws java.lang.Exception
java.lang.Exception
public void testPreparedStatement0040()
throws java.lang.Exception
java.lang.Exception
public void testPreparedStatement0041()
throws java.lang.Exception
java.lang.Exception
public void testPreparedStatement0042()
throws java.lang.Exception
java.lang.Exception
public void testResultSet0043()
throws java.lang.Exception
java.lang.Exception
public void testResultSet0044()
throws java.lang.Exception
java.lang.Exception
public void testResultSet0045()
throws java.lang.Exception
java.lang.Exception
public void testMetaData0046()
throws java.lang.Exception
java.lang.Exception
public void testTimestamps0047()
throws java.lang.Exception
java.lang.Exception
public void testTimestamps0048()
throws java.lang.Exception
java.lang.Exception
public void testDecimalConversion0058()
throws java.lang.Exception
java.lang.Exception
public void testDatetimeRounding1()
throws java.lang.Exception
java.lang.Exception
public void testDatetimeRounding2()
throws java.lang.Exception
java.lang.Exception
public void testDatetimeRounding3()
throws java.lang.Exception
java.lang.Exception
public void testDatetimeRounding4()
throws java.lang.Exception
java.lang.Exception
public void testDatetimeRounding5()
throws java.lang.Exception
java.lang.Exception
public void testDatetimeRounding6()
throws java.lang.Exception
java.lang.Exception
public void testDatetimeRounding7()
throws java.lang.Exception
java.lang.Exception
public void testDatetimeRounding8()
throws java.lang.Exception
java.lang.Exception
public void testDatetimeRounding9()
throws java.lang.Exception
java.lang.Exception
public void testDatetimeRounding10()
throws java.lang.Exception
java.lang.Exception
public void testTimestampTimeZone()
throws java.sql.SQLException
java.sql.SQLException
public void testTimestampRange()
throws java.sql.SQLException
jTDS seems to accept dates outside the range accepted by SQL Server (i.e. 1753-9999).
java.sql.SQLException
public void testWriteDate()
throws java.sql.SQLException
java.sql.Date objects are inserted and retrieved
correctly (ie no time component).
java.sql.SQLException
public void testDayOfWeek()
throws java.lang.Exception
java.lang.Exception
public void testGetString()
throws java.sql.SQLException
java.sql.SQLException
public void test1899Date()
throws java.lang.Exception
java.lang.Exception
public long getTimeInMs(java.sql.ResultSet rs)
throws java.sql.SQLException
rs - the result set returning the Timstamp value in column 1
long.
java.sql.SQLException
public void testDateTimeDegeneration()
throws java.lang.Exception
java.lang.Exception
public void testEscaping()
throws java.sql.SQLException
java.sql.SQLException
public void testEra()
throws java.sql.SQLException
java.sql.SQLException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.UnitTestBase
net.sourceforge.jtds.test.NamedPipeUnitTest
Unit tests for the SharedNamedPipe class.
| Field Summary |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
NamedPipeUnitTest(java.lang.String name)
Constructor. |
|
| Method Summary | |
private int |
invoke_calculateBufferSize(int tdsVersion,
int packetSize)
Helper method to invoke Support.calculateNamedPipeBufferSize(int, int)
using reflection. |
void |
testCalculateBufferSize_TDS42()
Test that Support.calculateNamedPipeBufferSize(int, int)
sets the buffer size appropriately for TDS 4.2 when the packet
size is set to 0. |
void |
testCalculateBufferSize_TDS50()
Test that Support.calculateNamedPipeBufferSize(int, int)
sets the buffer size appropriately for TDS 5.0 when the packet
size is set to 0. |
void |
testCalculateBufferSize_TDS70()
Test that Support.calculateNamedPipeBufferSize(int, int)
sets the buffer size appropriately for TDS 7.0 when the packet
size is set to 0. |
void |
testCalculateBufferSize_TDS80()
Test that Support.calculateNamedPipeBufferSize(int, int)
sets the buffer size appropriately for TDS 8.0 when the packet
size is set to 0. |
| Methods inherited from class net.sourceforge.jtds.test.UnitTestBase |
assertEquals, invokeConstructor, invokeGetInstanceField, invokeInstanceMethod, invokeSetInstanceField, invokeStaticMethod, ucFirst |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, setUp, tearDown, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public NamedPipeUnitTest(java.lang.String name)
name - The name of the test.| Method Detail |
public void testCalculateBufferSize_TDS42()
Support.calculateNamedPipeBufferSize(int, int)
sets the buffer size appropriately for TDS 4.2 when the packet
size is set to 0.
public void testCalculateBufferSize_TDS50()
Support.calculateNamedPipeBufferSize(int, int)
sets the buffer size appropriately for TDS 5.0 when the packet
size is set to 0.
public void testCalculateBufferSize_TDS70()
Support.calculateNamedPipeBufferSize(int, int)
sets the buffer size appropriately for TDS 7.0 when the packet
size is set to 0.
public void testCalculateBufferSize_TDS80()
Support.calculateNamedPipeBufferSize(int, int)
sets the buffer size appropriately for TDS 8.0 when the packet
size is set to 0.
private int invoke_calculateBufferSize(int tdsVersion,
int packetSize)
Support.calculateNamedPipeBufferSize(int, int)
using reflection.
tdsVersion - The TDS version as an int.packetSize - The packet size as an int.
Support.calculateNamedPipeBufferSize(int, int).
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjunit.framework.Assert
junit.framework.TestCase
net.sourceforge.jtds.test.TestBase
net.sourceforge.jtds.test.GenKeyTest
Test case to illustrate JDBC 3 GetGeneratedKeys() function.
| Field Summary |
| Fields inherited from class net.sourceforge.jtds.test.TestBase |
con, props |
| Fields inherited from class junit.framework.TestCase |
|
| Constructor Summary | |
GenKeyTest(java.lang.String name)
|
|
| Method Summary | |
static void |
main(java.lang.String[] args)
|
void |
testNoKeys()
Test empty result set returned when no keys available. |
void |
testParams()
|
void |
testSelect()
Test that SELECT statements work correctly with PreparedStatements created with
RETURN_GENERATED_KEYS. |
void |
testTrigger1()
Test for bug [930305] getGeneratedKeys() does not work with triggers |
| Methods inherited from class net.sourceforge.jtds.test.TestBase |
compareInputStreams, compareReaders, connect, dump, dumpRow, getConnection, getConnection, makeObjects, makeTestTables, setUp, tearDown |
| Methods inherited from class junit.framework.TestCase |
countTestCases, createResult, getName, run, run, runBare, runTest, setName, toString |
| Methods inherited from class junit.framework.Assert |
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
public GenKeyTest(java.lang.String name)
| Method Detail |
public void testParams()
throws java.lang.Exception
java.lang.Exception
public void testTrigger1()
throws java.lang.Exception
java.lang.Exception
public void testNoKeys()
throws java.lang.Exception
java.lang.Exception
public void testSelect()
throws java.sql.SQLException
PreparedStatements created with
RETURN_GENERATED_KEYS.
java.sql.SQLExceptionpublic static void main(java.lang.String[] args)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.util.Logger
Class providing static methods to log diagnostics.
There are three ways to enable logging:
| Field Summary | |
private static char[] |
hex
|
private static java.io.PrintWriter |
log
PrintWriter stream set by DataSource. |
| Constructor Summary | |
Logger()
|
|
| Method Summary | |
static java.io.PrintWriter |
getLogWriter()
Get the logging PrintWriter Stream. |
static boolean |
isActive()
Retrieve the active status of the logger. |
static void |
logException(java.lang.Exception e)
Print an Exception stack trace to the log. |
static void |
logPacket(int streamId,
boolean in,
byte[] pkt)
Print a dump of the current input or output network packet. |
static void |
println(java.lang.String message)
Print a diagnostic message to the output stream provided by the DataSource or the DriverManager. |
static void |
setActive(boolean value)
Deprecated. Use the JDBC standard mechanisms to enable logging. |
static void |
setLogWriter(java.io.PrintWriter out)
Set the logging PrintWriter stream. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private static java.io.PrintWriter log
private static final char[] hex
| Constructor Detail |
public Logger()
| Method Detail |
public static void setLogWriter(java.io.PrintWriter out)
out - the PrintWriter streampublic static java.io.PrintWriter getLogWriter()
PrintWriterpublic static boolean isActive()
boolean true if logging enabledpublic static void println(java.lang.String message)
message - the diagnostic message to print
public static void logPacket(int streamId,
boolean in,
byte[] pkt)
streamId - the owner of this packetin - true if this is an input packetpkt - the packet datapublic static void logException(java.lang.Exception e)
e - the exception to logpublic static void setActive(boolean value)
value - true to turn on logging
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.util.GeneralDigest
net.sourceforge.jtds.util.MD5Digest
implementation of MD5 as outlined in "Handbook of Applied Cryptography", pages 346 - 347.
| Field Summary | |
private static int |
DIGEST_LENGTH
|
private int |
H1
|
private int |
H2
|
private int |
H3
|
private int |
H4
|
private static int |
S11
|
private static int |
S12
|
private static int |
S13
|
private static int |
S14
|
private static int |
S21
|
private static int |
S22
|
private static int |
S23
|
private static int |
S24
|
private static int |
S31
|
private static int |
S32
|
private static int |
S33
|
private static int |
S34
|
private static int |
S41
|
private static int |
S42
|
private static int |
S43
|
private static int |
S44
|
private int[] |
X
|
private int |
xOff
|
| Fields inherited from class net.sourceforge.jtds.util.GeneralDigest |
|
| Constructor Summary | |
MD5Digest()
Standard constructor |
|
MD5Digest(MD5Digest t)
Copy constructor. |
|
| Method Summary | |
int |
doFinal(byte[] out,
int outOff)
|
private int |
F(int u,
int v,
int w)
|
private int |
G(int u,
int v,
int w)
|
java.lang.String |
getAlgorithmName()
|
int |
getDigestSize()
|
private int |
H(int u,
int v,
int w)
|
private int |
K(int u,
int v,
int w)
|
protected void |
processBlock()
|
protected void |
processLength(long bitLength)
|
protected void |
processWord(byte[] in,
int inOff)
|
void |
reset()
reset the chaining variables to the IV values. |
private int |
rotateLeft(int x,
int n)
|
private void |
unpackWord(int word,
byte[] out,
int outOff)
|
| Methods inherited from class net.sourceforge.jtds.util.GeneralDigest |
finish, update, update |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private static final int DIGEST_LENGTH
private int H1
private int H2
private int H3
private int H4
private int[] X
private int xOff
private static final int S11
private static final int S12
private static final int S13
private static final int S14
private static final int S21
private static final int S22
private static final int S23
private static final int S24
private static final int S31
private static final int S32
private static final int S33
private static final int S34
private static final int S41
private static final int S42
private static final int S43
private static final int S44
| Constructor Detail |
public MD5Digest()
public MD5Digest(MD5Digest t)
| Method Detail |
public java.lang.String getAlgorithmName()
public int getDigestSize()
protected void processWord(byte[] in,
int inOff)
processWord in class GeneralDigestprotected void processLength(long bitLength)
processLength in class GeneralDigest
private void unpackWord(int word,
byte[] out,
int outOff)
public int doFinal(byte[] out,
int outOff)
public void reset()
reset in class GeneralDigest
private int rotateLeft(int x,
int n)
private int F(int u,
int v,
int w)
private int G(int u,
int v,
int w)
private int H(int u,
int v,
int w)
private int K(int u,
int v,
int w)
protected void processBlock()
processBlock in class GeneralDigest
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjava.io.OutputStream
net.sourceforge.jtds.util.BlobBuffer.AsciiOutputStream
Implements an ASCII OutputStream for CLOB data.
| Field Summary | |
private boolean |
open
|
private int |
writePtr
|
| Constructor Summary | |
(package private) |
BlobBuffer.AsciiOutputStream(long pos)
Costructs an ASCII OutputStream object over the BLOB
buffer. |
| Method Summary | |
void |
close()
Closes the output stream. |
protected void |
finalize()
Ensures underlying BLOB file can be closed even if user does not close this stream. |
void |
write(int b)
Writes a byte to the BLOB buffer. |
| Methods inherited from class java.io.OutputStream |
flush, write, write |
| Methods inherited from class java.lang.Object |
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private int writePtr
private boolean open
| Constructor Detail |
BlobBuffer.AsciiOutputStream(long pos)
throws java.io.IOException
OutputStream object over the BLOB
buffer.
pos - the starting position (from 0)
java.io.IOException - if an I/O error occurs| Method Detail |
protected void finalize()
throws java.lang.Throwable
java.lang.Throwable
public void write(int b)
throws java.io.IOException
b - the byte value to write
java.io.IOException - if an I/O error occurs
public void close()
throws java.io.IOException
java.io.IOException - if an I/O error occurs
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use MD5Digest | |
| net.sourceforge.jtds.util | |
| Uses of MD5Digest in net.sourceforge.jtds.util |
| Constructors in net.sourceforge.jtds.util with parameters of type MD5Digest | |
MD5Digest(MD5Digest t)
Copy constructor. |
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use SSPIJNIClient | |
| net.sourceforge.jtds.jdbc | |
| net.sourceforge.jtds.util | |
| Uses of SSPIJNIClient in net.sourceforge.jtds.jdbc |
| Fields in net.sourceforge.jtds.jdbc declared as SSPIJNIClient | |
private static SSPIJNIClient |
TdsCore.sspiJNIClient
A reference to ntlm.SSPIJNIClient. |
| Uses of SSPIJNIClient in net.sourceforge.jtds.util |
| Fields in net.sourceforge.jtds.util declared as SSPIJNIClient | |
private static SSPIJNIClient |
SSPIJNIClient.thisInstance
Singleton instance. |
| Methods in net.sourceforge.jtds.util that return SSPIJNIClient | |
static SSPIJNIClient |
SSPIJNIClient.getInstance()
Returns the singleton SSPIJNIClient instance. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use TimerThread | |
| net.sourceforge.jtds.util | |
| Uses of TimerThread in net.sourceforge.jtds.util |
| Fields in net.sourceforge.jtds.util declared as TimerThread | |
private static TimerThread |
TimerThread.instance
Singleton instance. |
| Methods in net.sourceforge.jtds.util that return TimerThread | |
static TimerThread |
TimerThread.getInstance()
Singleton getter. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use MD4Digest | |
| net.sourceforge.jtds.util | |
| Uses of MD4Digest in net.sourceforge.jtds.util |
| Constructors in net.sourceforge.jtds.util with parameters of type MD4Digest | |
MD4Digest(MD4Digest t)
Copy constructor. |
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use BlobBuffer | |
| net.sourceforge.jtds.jdbc | |
| Uses of BlobBuffer in net.sourceforge.jtds.jdbc |
| Fields in net.sourceforge.jtds.jdbc declared as BlobBuffer | |
private BlobBuffer |
ClobImpl.blobBuffer
The underlying BlobBuffer. |
private BlobBuffer |
BlobImpl.blobBuffer
The underlying BlobBuffer. |
| Methods in net.sourceforge.jtds.jdbc that return BlobBuffer | |
(package private) BlobBuffer |
ClobImpl.getBlobBuffer()
Obtain this object's backing BlobBuffer object. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use TimerThread.TimerListener | |
| net.sourceforge.jtds.util | |
| Uses of TimerThread.TimerListener in net.sourceforge.jtds.util |
| Fields in net.sourceforge.jtds.util declared as TimerThread.TimerListener | |
(package private) TimerThread.TimerListener |
TimerThread.TimerRequest.target
Target to notify when the timeout expires. |
| Methods in net.sourceforge.jtds.util with parameters of type TimerThread.TimerListener | |
java.lang.Object |
TimerThread.setTimer(int timeout,
TimerThread.TimerListener l)
Add a timer request to the queue. |
| Constructors in net.sourceforge.jtds.util with parameters of type TimerThread.TimerListener | |
TimerThread.TimerRequest(int timeout,
TimerThread.TimerListener target)
Create a TimerRequest. |
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use GeneralDigest | |
| net.sourceforge.jtds.util | |
| Uses of GeneralDigest in net.sourceforge.jtds.util |
| Subclasses of GeneralDigest in net.sourceforge.jtds.util | |
class |
MD4Digest
implementation of MD4 as RFC 1320 by R. |
class |
MD5Digest
implementation of MD5 as outlined in "Handbook of Applied Cryptography", pages 346 - 347. |
| Constructors in net.sourceforge.jtds.util with parameters of type GeneralDigest | |
GeneralDigest(GeneralDigest t)
Copy constructor. |
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjava.io.InputStream
net.sourceforge.jtds.util.BlobBuffer.UnicodeInputStream
A Big Endian Unicode InputStream over the CLOB buffer.
| Field Summary | |
private boolean |
open
|
private int |
readPtr
|
| Fields inherited from class java.io.InputStream |
|
| Constructor Summary | |
BlobBuffer.UnicodeInputStream(long pos)
Costructs an InputStream object over the BLOB buffer. |
|
| Method Summary | |
int |
available()
Returns the number of bytes available to read. |
void |
close()
Close the output stream. |
protected void |
finalize()
Ensures underlying BLOB file can be closed even if user does not close this stream. |
int |
read()
Reads the next byte from the stream. |
| Methods inherited from class java.io.InputStream |
mark, markSupported, read, read, reset, skip |
| Methods inherited from class java.lang.Object |
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private int readPtr
private boolean open
| Constructor Detail |
public BlobBuffer.UnicodeInputStream(long pos)
throws java.io.IOException
pos - the starting position (from 0)
java.io.IOException - if an I/O error occurs| Method Detail |
protected void finalize()
throws java.lang.Throwable
java.lang.Throwable
public int available()
throws java.io.IOException
java.io.IOException - if an I/O error occurs
public int read()
throws java.io.IOException
int or -1 if at EOF
java.io.IOException - if an I/O error occurs
public void close()
throws java.io.IOException
java.io.IOException - if an I/O error occurs
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.util.SSPIJNIClient
A JNI client to SSPI based CPP program (DLL) that returns the user credentials for NTLM authentication.
The DLL name is ntlmauth.dll.
| Field Summary | |
private boolean |
initialized
SSPI client initialized flag. |
private static boolean |
libraryLoaded
SSPI native library loaded flag. |
private static SSPIJNIClient |
thisInstance
Singleton instance. |
| Constructor Summary | |
private |
SSPIJNIClient()
Private constructor for singleton. |
| Method Summary | |
static SSPIJNIClient |
getInstance()
Returns the singleton SSPIJNIClient instance. |
private void |
initialize()
Initializes the SSPI client. |
void |
invokeInitialize()
Calls #initialize() if the SSPI client is not already inited. |
byte[] |
invokePrepareSSORequest()
Calls #prepareSSORequest() to prepare the NTLM TYPE-1 message. |
byte[] |
invokePrepareSSOSubmit(byte[] buf)
Calls #prepareSSOSubmit(byte[], long) to prepare the NTLM TYPE-3
message. |
void |
invokeUnInitialize()
Calls #unInitialize() if the SSPI client is inited. |
private byte[] |
prepareSSORequest()
Prepares the NTLM TYPE-1 message and returns it as a byte[]. |
private byte[] |
prepareSSOSubmit(byte[] buf,
long size)
Prepares the NTLM TYPE-3 message using the current user's credentials. |
private void |
unInitialize()
Uninitializes the SSPI client. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private static SSPIJNIClient thisInstance
private static boolean libraryLoaded
private boolean initialized
| Constructor Detail |
private SSPIJNIClient()
| Method Detail |
private void initialize()
private void unInitialize()
private byte[] prepareSSORequest()
byte[].
private byte[] prepareSSOSubmit(byte[] buf,
long size)
It needs the challenge BLOB and it's size as input. The challenge BLOB is nothig but the TYPE-2 message that is received from the SQL Server.
buf - challenge BLOBsize - challenge BLOB size
public static SSPIJNIClient getInstance() throws java.lang.Exception
SSPIJNIClient instance.
java.sql.SQLException - if an error occurs during initialization
java.lang.Exceptionpublic void invokeInitialize()
#initialize() if the SSPI client is not already inited.
public void invokeUnInitialize()
#unInitialize() if the SSPI client is inited.
public byte[] invokePrepareSSORequest()
throws java.lang.Exception
#prepareSSORequest() to prepare the NTLM TYPE-1 message.
java.lang.Exception - if an error occurs during the call or the SSPI client
is uninitialized
public byte[] invokePrepareSSOSubmit(byte[] buf)
throws java.lang.Exception
#prepareSSOSubmit(byte[], long) to prepare the NTLM TYPE-3
message.
java.lang.Exception - if an error occurs during the call or the SSPI client
is uninitialized
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjava.lang.Thread
net.sourceforge.jtds.util.TimerThread
Simple timer class used to implement login and query timeouts.
This thread runs as a Daemon thread to ensure that the java VM will exit correctly when normal execution is complete. It provides both a singleton implementation and a default constructor for the case when more than one timer thread is desired.
| Nested Class Summary | |
static interface |
TimerThread.TimerListener
Interface to be implemented by classes that request timer services. |
private static class |
TimerThread.TimerRequest
Internal class associating a login or query timeout value with a target TimerListener. |
| Field Summary | |
private static TimerThread |
instance
Singleton instance. |
private long |
nextTimeout
Time when the first request time out should occur. |
private java.util.LinkedList |
timerList
List of TimerRequests to execute, ordered by time. |
| Fields inherited from class java.lang.Thread |
MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY |
| Constructor Summary | |
TimerThread()
Construct a new TimerThread instance. |
|
| Method Summary | |
boolean |
cancelTimer(java.lang.Object handle)
Remove a redundant timer before it expires. |
static TimerThread |
getInstance()
Singleton getter. |
boolean |
hasExpired(java.lang.Object handle)
Check whether a timer has expired. |
void |
run()
Execute the TimerThread main loop. |
java.lang.Object |
setTimer(int timeout,
TimerThread.TimerListener l)
Add a timer request to the queue. |
void |
stopTimer()
Completely stops the timer and its underlying Java thread, discarding all pending timeouts. |
private void |
updateNextTimeout()
Internal method that updates the value of nextTimeout. |
| Methods inherited from class java.lang.Thread |
activeCount, checkAccess, countStackFrames, currentThread, destroy, dumpStack, enumerate, getContextClassLoader, getName, getPriority, getThreadGroup, holdsLock, interrupt, interrupted, isAlive, isDaemon, isInterrupted, join, join, join, resume, setContextClassLoader, setDaemon, setName, setPriority, sleep, sleep, start, stop, stop, suspend, toString, yield |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
private static TimerThread instance
private final java.util.LinkedList timerList
TimerRequests to execute, ordered by time.
private long nextTimeout
| Constructor Detail |
public TimerThread()
TimerThread instance.
| Method Detail |
public static TimerThread getInstance()
public void run()
TimerThread main loop.
public java.lang.Object setTimer(int timeout,
TimerThread.TimerListener l)
timeout - the interval in milliseconds after which the timer will
expirel - TimerListener to be notified on timeout
cancelTimerpublic boolean cancelTimer(java.lang.Object handle)
handle - handle to the request to be removed from the queue (a
TimerRequest instance)
true if timer had not expiredpublic void stopTimer()
getInstance()
will restart the timer.
public boolean hasExpired(java.lang.Object handle)
handle - handle to the request to be checked for expiry (a
TimerRequest instance)
true if timer has expiredprivate void updateNextTimeout()
nextTimeout.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV PACKAGE NEXT PACKAGE | FRAMES NO FRAMES | ||||||||||
| Interface Summary | |
| TimerThread.TimerListener | Interface to be implemented by classes that request timer services. |
| Class Summary | |
| BlobBuffer | Manages a buffer (backed by optional disk storage) for use as a data store by the CLOB and BLOB objects. |
| DESEngine | a class that provides a basic DES engine. |
| GeneralDigest | base implementation of MD4 family style digest as outlined in "Handbook of Applied Cryptography", pages 344 - 347. |
| Logger | Class providing static methods to log diagnostics. |
| MD4Digest | implementation of MD4 as RFC 1320 by R. |
| MD5Digest | implementation of MD5 as outlined in "Handbook of Applied Cryptography", pages 346 - 347. |
| SSPIJNIClient | A JNI client to SSPI based CPP program (DLL) that returns the user credentials for NTLM authentication. |
| TimerThread | Simple timer class used to implement login and query timeouts. |
| TimerThread.TimerRequest | Internal class associating a login or query timeout value with a target
TimerListener. |
|
|||||||||||
| PREV PACKAGE NEXT PACKAGE | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.util.TimerThread.TimerRequest
Internal class associating a login or query timeout value with a target
TimerListener.
| Field Summary | |
(package private) TimerThread.TimerListener |
target
Target to notify when the timeout expires. |
(package private) long |
time
The time when this timeout will expire. |
| Constructor Summary | |
(package private) |
TimerThread.TimerRequest(int timeout,
TimerThread.TimerListener target)
Create a TimerRequest. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
final long time
final TimerThread.TimerListener target
| Constructor Detail |
TimerThread.TimerRequest(int timeout,
TimerThread.TimerListener target)
TimerRequest.
timeout - the desired timeout in millisecondstarget - the target object; one of SharedSocket or
TdsCore
java.lang.IllegalArgumentException - if the timeout is negative or 0
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjava.io.InputStream
net.sourceforge.jtds.util.BlobBuffer.AsciiInputStream
An ASCII InputStream over the CLOB buffer.
| Field Summary | |
private boolean |
open
|
private int |
readPtr
|
| Fields inherited from class java.io.InputStream |
|
| Constructor Summary | |
BlobBuffer.AsciiInputStream(long pos)
Costructs an InputStream object over the BLOB buffer. |
|
| Method Summary | |
int |
available()
Returns the number of bytes available to read. |
void |
close()
Closes the output stream. |
protected void |
finalize()
Ensures underlying BLOB file can be closed even if user does not close this stream. |
int |
read()
Read the next byte from the stream. |
| Methods inherited from class java.io.InputStream |
mark, markSupported, read, read, reset, skip |
| Methods inherited from class java.lang.Object |
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private int readPtr
private boolean open
| Constructor Detail |
public BlobBuffer.AsciiInputStream(long pos)
throws java.io.IOException
pos - the starting position (from 0)
java.io.IOException - if an I/O error occurs| Method Detail |
protected void finalize()
throws java.lang.Throwable
java.lang.Throwable
public int available()
throws java.io.IOException
java.io.IOException - if an I/O error occurs
public int read()
throws java.io.IOException
int or -1 if at EOF
java.io.IOException - if an I/O error occurs
public void close()
throws java.io.IOException
java.io.IOException - if an I/O error occurs
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use net.sourceforge.jtds.util | |
| net.sourceforge.jtds.jdbc | |
| net.sourceforge.jtds.util | |
| Classes in net.sourceforge.jtds.util used by net.sourceforge.jtds.jdbc | |
| BlobBuffer
Manages a buffer (backed by optional disk storage) for use as a data store by the CLOB and BLOB objects. |
|
| SSPIJNIClient
A JNI client to SSPI based CPP program (DLL) that returns the user credentials for NTLM authentication. |
|
| Classes in net.sourceforge.jtds.util used by net.sourceforge.jtds.util | |
| GeneralDigest
base implementation of MD4 family style digest as outlined in "Handbook of Applied Cryptography", pages 344 - 347. |
|
| MD4Digest
implementation of MD4 as RFC 1320 by R. |
|
| MD5Digest
implementation of MD5 as outlined in "Handbook of Applied Cryptography", pages 346 - 347. |
|
| SSPIJNIClient
A JNI client to SSPI based CPP program (DLL) that returns the user credentials for NTLM authentication. |
|
| TimerThread
Simple timer class used to implement login and query timeouts. |
|
| TimerThread.TimerListener
Interface to be implemented by classes that request timer services. |
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.util.GeneralDigest
net.sourceforge.jtds.util.MD4Digest
implementation of MD4 as RFC 1320 by R. Rivest, MIT Laboratory for Computer Science and RSA Data Security, Inc.
NOTE: This algorithm is only included for backwards compatability with legacy applications, it's not secure, don't use it for anything new!
| Field Summary | |
private static int |
DIGEST_LENGTH
|
private int |
H1
|
private int |
H2
|
private int |
H3
|
private int |
H4
|
private static int |
S11
|
private static int |
S12
|
private static int |
S13
|
private static int |
S14
|
private static int |
S21
|
private static int |
S22
|
private static int |
S23
|
private static int |
S24
|
private static int |
S31
|
private static int |
S32
|
private static int |
S33
|
private static int |
S34
|
private int[] |
X
|
private int |
xOff
|
| Fields inherited from class net.sourceforge.jtds.util.GeneralDigest |
|
| Constructor Summary | |
MD4Digest()
Standard constructor |
|
MD4Digest(MD4Digest t)
Copy constructor. |
|
| Method Summary | |
int |
doFinal(byte[] out,
int outOff)
|
private int |
F(int u,
int v,
int w)
|
private int |
G(int u,
int v,
int w)
|
java.lang.String |
getAlgorithmName()
|
int |
getDigestSize()
|
private int |
H(int u,
int v,
int w)
|
protected void |
processBlock()
|
protected void |
processLength(long bitLength)
|
protected void |
processWord(byte[] in,
int inOff)
|
void |
reset()
reset the chaining variables to the IV values. |
private int |
rotateLeft(int x,
int n)
|
private void |
unpackWord(int word,
byte[] out,
int outOff)
|
| Methods inherited from class net.sourceforge.jtds.util.GeneralDigest |
finish, update, update |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private static final int DIGEST_LENGTH
private static final int S11
private static final int S12
private static final int S13
private static final int S14
private static final int S21
private static final int S22
private static final int S23
private static final int S24
private static final int S31
private static final int S32
private static final int S33
private static final int S34
private int H1
private int H2
private int H3
private int H4
private int[] X
private int xOff
| Constructor Detail |
public MD4Digest()
public MD4Digest(MD4Digest t)
| Method Detail |
public java.lang.String getAlgorithmName()
public int getDigestSize()
protected void processWord(byte[] in,
int inOff)
processWord in class GeneralDigestprotected void processLength(long bitLength)
processLength in class GeneralDigest
private void unpackWord(int word,
byte[] out,
int outOff)
public int doFinal(byte[] out,
int outOff)
public void reset()
reset in class GeneralDigest
private int rotateLeft(int x,
int n)
private int F(int u,
int v,
int w)
private int G(int u,
int v,
int w)
private int H(int u,
int v,
int w)
protected void processBlock()
processBlock in class GeneralDigest
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.util.BlobBuffer
Manages a buffer (backed by optional disk storage) for use as a data store by the CLOB and BLOB objects.
The data can be purely memory based until the size exceeds the value dictated by thelobBuffer URL property after which it will be
written to disk. The disk array is accessed randomly one page (1024 bytes)
at a time.
This class is not synchronized and concurrent open input and output
streams can conflict.
Tuning hints:
PAGE_SIZE governs how much data is buffered when
reading or writing data a byte at a time. 1024 bytes seems to work well
but if very large objects are being written a byte at a time 4096 may be
better. NB. ensure that the PAGE_MASK and
BYTE_MASK fields are also adjusted to match.
MAX_BUF_INC value. Every time the buffer is
expanded the existing contents are copied and this may get expensive
with very large BLOBs.
| Nested Class Summary | |
private class |
BlobBuffer.AsciiInputStream
An ASCII InputStream over the CLOB buffer.
|
private class |
BlobBuffer.AsciiOutputStream
Implements an ASCII OutputStream for CLOB data. |
private class |
BlobBuffer.BlobInputStream
An InputStream over the BLOB buffer. |
private class |
BlobBuffer.BlobOutputStream
Implements an OutputStream for BLOB data. |
private class |
BlobBuffer.UnicodeInputStream
A Big Endian Unicode InputStream over the CLOB buffer. |
| Field Summary | |
private java.io.File |
blobFile
The name of the temporary BLOB disk file. |
private byte[] |
buffer
The BLOB buffer or the current page buffer. |
private java.io.File |
bufferDir
The directory to buffer data to. |
private boolean |
bufferDirty
Indicates page in memory must be saved. |
private static int |
BYTE_MASK
Mask for page offset component of R/W pointer. |
private int |
currentPage
The number of the current page in memory. |
private static byte[] |
EMPTY_BUFFER
Default zero length buffer. |
private static int |
INVALID_PAGE
Invalid page marker. |
private boolean |
isMemOnly
True if attempts to create a BLOB file have failed. |
private int |
length
The total length of the valid data in buffer. |
private static int |
MAX_BUF_INC
Maximum buffer increment. |
private int |
maxMemSize
The maximum size of an in memory buffer. |
private int |
openCount
Count of callers that have opened the BLOB file. |
private static int |
PAGE_MASK
Mask for page component of read/write pointer. |
private static int |
PAGE_SIZE
Default page size (must be power of 2). |
private java.io.RandomAccessFile |
raFile
The RA file object reference or null if closed. |
| Constructor Summary | |
BlobBuffer(java.io.File bufferDir,
long maxMemSize)
Creates a blob buffer. |
|
| Method Summary | |
void |
close()
Logically closes the file or physically close it if the open count is now zero. |
void |
createBlobFile()
Creates a random access disk file to use as backing storage for the LOB data. |
protected void |
finalize()
Finalizes this object by deleting any work files. |
java.io.InputStream |
getBinaryStream(boolean ascii)
Retrieve the BLOB data as an InputStream. |
byte[] |
getBytes(long pos,
int len)
Returns the BLOB data as a byte array. |
long |
getLength()
Retrieves the length of this BLOB buffer in bytes. |
java.io.InputStream |
getUnicodeStream()
Retrieve the BLOB data as an Big Endian Unicode InputStream. |
void |
growBuffer(int minSize)
Increases the size of the in memory buffer for situations where disk storage of BLOB is not possible. |
void |
open()
Opens the BLOB disk file. |
int |
position(byte[] pattern,
long start)
Provides support for pattern searching methods. |
int |
read(int readPtr)
Reads byte from the BLOB buffer at the specified location. |
int |
read(int readPtr,
byte[] bytes,
int offset,
int len)
Reads bytes from the BLOB buffer at the specified location. |
void |
readPage(int page)
Reads in the specified page from the disk buffer. |
java.io.OutputStream |
setBinaryStream(long pos,
boolean ascii)
Creates an OutputStream that can be used to update the
BLOB.
|
void |
setBuffer(byte[] bytes,
boolean copy)
Sets the initial buffer to an existing byte array. |
int |
setBytes(long pos,
byte[] bytes,
int offset,
int len,
boolean copy)
Sets the content of the BLOB to the supplied byte array value. |
void |
setLength(long length)
Retrieves the length of the BLOB buffer (in memory version only). |
void |
truncate(long len)
Truncates the BLOB buffer to the specified size. |
(package private) void |
write(int writePtr,
byte[] bytes,
int offset,
int len)
Inserts bytes into the buffer at the specified location. |
void |
write(int writePtr,
int b)
Inserts a byte into the buffer at the specified location. |
void |
writePage(int page)
Writes the specified page to the disk buffer. |
| Methods inherited from class java.lang.Object |
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private static final byte[] EMPTY_BUFFER
private static final int PAGE_SIZE
private static final int PAGE_MASK
private static final int BYTE_MASK
private static final int MAX_BUF_INC
private static final int INVALID_PAGE
private byte[] buffer
private int length
private int currentPage
private java.io.File blobFile
private java.io.RandomAccessFile raFile
private boolean bufferDirty
private int openCount
private boolean isMemOnly
private final java.io.File bufferDir
private final int maxMemSize
| Constructor Detail |
public BlobBuffer(java.io.File bufferDir,
long maxMemSize)
bufferDir - maxMemSize - the maximum size of the in memory buffer| Method Detail |
protected void finalize()
throws java.lang.Throwable
java.lang.Throwablepublic void createBlobFile()
public void open()
throws java.io.IOException
java.io.IOException - if an I/O error occurs
public int read(int readPtr)
throws java.io.IOException
readPtr - the offset in the buffer of the required byte
int or -1 if at EOF
java.io.IOException - if an I/O error occurs
public int read(int readPtr,
byte[] bytes,
int offset,
int len)
throws java.io.IOException
readPtr - the offset in the buffer of the required bytebytes - the byte array to filloffset - the start position in the byte arraylen - the number of bytes to read
java.io.IOException - if an I/O error occurs
public void write(int writePtr,
int b)
throws java.io.IOException
writePtr - the offset in the buffer of the required byteb - the byte value to write
java.io.IOException - if an I/O error occurs
void write(int writePtr,
byte[] bytes,
int offset,
int len)
throws java.io.IOException
writePtr - the offset in the buffer of the required bytebytes - the byte array value to writeoffset - the start position in the byte arraylen - the number of bytes to write
java.io.IOException - if an I/O error occurs
public void readPage(int page)
throws java.io.IOException
page - the page number
java.io.IOException - if an I/O error occurs
public void writePage(int page)
throws java.io.IOException
page - the page number
java.io.IOException - if an I/O error occurs
public void close()
throws java.io.IOException
java.io.IOException - if an I/O error occurspublic void growBuffer(int minSize)
minSize - the minimum size of buffer required
public void setBuffer(byte[] bytes,
boolean copy)
bytes - the byte array containing the BLOB datacopy - true if a local copy of the data is required
public byte[] getBytes(long pos,
int len)
throws java.sql.SQLException
pos - the start position in the BLOB buffer (from 1)len - the number of bytes to copy
byte[]
java.sql.SQLException
public java.io.InputStream getBinaryStream(boolean ascii)
throws java.sql.SQLException
InputStream.
ascii - true if an ASCII input stream should be returned
InputStream built over the BLOB data
java.sql.SQLException - if an error occurs
public java.io.InputStream getUnicodeStream()
throws java.sql.SQLException
InputStream.
InputStream built over the BLOB data
java.sql.SQLException - if an error occurs
public java.io.OutputStream setBinaryStream(long pos,
boolean ascii)
throws java.sql.SQLException
OutputStream that can be used to update the
BLOB.
Given that we cannot know the final size of a BLOB created by the caller
of this method, we assume the worst and create a disk BLOB by default.
pos - the start position in the buffer (from 1)ascii - true if an ASCII output stream is required
OutputStream to be used to update the BLOB
java.sql.SQLException - if an error occurs
public int setBytes(long pos,
byte[] bytes,
int offset,
int len,
boolean copy)
throws java.sql.SQLException
pos - the start position in the buffer (from 1)bytes - the byte array containing the data to copyoffset - the start position in the byte array (from 0)len - the number of bytes to copycopy - true if a local copy of the byte array is required
java.sql.SQLException - if an error occurspublic long getLength()
public void setLength(long length)
length - the length of the valid data in the buffer
public void truncate(long len)
throws java.sql.SQLException
len - the required length
java.sql.SQLException - if an error occurs
public int position(byte[] pattern,
long start)
throws java.sql.SQLException
pattern - the byte array containg the search patternstart - the start position in the BLOB (from 1)
int start index for the pattern (from 1) or -1
if the pattern is not found.
java.sql.SQLException - if an error occurs
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjava.io.InputStream
net.sourceforge.jtds.util.BlobBuffer.BlobInputStream
An InputStream over the BLOB buffer.
| Field Summary | |
private boolean |
open
|
private int |
readPtr
|
| Fields inherited from class java.io.InputStream |
|
| Constructor Summary | |
BlobBuffer.BlobInputStream(long pos)
Costructs an InputStream object over the BLOB buffer. |
|
| Method Summary | |
int |
available()
Returns the number of bytes available to read. |
void |
close()
Closes the output stream. |
protected void |
finalize()
Ensures underlying BLOB file can be closed even if user does not close this stream. |
int |
read()
Reads the next byte from the stream. |
int |
read(byte[] bytes,
int offset,
int len)
Reads a bytes from the stream. |
| Methods inherited from class java.io.InputStream |
mark, markSupported, read, reset, skip |
| Methods inherited from class java.lang.Object |
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private int readPtr
private boolean open
| Constructor Detail |
public BlobBuffer.BlobInputStream(long pos)
throws java.io.IOException
InputStream object over the BLOB buffer.
pos - the starting position (from 0)
java.io.IOException - if an I/O error occurs| Method Detail |
protected void finalize()
throws java.lang.Throwable
java.lang.Throwable
public int available()
throws java.io.IOException
java.io.IOException - if an I/O error occurs
public int read()
throws java.io.IOException
int or -1 if at EOF
java.io.IOException - if an I/O error occurs
public int read(byte[] bytes,
int offset,
int len)
throws java.io.IOException
bytes - the byte array to filloffset - the start position in the byte arraylen - the number of bytes to read
java.io.IOException - if an I/O error occurs
public void close()
throws java.io.IOException
java.io.IOException - if an I/O error occurs
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.util.DESEngine
a class that provides a basic DES engine. Modified by Matt Brinkley (mdb) ... mainly just removed depends on external classes.
| Field Summary | |
(package private) static int[] |
bigbyte
|
protected static int |
BLOCK_SIZE
|
(package private) static short[] |
bytebit
|
(package private) static short[] |
Df_Key
what follows is mainly taken from "Applied Cryptography", by Bruce Schneier, however it also bears great resemblance to Richard Outerbridge's D3DES... |
(package private) static byte[] |
pc1
|
(package private) static byte[] |
pc2
|
(package private) static int[] |
SP1
|
(package private) static int[] |
SP2
|
(package private) static int[] |
SP3
|
(package private) static int[] |
SP4
|
(package private) static int[] |
SP5
|
(package private) static int[] |
SP6
|
(package private) static int[] |
SP7
|
(package private) static int[] |
SP8
|
(package private) static byte[] |
totrot
|
private int[] |
workingKey
|
| Constructor Summary | |
DESEngine()
standard constructor. |
|
DESEngine(boolean encrypting,
byte[] key)
mdb: convenient constructor |
|
| Method Summary | |
protected void |
desFunc(int[] wKey,
byte[] in,
int inOff,
byte[] out,
int outOff)
the DES engine. |
protected int[] |
generateWorkingKey(boolean encrypting,
byte[] key)
generate an integer based working key based on our secret key and what we processing we are planning to do. |
java.lang.String |
getAlgorithmName()
|
int |
getBlockSize()
|
void |
init(boolean encrypting,
byte[] key)
initialise a DES cipher. |
int |
processBlock(byte[] in,
int inOff,
byte[] out,
int outOff)
|
void |
reset()
|
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
protected static final int BLOCK_SIZE
private int[] workingKey
static short[] Df_Key
static short[] bytebit
static int[] bigbyte
static byte[] pc1
static byte[] totrot
static byte[] pc2
static int[] SP1
static int[] SP2
static int[] SP3
static int[] SP4
static int[] SP5
static int[] SP6
static int[] SP7
static int[] SP8
| Constructor Detail |
public DESEngine()
public DESEngine(boolean encrypting,
byte[] key)
| Method Detail |
public void init(boolean encrypting,
byte[] key)
encrypting - whether or not we are for encryption.key - the parameters required to set up the cipher.
java.lang.IllegalArgumentException - if the params argument is
inappropriate.public java.lang.String getAlgorithmName()
public int getBlockSize()
public int processBlock(byte[] in,
int inOff,
byte[] out,
int outOff)
public void reset()
protected int[] generateWorkingKey(boolean encrypting,
byte[] key)
protected void desFunc(int[] wKey,
byte[] in,
int inOff,
byte[] out,
int outOff)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
Interfaces
TimerThread.TimerListener |
|
Classes
BlobBuffer DESEngine GeneralDigest Logger MD4Digest MD5Digest SSPIJNIClient TimerThread TimerThread.TimerRequest |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectjava.io.OutputStream
net.sourceforge.jtds.util.BlobBuffer.BlobOutputStream
Implements an OutputStream for BLOB data.
| Field Summary | |
private boolean |
open
|
private int |
writePtr
|
| Constructor Summary | |
(package private) |
BlobBuffer.BlobOutputStream(long pos)
Costructs an OutputStream object over the BLOB buffer. |
| Method Summary | |
void |
close()
Close the output stream. |
protected void |
finalize()
Ensures underlying BLOB file can be closed even if user does not close this stream. |
void |
write(byte[] bytes,
int offset,
int len)
Write bytes to the BLOB buffer. |
void |
write(int b)
Write a byte to the BLOB buffer. |
| Methods inherited from class java.io.OutputStream |
flush, write |
| Methods inherited from class java.lang.Object |
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private int writePtr
private boolean open
| Constructor Detail |
BlobBuffer.BlobOutputStream(long pos)
throws java.io.IOException
pos - the starting position (from 0)
java.io.IOException - if an I/O error occurs| Method Detail |
protected void finalize()
throws java.lang.Throwable
java.lang.Throwable
public void write(int b)
throws java.io.IOException
b - the byte value to write
java.io.IOException - if an I/O error occurs
public void write(byte[] bytes,
int offset,
int len)
throws java.io.IOException
bytes - the byte array value to writeoffset - the start position in the byte arraylen - the number of bytes to write
java.io.IOException - if an I/O error occurs
public void close()
throws java.io.IOException
java.io.IOException - if an I/O error occurs
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
Interface to be implemented by classes that request timer services.
| Method Summary | |
void |
timerExpired()
Event to be fired when the timeout expires. |
| Method Detail |
public void timerExpired()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.util.GeneralDigest
base implementation of MD4 family style digest as outlined in "Handbook of Applied Cryptography", pages 344 - 347.
| Field Summary | |
private long |
byteCount
|
private byte[] |
xBuf
|
private int |
xBufOff
|
| Constructor Summary | |
protected |
GeneralDigest()
Standard constructor |
protected |
GeneralDigest(GeneralDigest t)
Copy constructor. |
| Method Summary | |
void |
finish()
|
protected abstract void |
processBlock()
|
protected abstract void |
processLength(long bitLength)
|
protected abstract void |
processWord(byte[] in,
int inOff)
|
void |
reset()
|
void |
update(byte in)
|
void |
update(byte[] in,
int inOff,
int len)
|
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private byte[] xBuf
private int xBufOff
private long byteCount
| Constructor Detail |
protected GeneralDigest()
protected GeneralDigest(GeneralDigest t)
| Method Detail |
public void update(byte in)
public void update(byte[] in,
int inOff,
int len)
public void finish()
public void reset()
protected abstract void processWord(byte[] in,
int inOff)
protected abstract void processLength(long bitLength)
protected abstract void processBlock()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use PooledConnection | |
| net.sourceforge.jtds.jdbcx | |
| net.sourceforge.jtds.jdbcx.proxy | |
| Uses of PooledConnection in net.sourceforge.jtds.jdbcx |
| Subclasses of PooledConnection in net.sourceforge.jtds.jdbcx | |
class |
JtdsXAConnection
jTDS implementation of the XAConnection interface. |
| Uses of PooledConnection in net.sourceforge.jtds.jdbcx.proxy |
| Fields in net.sourceforge.jtds.jdbcx.proxy declared as PooledConnection | |
private PooledConnection |
ConnectionProxy._pooledConnection
|
| Constructors in net.sourceforge.jtds.jdbcx.proxy with parameters of type PooledConnection | |
ConnectionProxy(PooledConnection pooledConnection,
java.sql.Connection connection)
Constructs a new connection proxy. |
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use JtdsDataSource | |
| net.sourceforge.jtds.jdbcx | |
| Uses of JtdsDataSource in net.sourceforge.jtds.jdbcx |
| Fields in net.sourceforge.jtds.jdbcx declared as JtdsDataSource | |
private JtdsDataSource |
JtdsXAConnection.dataSource
|
| Methods in net.sourceforge.jtds.jdbcx that return JtdsDataSource | |
protected JtdsDataSource |
JtdsXAConnection.getXADataSource()
|
| Constructors in net.sourceforge.jtds.jdbcx with parameters of type JtdsDataSource | |
JtdsXAConnection(JtdsDataSource dataSource,
java.sql.Connection connection)
Construct a new XAConnection object. |
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use JtdsXAConnection | |
| net.sourceforge.jtds.jdbcx | |
| Uses of JtdsXAConnection in net.sourceforge.jtds.jdbcx |
| Fields in net.sourceforge.jtds.jdbcx declared as JtdsXAConnection | |
private JtdsXAConnection |
JtdsXAResource.xaConnection
|
| Methods in net.sourceforge.jtds.jdbcx that return JtdsXAConnection | |
protected JtdsXAConnection |
JtdsXAResource.getResourceManager()
|
| Constructors in net.sourceforge.jtds.jdbcx with parameters of type JtdsXAConnection | |
JtdsXAResource(JtdsXAConnection xaConnection,
java.sql.Connection connection)
|
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbcx.JtdsObjectFactory
Description
| Constructor Summary | |
JtdsObjectFactory()
|
|
| Method Summary | |
java.lang.Object |
getObjectInstance(java.lang.Object refObj,
javax.naming.Name name,
javax.naming.Context nameCtx,
java.util.Hashtable env)
|
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Constructor Detail |
public JtdsObjectFactory()
| Method Detail |
public java.lang.Object getObjectInstance(java.lang.Object refObj,
javax.naming.Name name,
javax.naming.Context nameCtx,
java.util.Hashtable env)
throws java.lang.Exception
getObjectInstance in interface javax.naming.spi.ObjectFactoryjava.lang.Exception
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use StatementProxy | |
| net.sourceforge.jtds.jdbcx.proxy | |
| Uses of StatementProxy in net.sourceforge.jtds.jdbcx.proxy |
| Subclasses of StatementProxy in net.sourceforge.jtds.jdbcx.proxy | |
class |
CallableStatementProxy
This class would be better implemented as a java.lang.reflect.Proxy. |
class |
PreparedStatementProxy
This class would be better implemented as a java.lang.reflect.Proxy. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use ConnectionProxy | |
| net.sourceforge.jtds.jdbcx.proxy | |
| Uses of ConnectionProxy in net.sourceforge.jtds.jdbcx.proxy |
| Fields in net.sourceforge.jtds.jdbcx.proxy declared as ConnectionProxy | |
private ConnectionProxy |
StatementProxy._connection
|
| Constructors in net.sourceforge.jtds.jdbcx.proxy with parameters of type ConnectionProxy | |
StatementProxy(ConnectionProxy connection,
JtdsStatement statement)
|
|
PreparedStatementProxy(ConnectionProxy connection,
JtdsPreparedStatement preparedStatement)
|
|
CallableStatementProxy(ConnectionProxy connection,
JtdsCallableStatement callableStatement)
|
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use PreparedStatementProxy | |
| net.sourceforge.jtds.jdbcx.proxy | |
| Uses of PreparedStatementProxy in net.sourceforge.jtds.jdbcx.proxy |
| Subclasses of PreparedStatementProxy in net.sourceforge.jtds.jdbcx.proxy | |
class |
CallableStatementProxy
This class would be better implemented as a java.lang.reflect.Proxy. |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV PACKAGE NEXT PACKAGE | FRAMES NO FRAMES | ||||||||||
| Class Summary | |
| CallableStatementProxy | This class would be better implemented as a java.lang.reflect.Proxy. |
| ConnectionProxy | This class would be better implemented as a java.lang.reflect.Proxy. |
| PreparedStatementProxy | This class would be better implemented as a java.lang.reflect.Proxy. |
| StatementProxy | This class would be better implemented as a java.lang.reflect.Proxy. |
|
|||||||||||
| PREV PACKAGE NEXT PACKAGE | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use net.sourceforge.jtds.jdbcx.proxy | |
| net.sourceforge.jtds.jdbcx.proxy | |
| Classes in net.sourceforge.jtds.jdbcx.proxy used by net.sourceforge.jtds.jdbcx.proxy | |
| ConnectionProxy
This class would be better implemented as a java.lang.reflect.Proxy. |
|
| PreparedStatementProxy
This class would be better implemented as a java.lang.reflect.Proxy. |
|
| StatementProxy
This class would be better implemented as a java.lang.reflect.Proxy. |
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbcx.proxy.StatementProxy
This class would be better implemented as a java.lang.reflect.Proxy. However, this feature was not added until 1.3 and reflection performance was not improved until 1.4. Since the driver still needs to be compatible with 1.2 and 1.3 this class is used to delegate the calls to a statement with minimal overhead.
| Field Summary | |
private ConnectionProxy |
_connection
|
private JtdsStatement |
_statement
|
| Fields inherited from interface java.sql.Statement |
CLOSE_ALL_RESULTS, CLOSE_CURRENT_RESULT, EXECUTE_FAILED, KEEP_CURRENT_RESULT, NO_GENERATED_KEYS, RETURN_GENERATED_KEYS, SUCCESS_NO_INFO |
| Constructor Summary | |
(package private) |
StatementProxy(ConnectionProxy connection,
JtdsStatement statement)
|
| Method Summary | |
void |
addBatch(java.lang.String sql)
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
void |
cancel()
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
void |
clearBatch()
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
void |
clearWarnings()
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
void |
close()
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
boolean |
execute(java.lang.String sql)
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
boolean |
execute(java.lang.String sql,
int autoGeneratedKeys)
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
boolean |
execute(java.lang.String sql,
int[] columnIndexes)
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
boolean |
execute(java.lang.String sql,
java.lang.String[] columnNames)
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
int[] |
executeBatch()
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
java.sql.ResultSet |
executeQuery(java.lang.String sql)
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
int |
executeUpdate(java.lang.String sql)
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
int |
executeUpdate(java.lang.String sql,
int autoGeneratedKeys)
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
int |
executeUpdate(java.lang.String sql,
int[] columnIndexes)
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
int |
executeUpdate(java.lang.String sql,
java.lang.String[] columnNames)
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
java.sql.Connection |
getConnection()
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
int |
getFetchDirection()
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
int |
getFetchSize()
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
java.sql.ResultSet |
getGeneratedKeys()
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
int |
getMaxFieldSize()
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
int |
getMaxRows()
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
boolean |
getMoreResults()
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
boolean |
getMoreResults(int current)
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
int |
getQueryTimeout()
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
java.sql.ResultSet |
getResultSet()
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
int |
getResultSetConcurrency()
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
int |
getResultSetHoldability()
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
int |
getResultSetType()
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
int |
getUpdateCount()
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
java.sql.SQLWarning |
getWarnings()
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
protected void |
processSQLException(java.sql.SQLException sqlException)
Processes SQLExceptions. |
void |
setCursorName(java.lang.String name)
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
void |
setEscapeProcessing(boolean enable)
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
void |
setFetchDirection(int direction)
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
void |
setFetchSize(int rows)
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
void |
setMaxFieldSize(int max)
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
void |
setMaxRows(int max)
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
void |
setQueryTimeout(int seconds)
Delgates calls to the statement; SQLExceptions thrown from the statement will cause an event to be fired on the connection pool listeners. |
protected void |
validateConnection()
Validates the connection state. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private ConnectionProxy _connection
private JtdsStatement _statement
| Constructor Detail |
StatementProxy(ConnectionProxy connection, JtdsStatement statement)
| Method Detail |
public java.sql.ResultSet executeQuery(java.lang.String sql)
throws java.sql.SQLException
executeQuery in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public int executeUpdate(java.lang.String sql)
throws java.sql.SQLException
executeUpdate in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public void close()
throws java.sql.SQLException
close in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public int getMaxFieldSize()
throws java.sql.SQLException
getMaxFieldSize in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public void setMaxFieldSize(int max)
throws java.sql.SQLException
setMaxFieldSize in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public int getMaxRows()
throws java.sql.SQLException
getMaxRows in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public void setMaxRows(int max)
throws java.sql.SQLException
setMaxRows in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public void setEscapeProcessing(boolean enable)
throws java.sql.SQLException
setEscapeProcessing in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public int getQueryTimeout()
throws java.sql.SQLException
getQueryTimeout in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public void setQueryTimeout(int seconds)
throws java.sql.SQLException
setQueryTimeout in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public void cancel()
throws java.sql.SQLException
cancel in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public java.sql.SQLWarning getWarnings()
throws java.sql.SQLException
getWarnings in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public void clearWarnings()
throws java.sql.SQLException
clearWarnings in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public void setCursorName(java.lang.String name)
throws java.sql.SQLException
setCursorName in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public boolean execute(java.lang.String sql)
throws java.sql.SQLException
execute in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public java.sql.ResultSet getResultSet()
throws java.sql.SQLException
getResultSet in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public int getUpdateCount()
throws java.sql.SQLException
getUpdateCount in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public boolean getMoreResults()
throws java.sql.SQLException
getMoreResults in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public void setFetchDirection(int direction)
throws java.sql.SQLException
setFetchDirection in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public int getFetchDirection()
throws java.sql.SQLException
getFetchDirection in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public void setFetchSize(int rows)
throws java.sql.SQLException
setFetchSize in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public int getFetchSize()
throws java.sql.SQLException
getFetchSize in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public int getResultSetConcurrency()
throws java.sql.SQLException
getResultSetConcurrency in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public int getResultSetType()
throws java.sql.SQLException
getResultSetType in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public void addBatch(java.lang.String sql)
throws java.sql.SQLException
addBatch in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public void clearBatch()
throws java.sql.SQLException
clearBatch in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public int[] executeBatch()
throws java.sql.SQLException
executeBatch in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public java.sql.Connection getConnection()
throws java.sql.SQLException
getConnection in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public boolean getMoreResults(int current)
throws java.sql.SQLException
getMoreResults in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public java.sql.ResultSet getGeneratedKeys()
throws java.sql.SQLException
getGeneratedKeys in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public int executeUpdate(java.lang.String sql,
int autoGeneratedKeys)
throws java.sql.SQLException
executeUpdate in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public int executeUpdate(java.lang.String sql,
int[] columnIndexes)
throws java.sql.SQLException
executeUpdate in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public int executeUpdate(java.lang.String sql,
java.lang.String[] columnNames)
throws java.sql.SQLException
executeUpdate in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public boolean execute(java.lang.String sql,
int autoGeneratedKeys)
throws java.sql.SQLException
execute in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public boolean execute(java.lang.String sql,
int[] columnIndexes)
throws java.sql.SQLException
execute in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public boolean execute(java.lang.String sql,
java.lang.String[] columnNames)
throws java.sql.SQLException
execute in interface java.sql.Statementjava.sql.SQLException - if an error occurs
public int getResultSetHoldability()
throws java.sql.SQLException
getResultSetHoldability in interface java.sql.Statementjava.sql.SQLException - if an error occurs
protected void validateConnection()
throws java.sql.SQLException
java.sql.SQLException
protected void processSQLException(java.sql.SQLException sqlException)
throws java.sql.SQLException
java.sql.SQLException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbcx.proxy.ConnectionProxy
This class would be better implemented as a java.lang.reflect.Proxy. However, this feature was not added until 1.3 and reflection performance was not improved until 1.4. Since the driver still needs to be compatible with 1.2 and 1.3 this class is used to delegate the calls to the connection with minimal overhead.
| Field Summary | |
private boolean |
_closed
|
private ConnectionJDBC2 |
_connection
|
private PooledConnection |
_pooledConnection
|
| Fields inherited from interface java.sql.Connection |
TRANSACTION_NONE, TRANSACTION_READ_COMMITTED, TRANSACTION_READ_UNCOMMITTED, TRANSACTION_REPEATABLE_READ, TRANSACTION_SERIALIZABLE |
| Constructor Summary | |
ConnectionProxy(PooledConnection pooledConnection,
java.sql.Connection connection)
Constructs a new connection proxy. |
|
| Method Summary | |
void |
clearWarnings()
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
void |
close()
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
void |
commit()
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
java.sql.Statement |
createStatement()
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
java.sql.Statement |
createStatement(int resultSetType,
int resultSetConcurrency)
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
java.sql.Statement |
createStatement(int resultSetType,
int resultSetConcurrency,
int resultSetHoldability)
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
protected void |
finalize()
Closes the proxy, releasing the connection. |
boolean |
getAutoCommit()
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
java.lang.String |
getCatalog()
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
int |
getHoldability()
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
java.sql.DatabaseMetaData |
getMetaData()
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
int |
getTransactionIsolation()
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
java.util.Map |
getTypeMap()
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
java.sql.SQLWarning |
getWarnings()
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
boolean |
isClosed()
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
boolean |
isReadOnly()
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
java.lang.String |
nativeSQL(java.lang.String sql)
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
java.sql.CallableStatement |
prepareCall(java.lang.String sql)
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
java.sql.CallableStatement |
prepareCall(java.lang.String sql,
int resultSetType,
int resultSetConcurrency)
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
java.sql.CallableStatement |
prepareCall(java.lang.String sql,
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability)
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
java.sql.PreparedStatement |
prepareStatement(java.lang.String sql)
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
java.sql.PreparedStatement |
prepareStatement(java.lang.String sql,
int autoGeneratedKeys)
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
java.sql.PreparedStatement |
prepareStatement(java.lang.String sql,
int[] columnIndexes)
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
java.sql.PreparedStatement |
prepareStatement(java.lang.String sql,
int resultSetType,
int resultSetConcurrency)
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
java.sql.PreparedStatement |
prepareStatement(java.lang.String sql,
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability)
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
java.sql.PreparedStatement |
prepareStatement(java.lang.String sql,
java.lang.String[] columnNames)
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
(package private) void |
processSQLException(java.sql.SQLException sqlException)
Processes SQLExceptions. |
void |
releaseSavepoint(java.sql.Savepoint savepoint)
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
void |
rollback()
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
void |
rollback(java.sql.Savepoint savepoint)
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
void |
setAutoCommit(boolean autoCommit)
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
void |
setCatalog(java.lang.String catalog)
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
void |
setHoldability(int holdability)
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
void |
setReadOnly(boolean readOnly)
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
java.sql.Savepoint |
setSavepoint()
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
java.sql.Savepoint |
setSavepoint(java.lang.String name)
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
void |
setTransactionIsolation(int level)
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
void |
setTypeMap(java.util.Map map)
Delgates calls to the connection; SQLExceptions thrown from the connection will cause an event to be fired on the connection pool listeners. |
private void |
validateConnection()
Validates the connection state. |
| Methods inherited from class java.lang.Object |
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private PooledConnection _pooledConnection
private ConnectionJDBC2 _connection
private boolean _closed
| Constructor Detail |
public ConnectionProxy(PooledConnection pooledConnection, java.sql.Connection connection)
| Method Detail |
public void clearWarnings()
throws java.sql.SQLException
clearWarnings in interface java.sql.Connectionjava.sql.SQLException - if an error occurspublic void close()
close in interface java.sql.Connection
public void commit()
throws java.sql.SQLException
commit in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public java.sql.Statement createStatement()
throws java.sql.SQLException
createStatement in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public java.sql.Statement createStatement(int resultSetType,
int resultSetConcurrency)
throws java.sql.SQLException
createStatement in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public java.sql.Statement createStatement(int resultSetType,
int resultSetConcurrency,
int resultSetHoldability)
throws java.sql.SQLException
createStatement in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public boolean getAutoCommit()
throws java.sql.SQLException
getAutoCommit in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public java.lang.String getCatalog()
throws java.sql.SQLException
getCatalog in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public int getHoldability()
throws java.sql.SQLException
getHoldability in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public int getTransactionIsolation()
throws java.sql.SQLException
getTransactionIsolation in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public java.util.Map getTypeMap()
throws java.sql.SQLException
getTypeMap in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public java.sql.SQLWarning getWarnings()
throws java.sql.SQLException
getWarnings in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public java.sql.DatabaseMetaData getMetaData()
throws java.sql.SQLException
getMetaData in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public boolean isClosed()
throws java.sql.SQLException
isClosed in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public boolean isReadOnly()
throws java.sql.SQLException
isReadOnly in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public java.lang.String nativeSQL(java.lang.String sql)
throws java.sql.SQLException
nativeSQL in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public java.sql.CallableStatement prepareCall(java.lang.String sql)
throws java.sql.SQLException
prepareCall in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public java.sql.CallableStatement prepareCall(java.lang.String sql,
int resultSetType,
int resultSetConcurrency)
throws java.sql.SQLException
prepareCall in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public java.sql.CallableStatement prepareCall(java.lang.String sql,
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability)
throws java.sql.SQLException
prepareCall in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public java.sql.PreparedStatement prepareStatement(java.lang.String sql)
throws java.sql.SQLException
prepareStatement in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public java.sql.PreparedStatement prepareStatement(java.lang.String sql,
int autoGeneratedKeys)
throws java.sql.SQLException
prepareStatement in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public java.sql.PreparedStatement prepareStatement(java.lang.String sql,
int[] columnIndexes)
throws java.sql.SQLException
prepareStatement in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public java.sql.PreparedStatement prepareStatement(java.lang.String sql,
java.lang.String[] columnNames)
throws java.sql.SQLException
prepareStatement in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public java.sql.PreparedStatement prepareStatement(java.lang.String sql,
int resultSetType,
int resultSetConcurrency)
throws java.sql.SQLException
prepareStatement in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public java.sql.PreparedStatement prepareStatement(java.lang.String sql,
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability)
throws java.sql.SQLException
prepareStatement in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public void releaseSavepoint(java.sql.Savepoint savepoint)
throws java.sql.SQLException
releaseSavepoint in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public void rollback()
throws java.sql.SQLException
rollback in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public void rollback(java.sql.Savepoint savepoint)
throws java.sql.SQLException
rollback in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public void setAutoCommit(boolean autoCommit)
throws java.sql.SQLException
setAutoCommit in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public void setCatalog(java.lang.String catalog)
throws java.sql.SQLException
setCatalog in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public void setHoldability(int holdability)
throws java.sql.SQLException
setHoldability in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public void setReadOnly(boolean readOnly)
throws java.sql.SQLException
setReadOnly in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public java.sql.Savepoint setSavepoint()
throws java.sql.SQLException
setSavepoint in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public java.sql.Savepoint setSavepoint(java.lang.String name)
throws java.sql.SQLException
setSavepoint in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public void setTransactionIsolation(int level)
throws java.sql.SQLException
setTransactionIsolation in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
public void setTypeMap(java.util.Map map)
throws java.sql.SQLException
setTypeMap in interface java.sql.Connectionjava.sql.SQLException - if an error occurs
private void validateConnection()
throws java.sql.SQLException
java.sql.SQLException
void processSQLException(java.sql.SQLException sqlException)
throws java.sql.SQLException
java.sql.SQLExceptionprotected void finalize()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
Classes
CallableStatementProxy ConnectionProxy PreparedStatementProxy StatementProxy |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbcx.proxy.StatementProxy
net.sourceforge.jtds.jdbcx.proxy.PreparedStatementProxy
net.sourceforge.jtds.jdbcx.proxy.CallableStatementProxy
This class would be better implemented as a java.lang.reflect.Proxy. However, this feature was not added until 1.3 and reflection performance was not improved until 1.4. Since the driver still needs to be compatible with 1.2 and 1.3 this class is used to delegate the calls to a callable statement with minimal overhead.
| Field Summary | |
private JtdsCallableStatement |
_callableStatement
|
| Fields inherited from class net.sourceforge.jtds.jdbcx.proxy.PreparedStatementProxy |
|
| Fields inherited from class net.sourceforge.jtds.jdbcx.proxy.StatementProxy |
|
| Fields inherited from interface java.sql.Statement |
CLOSE_ALL_RESULTS, CLOSE_CURRENT_RESULT, EXECUTE_FAILED, KEEP_CURRENT_RESULT, NO_GENERATED_KEYS, RETURN_GENERATED_KEYS, SUCCESS_NO_INFO |
| Constructor Summary | |
(package private) |
CallableStatementProxy(ConnectionProxy connection,
JtdsCallableStatement callableStatement)
|
| Method Summary | |
java.sql.Array |
getArray(int parameterIndex)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.sql.Array |
getArray(java.lang.String parameterName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.math.BigDecimal |
getBigDecimal(int parameterIndex)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.math.BigDecimal |
getBigDecimal(int parameterIndex,
int scale)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.math.BigDecimal |
getBigDecimal(java.lang.String parameterName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.sql.Blob |
getBlob(int parameterIndex)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.sql.Blob |
getBlob(java.lang.String parameterName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
boolean |
getBoolean(int parameterIndex)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
boolean |
getBoolean(java.lang.String parameterName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
byte |
getByte(int parameterIndex)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
byte |
getByte(java.lang.String parameterName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
byte[] |
getBytes(int parameterIndex)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
byte[] |
getBytes(java.lang.String parameterName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.sql.Clob |
getClob(int parameterIndex)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.sql.Clob |
getClob(java.lang.String parameterName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.sql.Date |
getDate(int parameterIndex)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.sql.Date |
getDate(int parameterIndex,
java.util.Calendar cal)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.sql.Date |
getDate(java.lang.String parameterName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.sql.Date |
getDate(java.lang.String parameterName,
java.util.Calendar cal)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
double |
getDouble(int parameterIndex)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
double |
getDouble(java.lang.String parameterName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
float |
getFloat(int parameterIndex)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
float |
getFloat(java.lang.String parameterName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
int |
getInt(int parameterIndex)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
int |
getInt(java.lang.String parameterName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
long |
getLong(int parameterIndex)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
long |
getLong(java.lang.String parameterName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.lang.Object |
getObject(int parameterIndex)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.lang.Object |
getObject(int parameterIndex,
java.util.Map map)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.lang.Object |
getObject(java.lang.String parameterName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.lang.Object |
getObject(java.lang.String parameterName,
java.util.Map map)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.sql.Ref |
getRef(int parameterIndex)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.sql.Ref |
getRef(java.lang.String parameterName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
short |
getShort(int parameterIndex)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
short |
getShort(java.lang.String parameterName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.lang.String |
getString(int parameterIndex)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.lang.String |
getString(java.lang.String parameterName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.sql.Time |
getTime(int parameterIndex)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.sql.Time |
getTime(int parameterIndex,
java.util.Calendar cal)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.sql.Time |
getTime(java.lang.String parameterName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.sql.Time |
getTime(java.lang.String parameterName,
java.util.Calendar cal)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.sql.Timestamp |
getTimestamp(int parameterIndex)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.sql.Timestamp |
getTimestamp(int parameterIndex,
java.util.Calendar cal)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.sql.Timestamp |
getTimestamp(java.lang.String parameterName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.sql.Timestamp |
getTimestamp(java.lang.String parameterName,
java.util.Calendar cal)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.net.URL |
getURL(int parameterIndex)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
java.net.URL |
getURL(java.lang.String parameterName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
registerOutParameter(int parameterIndex,
int sqlType)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
registerOutParameter(int parameterIndex,
int sqlType,
int scale)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
registerOutParameter(int parameterIndex,
int sqlType,
java.lang.String typeName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
registerOutParameter(java.lang.String parameterName,
int sqlType)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
registerOutParameter(java.lang.String parameterName,
int sqlType,
int scale)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
registerOutParameter(java.lang.String parameterName,
int sqlType,
java.lang.String typeName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setAsciiStream(java.lang.String parameterName,
java.io.InputStream x,
int length)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setBigDecimal(java.lang.String parameterName,
java.math.BigDecimal x)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setBinaryStream(java.lang.String parameterName,
java.io.InputStream x,
int length)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setBoolean(java.lang.String parameterName,
boolean x)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setByte(java.lang.String parameterName,
byte x)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setBytes(java.lang.String parameterName,
byte[] x)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setCharacterStream(java.lang.String parameterName,
java.io.Reader x,
int length)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setDate(java.lang.String parameterName,
java.sql.Date x)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setDate(java.lang.String parameterName,
java.sql.Date x,
java.util.Calendar cal)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setDouble(java.lang.String parameterName,
double x)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setFloat(java.lang.String parameterName,
float x)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setInt(java.lang.String parameterName,
int x)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setLong(java.lang.String parameterName,
long x)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setNull(java.lang.String parameterName,
int sqlType)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setNull(java.lang.String parameterName,
int sqlType,
java.lang.String typeName)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setObject(java.lang.String parameterName,
java.lang.Object x)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setObject(java.lang.String parameterName,
java.lang.Object x,
int targetSqlType)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setObject(java.lang.String parameterName,
java.lang.Object x,
int targetSqlType,
int scale)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setShort(java.lang.String parameterName,
short x)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setString(java.lang.String parameterName,
java.lang.String x)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setTime(java.lang.String parameterName,
java.sql.Time x)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setTime(java.lang.String parameterName,
java.sql.Time x,
java.util.Calendar cal)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setTimestamp(java.lang.String parameterName,
java.sql.Timestamp x)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setTimestamp(java.lang.String parameterName,
java.sql.Timestamp x,
java.util.Calendar cal)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
void |
setURL(java.lang.String parameterName,
java.net.URL val)
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
boolean |
wasNull()
Delgates calls to the callable statement; SQLExceptions thrown from the callable statement will cause an event to be fired on the connection pool listeners. |
| Methods inherited from class net.sourceforge.jtds.jdbcx.proxy.PreparedStatementProxy |
addBatch, clearParameters, execute, executeQuery, executeUpdate, getMetaData, getParameterMetaData, setArray, setAsciiStream, setBigDecimal, setBinaryStream, setBlob, setBoolean, setByte, setBytes, setCharacterStream, setClob, setDate, setDate, setDouble, setFloat, setInt, setLong, setNull, setNull, setObject, setObject, setObject, setRef, setShort, setString, setTime, setTime, setTimestamp, setTimestamp, setUnicodeStream, setURL |
| Methods inherited from class net.sourceforge.jtds.jdbcx.proxy.StatementProxy |
addBatch, cancel, clearBatch, clearWarnings, close, execute, execute, execute, execute, executeBatch, executeQuery, executeUpdate, executeUpdate, executeUpdate, executeUpdate, getConnection, getFetchDirection, getFetchSize, getGeneratedKeys, getMaxFieldSize, getMaxRows, getMoreResults, getMoreResults, getQueryTimeout, getResultSet, getResultSetConcurrency, getResultSetHoldability, getResultSetType, getUpdateCount, getWarnings, processSQLException, setCursorName, setEscapeProcessing, setFetchDirection, setFetchSize, setMaxFieldSize, setMaxRows, setQueryTimeout, validateConnection |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Methods inherited from interface java.sql.PreparedStatement |
addBatch, clearParameters, execute, executeQuery, executeUpdate, getMetaData, getParameterMetaData, setArray, setAsciiStream, setBigDecimal, setBinaryStream, setBlob, setBoolean, setByte, setBytes, setCharacterStream, setClob, setDate, setDate, setDouble, setFloat, setInt, setLong, setNull, setNull, setObject, setObject, setObject, setRef, setShort, setString, setTime, setTime, setTimestamp, setTimestamp, setUnicodeStream, setURL |
| Methods inherited from interface java.sql.Statement |
addBatch, cancel, clearBatch, clearWarnings, close, execute, execute, execute, execute, executeBatch, executeQuery, executeUpdate, executeUpdate, executeUpdate, executeUpdate, getConnection, getFetchDirection, getFetchSize, getGeneratedKeys, getMaxFieldSize, getMaxRows, getMoreResults, getMoreResults, getQueryTimeout, getResultSet, getResultSetConcurrency, getResultSetHoldability, getResultSetType, getUpdateCount, getWarnings, setCursorName, setEscapeProcessing, setFetchDirection, setFetchSize, setMaxFieldSize, setMaxRows, setQueryTimeout |
| Field Detail |
private JtdsCallableStatement _callableStatement
| Constructor Detail |
CallableStatementProxy(ConnectionProxy connection, JtdsCallableStatement callableStatement)
| Method Detail |
public void registerOutParameter(int parameterIndex,
int sqlType)
throws java.sql.SQLException
registerOutParameter in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void registerOutParameter(int parameterIndex,
int sqlType,
int scale)
throws java.sql.SQLException
registerOutParameter in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public boolean wasNull()
throws java.sql.SQLException
wasNull in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.lang.String getString(int parameterIndex)
throws java.sql.SQLException
getString in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public boolean getBoolean(int parameterIndex)
throws java.sql.SQLException
getBoolean in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public byte getByte(int parameterIndex)
throws java.sql.SQLException
getByte in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public short getShort(int parameterIndex)
throws java.sql.SQLException
getShort in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public int getInt(int parameterIndex)
throws java.sql.SQLException
getInt in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public long getLong(int parameterIndex)
throws java.sql.SQLException
getLong in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public float getFloat(int parameterIndex)
throws java.sql.SQLException
getFloat in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public double getDouble(int parameterIndex)
throws java.sql.SQLException
getDouble in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.math.BigDecimal getBigDecimal(int parameterIndex,
int scale)
throws java.sql.SQLException
getBigDecimal in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public byte[] getBytes(int parameterIndex)
throws java.sql.SQLException
getBytes in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.sql.Date getDate(int parameterIndex)
throws java.sql.SQLException
getDate in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.sql.Time getTime(int parameterIndex)
throws java.sql.SQLException
getTime in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.sql.Timestamp getTimestamp(int parameterIndex)
throws java.sql.SQLException
getTimestamp in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.lang.Object getObject(int parameterIndex)
throws java.sql.SQLException
getObject in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.math.BigDecimal getBigDecimal(int parameterIndex)
throws java.sql.SQLException
getBigDecimal in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.lang.Object getObject(int parameterIndex,
java.util.Map map)
throws java.sql.SQLException
getObject in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.sql.Ref getRef(int parameterIndex)
throws java.sql.SQLException
getRef in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.sql.Blob getBlob(int parameterIndex)
throws java.sql.SQLException
getBlob in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.sql.Clob getClob(int parameterIndex)
throws java.sql.SQLException
getClob in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.sql.Array getArray(int parameterIndex)
throws java.sql.SQLException
getArray in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.sql.Date getDate(int parameterIndex,
java.util.Calendar cal)
throws java.sql.SQLException
getDate in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.sql.Time getTime(int parameterIndex,
java.util.Calendar cal)
throws java.sql.SQLException
getTime in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.sql.Timestamp getTimestamp(int parameterIndex,
java.util.Calendar cal)
throws java.sql.SQLException
getTimestamp in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void registerOutParameter(int parameterIndex,
int sqlType,
java.lang.String typeName)
throws java.sql.SQLException
registerOutParameter in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void registerOutParameter(java.lang.String parameterName,
int sqlType)
throws java.sql.SQLException
registerOutParameter in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void registerOutParameter(java.lang.String parameterName,
int sqlType,
int scale)
throws java.sql.SQLException
registerOutParameter in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void registerOutParameter(java.lang.String parameterName,
int sqlType,
java.lang.String typeName)
throws java.sql.SQLException
registerOutParameter in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.net.URL getURL(int parameterIndex)
throws java.sql.SQLException
getURL in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setURL(java.lang.String parameterName,
java.net.URL val)
throws java.sql.SQLException
setURL in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setNull(java.lang.String parameterName,
int sqlType)
throws java.sql.SQLException
setNull in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setBoolean(java.lang.String parameterName,
boolean x)
throws java.sql.SQLException
setBoolean in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setByte(java.lang.String parameterName,
byte x)
throws java.sql.SQLException
setByte in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setShort(java.lang.String parameterName,
short x)
throws java.sql.SQLException
setShort in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setInt(java.lang.String parameterName,
int x)
throws java.sql.SQLException
setInt in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setLong(java.lang.String parameterName,
long x)
throws java.sql.SQLException
setLong in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setFloat(java.lang.String parameterName,
float x)
throws java.sql.SQLException
setFloat in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setDouble(java.lang.String parameterName,
double x)
throws java.sql.SQLException
setDouble in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setBigDecimal(java.lang.String parameterName,
java.math.BigDecimal x)
throws java.sql.SQLException
setBigDecimal in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setString(java.lang.String parameterName,
java.lang.String x)
throws java.sql.SQLException
setString in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setBytes(java.lang.String parameterName,
byte[] x)
throws java.sql.SQLException
setBytes in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setDate(java.lang.String parameterName,
java.sql.Date x)
throws java.sql.SQLException
setDate in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setTime(java.lang.String parameterName,
java.sql.Time x)
throws java.sql.SQLException
setTime in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setTimestamp(java.lang.String parameterName,
java.sql.Timestamp x)
throws java.sql.SQLException
setTimestamp in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setAsciiStream(java.lang.String parameterName,
java.io.InputStream x,
int length)
throws java.sql.SQLException
setAsciiStream in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setBinaryStream(java.lang.String parameterName,
java.io.InputStream x,
int length)
throws java.sql.SQLException
setBinaryStream in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setObject(java.lang.String parameterName,
java.lang.Object x,
int targetSqlType,
int scale)
throws java.sql.SQLException
setObject in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setObject(java.lang.String parameterName,
java.lang.Object x,
int targetSqlType)
throws java.sql.SQLException
setObject in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setObject(java.lang.String parameterName,
java.lang.Object x)
throws java.sql.SQLException
setObject in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setCharacterStream(java.lang.String parameterName,
java.io.Reader x,
int length)
throws java.sql.SQLException
setCharacterStream in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setDate(java.lang.String parameterName,
java.sql.Date x,
java.util.Calendar cal)
throws java.sql.SQLException
setDate in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setTime(java.lang.String parameterName,
java.sql.Time x,
java.util.Calendar cal)
throws java.sql.SQLException
setTime in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setTimestamp(java.lang.String parameterName,
java.sql.Timestamp x,
java.util.Calendar cal)
throws java.sql.SQLException
setTimestamp in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public void setNull(java.lang.String parameterName,
int sqlType,
java.lang.String typeName)
throws java.sql.SQLException
setNull in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.lang.String getString(java.lang.String parameterName)
throws java.sql.SQLException
getString in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public boolean getBoolean(java.lang.String parameterName)
throws java.sql.SQLException
getBoolean in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public byte getByte(java.lang.String parameterName)
throws java.sql.SQLException
getByte in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public short getShort(java.lang.String parameterName)
throws java.sql.SQLException
getShort in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public int getInt(java.lang.String parameterName)
throws java.sql.SQLException
getInt in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public long getLong(java.lang.String parameterName)
throws java.sql.SQLException
getLong in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public float getFloat(java.lang.String parameterName)
throws java.sql.SQLException
getFloat in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public double getDouble(java.lang.String parameterName)
throws java.sql.SQLException
getDouble in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public byte[] getBytes(java.lang.String parameterName)
throws java.sql.SQLException
getBytes in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.sql.Date getDate(java.lang.String parameterName)
throws java.sql.SQLException
getDate in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.sql.Time getTime(java.lang.String parameterName)
throws java.sql.SQLException
getTime in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.sql.Timestamp getTimestamp(java.lang.String parameterName)
throws java.sql.SQLException
getTimestamp in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.lang.Object getObject(java.lang.String parameterName)
throws java.sql.SQLException
getObject in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.math.BigDecimal getBigDecimal(java.lang.String parameterName)
throws java.sql.SQLException
getBigDecimal in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.lang.Object getObject(java.lang.String parameterName,
java.util.Map map)
throws java.sql.SQLException
getObject in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.sql.Ref getRef(java.lang.String parameterName)
throws java.sql.SQLException
getRef in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.sql.Blob getBlob(java.lang.String parameterName)
throws java.sql.SQLException
getBlob in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.sql.Clob getClob(java.lang.String parameterName)
throws java.sql.SQLException
getClob in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.sql.Array getArray(java.lang.String parameterName)
throws java.sql.SQLException
getArray in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.sql.Date getDate(java.lang.String parameterName,
java.util.Calendar cal)
throws java.sql.SQLException
getDate in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.sql.Time getTime(java.lang.String parameterName,
java.util.Calendar cal)
throws java.sql.SQLException
getTime in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.sql.Timestamp getTimestamp(java.lang.String parameterName,
java.util.Calendar cal)
throws java.sql.SQLException
getTimestamp in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
public java.net.URL getURL(java.lang.String parameterName)
throws java.sql.SQLException
getURL in interface java.sql.CallableStatementjava.sql.SQLException - if an error occurs
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbcx.proxy.StatementProxy
net.sourceforge.jtds.jdbcx.proxy.PreparedStatementProxy
This class would be better implemented as a java.lang.reflect.Proxy. However, this feature was not added until 1.3 and reflection performance was not improved until 1.4. Since the driver still needs to be compatible with 1.2 and 1.3 this class is used to delegate the calls to a prepared statement with minimal overhead.
| Field Summary | |
private JtdsPreparedStatement |
_preparedStatement
|
| Fields inherited from class net.sourceforge.jtds.jdbcx.proxy.StatementProxy |
|
| Fields inherited from interface java.sql.Statement |
CLOSE_ALL_RESULTS, CLOSE_CURRENT_RESULT, EXECUTE_FAILED, KEEP_CURRENT_RESULT, NO_GENERATED_KEYS, RETURN_GENERATED_KEYS, SUCCESS_NO_INFO |
| Constructor Summary | |
(package private) |
PreparedStatementProxy(ConnectionProxy connection,
JtdsPreparedStatement preparedStatement)
|
| Method Summary | |
void |
addBatch()
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
clearParameters()
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
boolean |
execute()
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
java.sql.ResultSet |
executeQuery()
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
int |
executeUpdate()
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
java.sql.ResultSetMetaData |
getMetaData()
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
java.sql.ParameterMetaData |
getParameterMetaData()
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setArray(int parameterIndex,
java.sql.Array x)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setAsciiStream(int parameterIndex,
java.io.InputStream x,
int length)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setBigDecimal(int parameterIndex,
java.math.BigDecimal x)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setBinaryStream(int parameterIndex,
java.io.InputStream x,
int length)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setBlob(int parameterIndex,
java.sql.Blob x)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setBoolean(int parameterIndex,
boolean x)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setByte(int parameterIndex,
byte x)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setBytes(int parameterIndex,
byte[] x)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setCharacterStream(int parameterIndex,
java.io.Reader x,
int length)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setClob(int parameterIndex,
java.sql.Clob x)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setDate(int parameterIndex,
java.sql.Date x)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setDate(int parameterIndex,
java.sql.Date x,
java.util.Calendar cal)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setDouble(int parameterIndex,
double x)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setFloat(int parameterIndex,
float x)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setInt(int parameterIndex,
int x)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setLong(int parameterIndex,
long x)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setNull(int parameterIndex,
int sqlType)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setNull(int parameterIndex,
int sqlType,
java.lang.String typeName)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setObject(int parameterIndex,
java.lang.Object x)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setObject(int parameterIndex,
java.lang.Object x,
int targetSqlType)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setObject(int parameterIndex,
java.lang.Object x,
int targetSqlType,
int scale)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setRef(int parameterIndex,
java.sql.Ref x)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setShort(int parameterIndex,
short x)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setString(int parameterIndex,
java.lang.String x)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setTime(int parameterIndex,
java.sql.Time x)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setTime(int parameterIndex,
java.sql.Time x,
java.util.Calendar cal)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setTimestamp(int parameterIndex,
java.sql.Timestamp x)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setTimestamp(int parameterIndex,
java.sql.Timestamp x,
java.util.Calendar cal)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setUnicodeStream(int parameterIndex,
java.io.InputStream x,
int length)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
void |
setURL(int parameterIndex,
java.net.URL x)
Delgates calls to the prepared statement; SQLExceptions thrown from the prepared statement will cause an event to be fired on the connection pool listeners. |
| Methods inherited from class net.sourceforge.jtds.jdbcx.proxy.StatementProxy |
addBatch, cancel, clearBatch, clearWarnings, close, execute, execute, execute, execute, executeBatch, executeQuery, executeUpdate, executeUpdate, executeUpdate, executeUpdate, getConnection, getFetchDirection, getFetchSize, getGeneratedKeys, getMaxFieldSize, getMaxRows, getMoreResults, getMoreResults, getQueryTimeout, getResultSet, getResultSetConcurrency, getResultSetHoldability, getResultSetType, getUpdateCount, getWarnings, processSQLException, setCursorName, setEscapeProcessing, setFetchDirection, setFetchSize, setMaxFieldSize, setMaxRows, setQueryTimeout, validateConnection |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Methods inherited from interface java.sql.Statement |
addBatch, cancel, clearBatch, clearWarnings, close, execute, execute, execute, execute, executeBatch, executeQuery, executeUpdate, executeUpdate, executeUpdate, executeUpdate, getConnection, getFetchDirection, getFetchSize, getGeneratedKeys, getMaxFieldSize, getMaxRows, getMoreResults, getMoreResults, getQueryTimeout, getResultSet, getResultSetConcurrency, getResultSetHoldability, getResultSetType, getUpdateCount, getWarnings, setCursorName, setEscapeProcessing, setFetchDirection, setFetchSize, setMaxFieldSize, setMaxRows, setQueryTimeout |
| Field Detail |
private JtdsPreparedStatement _preparedStatement
| Constructor Detail |
PreparedStatementProxy(ConnectionProxy connection, JtdsPreparedStatement preparedStatement)
| Method Detail |
public java.sql.ResultSet executeQuery()
throws java.sql.SQLException
executeQuery in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public int executeUpdate()
throws java.sql.SQLException
executeUpdate in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setNull(int parameterIndex,
int sqlType)
throws java.sql.SQLException
setNull in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setBoolean(int parameterIndex,
boolean x)
throws java.sql.SQLException
setBoolean in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setByte(int parameterIndex,
byte x)
throws java.sql.SQLException
setByte in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setShort(int parameterIndex,
short x)
throws java.sql.SQLException
setShort in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setInt(int parameterIndex,
int x)
throws java.sql.SQLException
setInt in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setLong(int parameterIndex,
long x)
throws java.sql.SQLException
setLong in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setFloat(int parameterIndex,
float x)
throws java.sql.SQLException
setFloat in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setDouble(int parameterIndex,
double x)
throws java.sql.SQLException
setDouble in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setBigDecimal(int parameterIndex,
java.math.BigDecimal x)
throws java.sql.SQLException
setBigDecimal in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setString(int parameterIndex,
java.lang.String x)
throws java.sql.SQLException
setString in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setBytes(int parameterIndex,
byte[] x)
throws java.sql.SQLException
setBytes in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setDate(int parameterIndex,
java.sql.Date x)
throws java.sql.SQLException
setDate in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setTime(int parameterIndex,
java.sql.Time x)
throws java.sql.SQLException
setTime in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setTimestamp(int parameterIndex,
java.sql.Timestamp x)
throws java.sql.SQLException
setTimestamp in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setAsciiStream(int parameterIndex,
java.io.InputStream x,
int length)
throws java.sql.SQLException
setAsciiStream in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setUnicodeStream(int parameterIndex,
java.io.InputStream x,
int length)
throws java.sql.SQLException
setUnicodeStream in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setBinaryStream(int parameterIndex,
java.io.InputStream x,
int length)
throws java.sql.SQLException
setBinaryStream in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void clearParameters()
throws java.sql.SQLException
clearParameters in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setObject(int parameterIndex,
java.lang.Object x,
int targetSqlType,
int scale)
throws java.sql.SQLException
setObject in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setObject(int parameterIndex,
java.lang.Object x,
int targetSqlType)
throws java.sql.SQLException
setObject in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setObject(int parameterIndex,
java.lang.Object x)
throws java.sql.SQLException
setObject in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public boolean execute()
throws java.sql.SQLException
execute in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void addBatch()
throws java.sql.SQLException
addBatch in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setCharacterStream(int parameterIndex,
java.io.Reader x,
int length)
throws java.sql.SQLException
setCharacterStream in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setRef(int parameterIndex,
java.sql.Ref x)
throws java.sql.SQLException
setRef in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setBlob(int parameterIndex,
java.sql.Blob x)
throws java.sql.SQLException
setBlob in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setClob(int parameterIndex,
java.sql.Clob x)
throws java.sql.SQLException
setClob in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setArray(int parameterIndex,
java.sql.Array x)
throws java.sql.SQLException
setArray in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public java.sql.ResultSetMetaData getMetaData()
throws java.sql.SQLException
getMetaData in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setDate(int parameterIndex,
java.sql.Date x,
java.util.Calendar cal)
throws java.sql.SQLException
setDate in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setTime(int parameterIndex,
java.sql.Time x,
java.util.Calendar cal)
throws java.sql.SQLException
setTime in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setTimestamp(int parameterIndex,
java.sql.Timestamp x,
java.util.Calendar cal)
throws java.sql.SQLException
setTimestamp in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setNull(int parameterIndex,
int sqlType,
java.lang.String typeName)
throws java.sql.SQLException
setNull in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public void setURL(int parameterIndex,
java.net.URL x)
throws java.sql.SQLException
setURL in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
public java.sql.ParameterMetaData getParameterMetaData()
throws java.sql.SQLException
getParameterMetaData in interface java.sql.PreparedStatementjava.sql.SQLException - if an error occurs
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV PACKAGE NEXT PACKAGE | FRAMES NO FRAMES | ||||||||||
| Class Summary | |
| JtdsDataSource | The jTDS DataSource, ConnectionPoolDataSource and
XADataSource implementation. |
| JtdsObjectFactory | Description |
| JtdsXAConnection | jTDS implementation of the XAConnection interface. |
| JtdsXAResource | jTDS implementation of the XAResource interface. |
| JtdsXid | jTDS implementation of the Xid interface. |
| PooledConnection | jTDS implementation of the PooledConnection interface. |
|
|||||||||||
| PREV PACKAGE NEXT PACKAGE | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbcx.JtdsXid
jTDS implementation of the Xid interface.
| Field Summary | |
private byte[] |
bqual
The branch qualifier ID. |
int |
fmtId
The format ID. |
private byte[] |
gtran
The global transaction ID. |
int |
hash
Precalculated hash value. |
static int |
XID_SIZE
The size of an XID in bytes. |
| Fields inherited from interface javax.transaction.xa.Xid |
MAXBQUALSIZE, MAXGTRIDSIZE |
| Constructor Summary | |
JtdsXid(byte[] global,
byte[] branch)
Construct an XID using two byte arrays. |
|
JtdsXid(byte[] buf,
int pos)
Construct an XID using an offset into a byte buffer. |
|
JtdsXid(javax.transaction.xa.Xid xid)
Construct an XID as a clone of another XID. |
|
| Method Summary | |
private void |
calculateHash()
|
boolean |
equals(java.lang.Object obj)
Test for equality. |
byte[] |
getBranchQualifier()
|
int |
getFormatId()
|
byte[] |
getGlobalTransactionId()
|
int |
hashCode()
Get the hash code for this object. |
java.lang.String |
toString()
|
| Methods inherited from class java.lang.Object |
clone, finalize, getClass, notify, notifyAll, wait, wait, wait |
| Field Detail |
public static final int XID_SIZE
private final byte[] gtran
private final byte[] bqual
public final int fmtId
public int hash
| Constructor Detail |
public JtdsXid(byte[] buf,
int pos)
buf - the byte bufferpos - the offset
public JtdsXid(byte[] global,
byte[] branch)
global - the global transaction idbranch - the transaction branchpublic JtdsXid(javax.transaction.xa.Xid xid)
| Method Detail |
private void calculateHash()
public int hashCode()
intpublic boolean equals(java.lang.Object obj)
obj - the object to test for equality with this
boolean true if the parameter equals thispublic int getFormatId()
getFormatId in interface javax.transaction.xa.Xidpublic byte[] getBranchQualifier()
getBranchQualifier in interface javax.transaction.xa.Xidpublic byte[] getGlobalTransactionId()
getGlobalTransactionId in interface javax.transaction.xa.Xidpublic java.lang.String toString()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbcx.JtdsXAResource
jTDS implementation of the XAResource interface.
| Field Summary | |
private java.sql.Connection |
connection
|
private java.lang.String |
rmHost
|
private JtdsXAConnection |
xaConnection
|
| Fields inherited from interface javax.transaction.xa.XAResource |
TMENDRSCAN, TMFAIL, TMJOIN, TMNOFLAGS, TMONEPHASE, TMRESUME, TMSTARTRSCAN, TMSUCCESS, TMSUSPEND, XA_OK, XA_RDONLY |
| Constructor Summary | |
JtdsXAResource(JtdsXAConnection xaConnection,
java.sql.Connection connection)
|
|
| Method Summary | |
void |
commit(javax.transaction.xa.Xid xid,
boolean commit)
|
void |
end(javax.transaction.xa.Xid xid,
int flags)
|
void |
forget(javax.transaction.xa.Xid xid)
|
protected JtdsXAConnection |
getResourceManager()
|
protected java.lang.String |
getRmHost()
|
int |
getTransactionTimeout()
|
boolean |
isSameRM(javax.transaction.xa.XAResource xares)
|
int |
prepare(javax.transaction.xa.Xid xid)
|
javax.transaction.xa.Xid[] |
recover(int flags)
|
void |
rollback(javax.transaction.xa.Xid xid)
|
boolean |
setTransactionTimeout(int arg0)
|
void |
start(javax.transaction.xa.Xid xid,
int flags)
|
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private final java.sql.Connection connection
private final JtdsXAConnection xaConnection
private final java.lang.String rmHost
| Constructor Detail |
public JtdsXAResource(JtdsXAConnection xaConnection, java.sql.Connection connection)
| Method Detail |
protected JtdsXAConnection getResourceManager()
protected java.lang.String getRmHost()
public int getTransactionTimeout()
throws javax.transaction.xa.XAException
getTransactionTimeout in interface javax.transaction.xa.XAResourcejavax.transaction.xa.XAException
public boolean setTransactionTimeout(int arg0)
throws javax.transaction.xa.XAException
setTransactionTimeout in interface javax.transaction.xa.XAResourcejavax.transaction.xa.XAException
public boolean isSameRM(javax.transaction.xa.XAResource xares)
throws javax.transaction.xa.XAException
isSameRM in interface javax.transaction.xa.XAResourcejavax.transaction.xa.XAException
public javax.transaction.xa.Xid[] recover(int flags)
throws javax.transaction.xa.XAException
recover in interface javax.transaction.xa.XAResourcejavax.transaction.xa.XAException
public int prepare(javax.transaction.xa.Xid xid)
throws javax.transaction.xa.XAException
prepare in interface javax.transaction.xa.XAResourcejavax.transaction.xa.XAException
public void forget(javax.transaction.xa.Xid xid)
throws javax.transaction.xa.XAException
forget in interface javax.transaction.xa.XAResourcejavax.transaction.xa.XAException
public void rollback(javax.transaction.xa.Xid xid)
throws javax.transaction.xa.XAException
rollback in interface javax.transaction.xa.XAResourcejavax.transaction.xa.XAException
public void end(javax.transaction.xa.Xid xid,
int flags)
throws javax.transaction.xa.XAException
end in interface javax.transaction.xa.XAResourcejavax.transaction.xa.XAException
public void start(javax.transaction.xa.Xid xid,
int flags)
throws javax.transaction.xa.XAException
start in interface javax.transaction.xa.XAResourcejavax.transaction.xa.XAException
public void commit(javax.transaction.xa.Xid xid,
boolean commit)
throws javax.transaction.xa.XAException
commit in interface javax.transaction.xa.XAResourcejavax.transaction.xa.XAException
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
| Packages that use net.sourceforge.jtds.jdbcx | |
| net.sourceforge.jtds.jdbcx | |
| net.sourceforge.jtds.jdbcx.proxy | |
| Classes in net.sourceforge.jtds.jdbcx used by net.sourceforge.jtds.jdbcx | |
| JtdsDataSource
The jTDS DataSource, ConnectionPoolDataSource and
XADataSource implementation. |
|
| JtdsXAConnection
jTDS implementation of the XAConnection interface. |
|
| PooledConnection
jTDS implementation of the PooledConnection interface. |
|
| Classes in net.sourceforge.jtds.jdbcx used by net.sourceforge.jtds.jdbcx.proxy | |
| PooledConnection
jTDS implementation of the PooledConnection interface. |
|
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbcx.PooledConnection
jTDS implementation of the PooledConnection interface.
| Field Summary | |
protected java.sql.Connection |
connection
|
private java.util.ArrayList |
listeners
|
| Constructor Summary | |
PooledConnection(java.sql.Connection connection)
|
|
| Method Summary | |
void |
addConnectionEventListener(javax.sql.ConnectionEventListener listener)
Adds the specified listener to the list. |
void |
close()
Closes the database connection. |
void |
fireConnectionEvent(boolean closed,
java.sql.SQLException sqlException)
Fires a new connection event on all listeners. |
java.sql.Connection |
getConnection()
Returns a ConnectionProxy. |
void |
removeConnectionEventListener(javax.sql.ConnectionEventListener listener)
Removes the specified listener from the list. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
private java.util.ArrayList listeners
protected java.sql.Connection connection
| Constructor Detail |
public PooledConnection(java.sql.Connection connection)
| Method Detail |
public void addConnectionEventListener(javax.sql.ConnectionEventListener listener)
addConnectionEventListener in interface javax.sql.PooledConnection
public void close()
throws java.sql.SQLException
close in interface javax.sql.PooledConnectionjava.sql.SQLException - if an error occurs
public void fireConnectionEvent(boolean closed,
java.sql.SQLException sqlException)
closed - true if close has been called on the
connection; false if the sqlException represents
an error where the connection may not longer be used.sqlException - the SQLException to pass to the listeners
public java.sql.Connection getConnection()
throws java.sql.SQLException
getConnection in interface javax.sql.PooledConnectionjava.sql.SQLException - if an error occurspublic void removeConnectionEventListener(javax.sql.ConnectionEventListener listener)
removeConnectionEventListener in interface javax.sql.PooledConnection
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbcx.JtdsDataSource
The jTDS DataSource, ConnectionPoolDataSource and
XADataSource implementation.
| Field Summary | |
protected java.lang.String |
appName
|
protected java.lang.String |
batchSize
|
protected java.lang.String |
bindAddress
|
protected java.lang.String |
bufferDir
|
protected java.lang.String |
bufferMaxMemory
|
protected java.lang.String |
bufferMinPackets
|
protected java.lang.String |
cacheMetaData
|
protected java.lang.String |
charset
|
protected java.lang.String |
databaseName
|
protected java.lang.String |
description
|
protected java.lang.String |
domain
|
private static Driver |
driver
Driver instance used for obtaining connections. |
protected java.lang.String |
instance
|
protected java.lang.String |
language
|
protected java.lang.String |
lastUpdateCount
|
protected java.lang.String |
lobBuffer
|
protected java.lang.String |
logFile
|
protected java.lang.String |
loginTimeout
|
protected java.lang.String |
macAddress
|
protected java.lang.String |
maxStatements
|
protected java.lang.String |
namedPipe
|
protected java.lang.String |
packetSize
|
protected java.lang.String |
password
|
protected java.lang.String |
portNumber
|
protected java.lang.String |
prepareSql
|
protected java.lang.String |
processId
|
protected java.lang.String |
progName
|
protected java.lang.String |
sendStringParametersAsUnicode
|
(package private) static long |
serialVersionUID
Serial version UID. |
protected java.lang.String |
serverName
|
protected java.lang.String |
serverType
|
protected java.lang.String |
socketKeepAlive
|
protected java.lang.String |
socketTimeout
|
protected java.lang.String |
ssl
|
protected java.lang.String |
tcpNoDelay
|
protected java.lang.String |
tdsVersion
|
protected java.lang.String |
useCursors
|
protected java.lang.String |
useJCIFS
|
protected java.lang.String |
useLOBs
|
protected java.lang.String |
useNTLMV2
|
protected java.lang.String |
user
|
protected java.lang.String |
wsid
|
protected java.lang.String |
xaEmulation
|
| Constructor Summary | |
JtdsDataSource()
Constructs a new datasource. |
|
| Method Summary | |
private void |
addNonNullProperties(java.util.Properties props,
java.lang.String user,
java.lang.String password)
|
java.lang.String |
getAppName()
|
int |
getBatchSize()
|
java.lang.String |
getBindAddress()
|
java.lang.String |
getBufferDir()
|
int |
getBufferMaxMemory()
|
int |
getBufferMinPackets()
|
boolean |
getCacheMetaData()
|
java.lang.String |
getCharset()
|
java.sql.Connection |
getConnection()
Returns a new database connection. |
java.sql.Connection |
getConnection(java.lang.String user,
java.lang.String password)
Returns a new database connection for the user and password specified. |
java.lang.String |
getDatabaseName()
|
java.lang.String |
getDescription()
|
java.lang.String |
getDomain()
|
java.lang.String |
getInstance()
|
java.lang.String |
getLanguage()
|
boolean |
getLastUpdateCount()
|
long |
getLobBuffer()
|
java.lang.String |
getLogFile()
|
int |
getLoginTimeout()
|
java.io.PrintWriter |
getLogWriter()
|
java.lang.String |
getMacAddress()
|
int |
getMaxStatements()
|
boolean |
getNamedPipe()
|
int |
getPacketSize()
|
java.lang.String |
getPassword()
|
javax.sql.PooledConnection |
getPooledConnection()
Returns a new pooled database connection. |
javax.sql.PooledConnection |
getPooledConnection(java.lang.String user,
java.lang.String password)
Returns a new pooled database connection for the user and password specified. |
int |
getPortNumber()
|
int |
getPrepareSql()
|
java.lang.String |
getProcessId()
|
java.lang.String |
getProgName()
|
javax.naming.Reference |
getReference()
|
boolean |
getSendStringParametersAsUnicode()
|
java.lang.String |
getServerName()
|
int |
getServerType()
|
boolean |
getSocketKeepAlive()
|
int |
getSocketTimeout()
|
java.lang.String |
getSsl()
|
boolean |
getTcpNoDelay()
|
java.lang.String |
getTds()
|
boolean |
getUseCursors()
|
boolean |
getUseJCIFS()
|
boolean |
getUseLOBs()
|
java.lang.String |
getUseNTLMV2()
|
java.lang.String |
getUser()
|
java.lang.String |
getWsid()
|
javax.sql.XAConnection |
getXAConnection()
Returns a new XA database connection. |
javax.sql.XAConnection |
getXAConnection(java.lang.String user,
java.lang.String password)
Returns a new XA database connection for the user and password specified. |
boolean |
getXaEmulation()
|
void |
setAppName(java.lang.String appName)
|
void |
setBatchSize(int batchSize)
|
void |
setBindAddress(java.lang.String bindAddress)
|
void |
setBufferDir(java.lang.String bufferDir)
|
void |
setBufferMaxMemory(int bufferMaxMemory)
|
void |
setBufferMinPackets(int bufferMinPackets)
|
void |
setCacheMetaData(boolean cacheMetaData)
|
void |
setCharset(java.lang.String charset)
|
void |
setDatabaseName(java.lang.String databaseName)
|
void |
setDescription(java.lang.String description)
|
void |
setDomain(java.lang.String domain)
|
void |
setInstance(java.lang.String instance)
|
void |
setLanguage(java.lang.String language)
|
void |
setLastUpdateCount(boolean lastUpdateCount)
|
void |
setLobBuffer(long lobBuffer)
|
void |
setLogFile(java.lang.String logFile)
|
void |
setLoginTimeout(int loginTimeout)
|
void |
setLogWriter(java.io.PrintWriter out)
|
void |
setMacAddress(java.lang.String macAddress)
|
void |
setMaxStatements(int maxStatements)
|
void |
setNamedPipe(boolean namedPipe)
|
void |
setPacketSize(int packetSize)
|
void |
setPassword(java.lang.String password)
|
void |
setPortNumber(int portNumber)
|
void |
setPrepareSql(int prepareSql)
|
void |
setProcessId(java.lang.String processId)
|
void |
setProgName(java.lang.String progName)
|
void |
setSendStringParametersAsUnicode(boolean sendStringParametersAsUnicode)
|
void |
setServerName(java.lang.String serverName)
|
void |
setServerType(int serverType)
|
void |
setSocketKeepAlive(boolean socketKeepAlive)
|
void |
setSocketTimeout(int socketTimeout)
|
void |
setSsl(java.lang.String ssl)
|
void |
setTcpNoDelay(boolean tcpNoDelay)
|
void |
setTds(java.lang.String tds)
|
void |
setUseCursors(boolean useCursors)
|
void |
setUseJCIFS(boolean useJCIFS)
|
void |
setUseLOBs(boolean useLOBs)
|
void |
setUseNTLMV2(java.lang.String usentlmv2)
|
void |
setUser(java.lang.String user)
|
void |
setWsid(java.lang.String wsid)
|
void |
setXaEmulation(boolean xaEmulation)
|
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
static final long serialVersionUID
protected java.lang.String serverName
protected java.lang.String serverType
protected java.lang.String portNumber
protected java.lang.String databaseName
protected java.lang.String tdsVersion
protected java.lang.String charset
protected java.lang.String language
protected java.lang.String domain
protected java.lang.String useNTLMV2
protected java.lang.String instance
protected java.lang.String lastUpdateCount
protected java.lang.String sendStringParametersAsUnicode
protected java.lang.String namedPipe
protected java.lang.String macAddress
protected java.lang.String prepareSql
protected java.lang.String packetSize
protected java.lang.String tcpNoDelay
protected java.lang.String user
protected java.lang.String password
protected java.lang.String loginTimeout
protected java.lang.String lobBuffer
protected java.lang.String maxStatements
protected java.lang.String appName
protected java.lang.String progName
protected java.lang.String wsid
protected java.lang.String xaEmulation
protected java.lang.String logFile
protected java.lang.String socketTimeout
protected java.lang.String socketKeepAlive
protected java.lang.String processId
protected java.lang.String ssl
protected java.lang.String batchSize
protected java.lang.String bufferDir
protected java.lang.String bufferMaxMemory
protected java.lang.String bufferMinPackets
protected java.lang.String cacheMetaData
protected java.lang.String useCursors
protected java.lang.String useLOBs
protected java.lang.String bindAddress
protected java.lang.String useJCIFS
protected java.lang.String description
private static final Driver driver
| Constructor Detail |
public JtdsDataSource()
| Method Detail |
public javax.sql.XAConnection getXAConnection()
throws java.sql.SQLException
getXAConnection in interface javax.sql.XADataSourcejava.sql.SQLException - if an error occurs
public javax.sql.XAConnection getXAConnection(java.lang.String user,
java.lang.String password)
throws java.sql.SQLException
getXAConnection in interface javax.sql.XADataSourceuser - the user name to connect withpassword - the password to connect with
java.sql.SQLException - if an error occurs
public java.sql.Connection getConnection()
throws java.sql.SQLException
getConnection in interface javax.sql.DataSourcejava.sql.SQLException - if an error occurs
public java.sql.Connection getConnection(java.lang.String user,
java.lang.String password)
throws java.sql.SQLException
getConnection in interface javax.sql.DataSourceuser - the user name to connect withpassword - the password to connect with
java.sql.SQLException - if an error occurs
public javax.naming.Reference getReference()
throws javax.naming.NamingException
getReference in interface javax.naming.Referenceablejavax.naming.NamingException
public javax.sql.PooledConnection getPooledConnection()
throws java.sql.SQLException
getPooledConnection in interface javax.sql.ConnectionPoolDataSourcejava.sql.SQLException - if an error occurs
public javax.sql.PooledConnection getPooledConnection(java.lang.String user,
java.lang.String password)
throws java.sql.SQLException
getPooledConnection in interface javax.sql.ConnectionPoolDataSourceuser - the user name to connect withpassword - the password to connect with
java.sql.SQLException - if an error occurs
public java.io.PrintWriter getLogWriter()
throws java.sql.SQLException
getLogWriter in interface javax.sql.DataSourcejava.sql.SQLException
public void setLogWriter(java.io.PrintWriter out)
throws java.sql.SQLException
setLogWriter in interface javax.sql.DataSourcejava.sql.SQLException
public void setLoginTimeout(int loginTimeout)
throws java.sql.SQLException
setLoginTimeout in interface javax.sql.DataSourcejava.sql.SQLException
public int getLoginTimeout()
throws java.sql.SQLException
getLoginTimeout in interface javax.sql.DataSourcejava.sql.SQLException
public void setSocketTimeout(int socketTimeout)
throws java.sql.SQLException
java.sql.SQLException
public void setSocketKeepAlive(boolean socketKeepAlive)
throws java.sql.SQLException
java.sql.SQLException
public void setProcessId(java.lang.String processId)
throws java.sql.SQLException
java.sql.SQLException
public int getSocketTimeout()
throws java.sql.SQLException
java.sql.SQLException
public boolean getSocketKeepAlive()
throws java.sql.SQLException
java.sql.SQLException
public java.lang.String getProcessId()
throws java.sql.SQLException
java.sql.SQLExceptionpublic void setDatabaseName(java.lang.String databaseName)
public java.lang.String getDatabaseName()
public void setDescription(java.lang.String description)
public java.lang.String getDescription()
public void setPassword(java.lang.String password)
public java.lang.String getPassword()
public void setPortNumber(int portNumber)
public int getPortNumber()
public void setServerName(java.lang.String serverName)
public java.lang.String getServerName()
public void setUser(java.lang.String user)
public java.lang.String getUser()
public void setTds(java.lang.String tds)
public java.lang.String getTds()
public void setServerType(int serverType)
public int getServerType()
public java.lang.String getDomain()
public void setDomain(java.lang.String domain)
public java.lang.String getUseNTLMV2()
public void setUseNTLMV2(java.lang.String usentlmv2)
public java.lang.String getInstance()
public void setInstance(java.lang.String instance)
public boolean getSendStringParametersAsUnicode()
public void setSendStringParametersAsUnicode(boolean sendStringParametersAsUnicode)
public boolean getNamedPipe()
public void setNamedPipe(boolean namedPipe)
public boolean getLastUpdateCount()
public void setLastUpdateCount(boolean lastUpdateCount)
public boolean getXaEmulation()
public void setXaEmulation(boolean xaEmulation)
public java.lang.String getCharset()
public void setCharset(java.lang.String charset)
public java.lang.String getLanguage()
public void setLanguage(java.lang.String language)
public java.lang.String getMacAddress()
public void setMacAddress(java.lang.String macAddress)
public void setPacketSize(int packetSize)
public int getPacketSize()
public boolean getTcpNoDelay()
public void setTcpNoDelay(boolean tcpNoDelay)
public void setPrepareSql(int prepareSql)
public int getPrepareSql()
public void setLobBuffer(long lobBuffer)
public long getLobBuffer()
public void setMaxStatements(int maxStatements)
public int getMaxStatements()
public void setAppName(java.lang.String appName)
public java.lang.String getAppName()
public void setProgName(java.lang.String progName)
public java.lang.String getProgName()
public void setWsid(java.lang.String wsid)
public java.lang.String getWsid()
public void setLogFile(java.lang.String logFile)
public java.lang.String getLogFile()
public void setSsl(java.lang.String ssl)
public java.lang.String getSsl()
public void setBatchSize(int batchSize)
public int getBatchSize()
public java.lang.String getBufferDir()
public void setBufferDir(java.lang.String bufferDir)
public int getBufferMaxMemory()
public void setBufferMaxMemory(int bufferMaxMemory)
public int getBufferMinPackets()
public void setBufferMinPackets(int bufferMinPackets)
public boolean getCacheMetaData()
public void setCacheMetaData(boolean cacheMetaData)
public boolean getUseCursors()
public void setUseCursors(boolean useCursors)
public boolean getUseLOBs()
public void setUseLOBs(boolean useLOBs)
public java.lang.String getBindAddress()
public void setBindAddress(java.lang.String bindAddress)
public boolean getUseJCIFS()
public void setUseJCIFS(boolean useJCIFS)
private void addNonNullProperties(java.util.Properties props,
java.lang.String user,
java.lang.String password)
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
Classes
JtdsDataSource JtdsObjectFactory JtdsXAConnection JtdsXAResource JtdsXid PooledConnection |
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
java.lang.Objectnet.sourceforge.jtds.jdbcx.PooledConnection
net.sourceforge.jtds.jdbcx.JtdsXAConnection
jTDS implementation of the XAConnection interface.
| Field Summary | |
private JtdsDataSource |
dataSource
|
private javax.transaction.xa.XAResource |
resource
The XAResource used by the transaction manager to control this connection. |
private int |
xaConnectionId
|
| Fields inherited from class net.sourceforge.jtds.jdbcx.PooledConnection |
connection |
| Constructor Summary | |
JtdsXAConnection(JtdsDataSource dataSource,
java.sql.Connection connection)
Construct a new XAConnection object. |
|
| Method Summary | |
void |
close()
Closes the database connection. |
(package private) int |
getXAConnectionID()
Retrieves the XA Connection ID to pass to server. |
protected JtdsDataSource |
getXADataSource()
|
javax.transaction.xa.XAResource |
getXAResource()
|
| Methods inherited from class net.sourceforge.jtds.jdbcx.PooledConnection |
addConnectionEventListener, fireConnectionEvent, getConnection, removeConnectionEventListener |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Methods inherited from interface javax.sql.PooledConnection |
addConnectionEventListener, getConnection, removeConnectionEventListener |
| Field Detail |
private final javax.transaction.xa.XAResource resource
private final JtdsDataSource dataSource
private final int xaConnectionId
| Constructor Detail |
public JtdsXAConnection(JtdsDataSource dataSource, java.sql.Connection connection) throws java.sql.SQLException
XAConnection object.
dataSource - the parent DataSource objectconnection - the real database connection| Method Detail |
int getXAConnectionID()
Integer
public javax.transaction.xa.XAResource getXAResource()
throws java.sql.SQLException
getXAResource in interface javax.sql.XAConnectionjava.sql.SQLException
public void close()
throws java.sql.SQLException
PooledConnection
close in interface javax.sql.PooledConnectionclose in class PooledConnectionjava.sql.SQLException - if an error occursprotected JtdsDataSource getXADataSource()
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
|
|||||||||||
| PREV NEXT | FRAMES NO FRAMES | ||||||||||
SSLSocketFactory
*/
private SSLSocketFactory getFactory() throws IOException {
try {
if (Ssl.SSL_AUTHENTICATE.equals(ssl)) {
// the default factory will produce a socket that authenticates
// the server using its certificate chain.
return (SSLSocketFactory) SSLSocketFactory.getDefault();
} else {
// Our custom factory will not authenticate the server.
return factory();
}
} catch (GeneralSecurityException e) {
Logger.logException(e);
throw new IOException(e.getMessage());
}
}
/**
* Returns an SSLSocketFactory whose sockets will not authenticate the
* server.
*
* @return an SSLSocketFactory
*/
private static SSLSocketFactory factory()
throws NoSuchAlgorithmException, KeyManagementException {
if (factorySingleton == null) {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, trustManagers(), null);
factorySingleton = ctx.getSocketFactory();
}
return factorySingleton;
}
private static TrustManager[] trustManagers() {
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkServerTrusted(X509Certificate[] chain, String x) {
// Dummy method
}
public void checkClientTrusted(X509Certificate[] chain, String x) {
// Dummy method
}
};
return new X509TrustManager[]{tm};
}
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/ssl/TdsTlsOutputStream.java 0000644 0001750 0001750 00000015037 11316672660 027462 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
//Copyright (C) 2004 The jTDS Project
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.ssl;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.jtds.jdbc.TdsCore;
/**
* An output stream that mediates between JSSE and the DB server.
*
* SQL Server 2000 has the following requirements:
* SSLSocketFactory
*/
private SSLSocketFactory getFactory() throws IOException {
try {
if (Ssl.SSL_AUTHENTICATE.equals(ssl)) {
// the default factory will produce a socket that authenticates
// the server using its certificate chain.
return (SSLSocketFactory) SSLSocketFactory.getDefault();
} else {
// Our custom factory will not authenticate the server.
return factory();
}
} catch (GeneralSecurityException e) {
Logger.logException(e);
throw new IOException(e.getMessage());
}
}
/**
* Returns an SSLSocketFactory whose sockets will not authenticate the
* server.
*
* @return an SSLSocketFactory
*/
private static SSLSocketFactory factory()
throws NoSuchAlgorithmException, KeyManagementException {
if (factorySingleton == null) {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, trustManagers(), null);
factorySingleton = ctx.getSocketFactory();
}
return factorySingleton;
}
private static TrustManager[] trustManagers() {
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public boolean isClientTrusted(X509Certificate[] chain) {
return true;
}
public boolean isServerTrusted(X509Certificate[] chain) {
return true;
}
};
return new X509TrustManager[]{tm};
}
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/ssl/TdsTlsInputStream.java 0000644 0001750 0001750 00000011414 11316672660 027254 0 ustar martin martin //jTDS JDBC Driver for Microsoft SQL Server and Sybase
//Copyright (C) 2004 The jTDS Project
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.ssl;
import java.io.ByteArrayInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import net.sourceforge.jtds.jdbc.TdsCore;
/**
* An input stream that filters out TDS headers so they are not returned to
* JSSE (which will not recognize them).
*
* @author Rob Worsnop
* @author Mike Hutchinson
* @version $Id: TdsTlsInputStream.java,v 1.5 2005/10/20 09:46:38 alin_sinpalean Exp $
*/
class TdsTlsInputStream extends FilterInputStream {
int bytesOutstanding;
/**
* Temporary buffer used to de-encapsulate inital TLS packets.
* Initial size should be enough for login phase after which no
* buffering is required.
*/
final byte[] readBuffer = new byte[6144];
InputStream bufferStream;
/** False if TLS packets are encapsulated in TDS packets. */
boolean pureSSL;
/**
* Constructs a TdsTlsInputStream and bases it on an underlying stream.
*
* @param in the underlying stream
*/
public TdsTlsInputStream(InputStream in) {
super(in);
}
/*
* (non-Javadoc)
*
* @see java.io.InputStream#read(byte[], int, int)
*/
public int read(byte[] b, int off, int len) throws IOException {
//
// If we have read past the TDS encapsulated TLS records
// Just read directly from the input stream.
//
if (pureSSL && bufferStream == null) {
return in.read(b, off, len);
}
// If this is the start of a new TLS record or
// TDS packet we need to read in entire record/packet.
if (!pureSSL && bufferStream == null) {
primeBuffer();
}
// Feed the client code bytes from the buffer
int ret = bufferStream.read(b, off, len);
bytesOutstanding -= ret < 0 ? 0 : ret;
if (bytesOutstanding == 0) {
// All bytes in the buffer have been read.
// The next read will prime it again.
bufferStream = null;
}
return ret;
}
/**
* Read in entire TLS record or TDS packet and store the TLS record in the
* buffer. (TDS packets will always contain a TLS record.)
*/
private void primeBuffer() throws IOException {
// first read the type (first byte for TDS and TLS).
// TLS packet hdr size = 5 TDS = 8
readFully(readBuffer, 0, Ssl.TLS_HEADER_SIZE);
int len;
if (readBuffer[0] == TdsCore.REPLY_PKT
|| readBuffer[0] == TdsCore.PRELOGIN_PKT) {
len = ((readBuffer[2] & 0xFF) << 8) | (readBuffer[3] & 0xFF);
// Read rest of header to skip
readFully(readBuffer, Ssl.TLS_HEADER_SIZE, TdsCore.PKT_HDR_LEN - Ssl.TLS_HEADER_SIZE );
len -= TdsCore.PKT_HDR_LEN;
readFully(readBuffer, 0, len); // Now get inner packet
} else {
len = ((readBuffer[3] & 0xFF) << 8) | (readBuffer[4] & 0xFF);
readFully(readBuffer, Ssl.TLS_HEADER_SIZE, len - Ssl.TLS_HEADER_SIZE);
pureSSL = true;
}
bufferStream = new ByteArrayInputStream(readBuffer, 0, len);
bytesOutstanding = len;
}
/**
* Reads len bytes or throws an IOException if
* there aren't that many bytes available.
*
* @param b buffer to read into
* @param off offset in the buffer where to start storing
* @param len amount of data to read
* @throws IOException if an I/O error occurs or not enough data is
* available
*/
private void readFully(byte[] b, int off, int len) throws IOException {
int res = 0;
while (len > 0 && (res = in.read(b, off, len)) >= 0) {
off += res;
len -= res;
}
if (res < 0) {
throw new IOException();
}
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/ 0000755 0001750 0001750 00000000000 11316672660 023100 5 ustar martin martin libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/TdsCore.java 0000644 0001750 0001750 00000457030 11316672660 025317 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.io.*;
import java.sql.*;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import net.sourceforge.jtds.ssl.*;
import net.sourceforge.jtds.util.*;
/**
* This class implements the Sybase / Microsoft TDS protocol.
* * Implementation notes: *
boolean true if the update count is valid.
*/
boolean isUpdateCount() {
return (token == TDS_DONE_TOKEN || token == TDS_DONEINPROC_TOKEN)
&& (status & DONE_ROW_COUNT) != 0;
}
/**
* Retrieve the DONE token status.
*
* @return boolean true if the current token is a DONE packet.
*/
boolean isEndToken() {
return token == TDS_DONE_TOKEN
|| token == TDS_DONEINPROC_TOKEN
|| token == TDS_DONEPROC_TOKEN;
}
/**
* Retrieve the NTLM challenge status.
*
* @return boolean true if the current token is an NTLM challenge.
*/
boolean isAuthToken() {
return token == TDS_AUTH_TOKEN;
}
/**
* Retrieve the results pending status.
*
* @return boolean true if more results in input.
*/
boolean resultsPending() {
return !isEndToken() || ((status & DONE_MORE_RESULTS) != 0);
}
/**
* Retrieve the result set status.
*
* @return boolean true if the current token is a result set.
*/
boolean isResultSet() {
return token == TDS_COLFMT_TOKEN
|| token == TDS7_RESULT_TOKEN
|| token == TDS_RESULT_TOKEN
|| token == TDS5_WIDE_RESULT
|| token == TDS_COLINFO_TOKEN
|| token == TDS_ROW_TOKEN;
}
/**
* Retrieve the row data status.
*
* @return boolean true if the current token is a result row.
*/
public boolean isRowData() {
return token == TDS_ROW_TOKEN;
}
}
/**
* Inner static class used to hold table meta data.
*/
private static class TableMetaData {
/** Table catalog (database) name. */
String catalog;
/** Table schema (user) name. */
String schema;
/** Table name. */
String name;
}
//
// Package private constants
//
/** Minimum network packet size. */
public static final int MIN_PKT_SIZE = 512;
/** Default minimum network packet size for TDS 7.0 and newer. */
public static final int DEFAULT_MIN_PKT_SIZE_TDS70 = 4096;
/** Maximum network packet size. */
public static final int MAX_PKT_SIZE = 32768;
/** The size of the packet header. */
public static final int PKT_HDR_LEN = 8;
/** TDS 4.2 or 7.0 Query packet. */
public static final byte QUERY_PKT = 1;
/** TDS 4.2 or 5.0 Login packet. */
public static final byte LOGIN_PKT = 2;
/** TDS Remote Procedure Call. */
public static final byte RPC_PKT = 3;
/** TDS Reply packet. */
public static final byte REPLY_PKT = 4;
/** TDS Cancel packet. */
public static final byte CANCEL_PKT = 6;
/** TDS MSDTC packet. */
public static final byte MSDTC_PKT = 14;
/** TDS 5.0 Query packet. */
public static final byte SYBQUERY_PKT = 15;
/** TDS 7.0 Login packet. */
public static final byte MSLOGIN_PKT = 16;
/** TDS 7.0 NTLM Authentication packet. */
public static final byte NTLMAUTH_PKT = 17;
/** SQL 2000 prelogin negotiation packet. */
public static final byte PRELOGIN_PKT = 18;
/** SSL Mode - Login packet must be encrypted. */
public static final int SSL_ENCRYPT_LOGIN = 0;
/** SSL Mode - Client requested force encryption. */
public static final int SSL_CLIENT_FORCE_ENCRYPT = 1;
/** SSL Mode - No server certificate installed. */
public static final int SSL_NO_ENCRYPT = 2;
/** SSL Mode - Server requested force encryption. */
public static final int SSL_SERVER_FORCE_ENCRYPT = 3;
//
// Sub packet types
//
/** TDS 5.0 Parameter format token. */
private static final byte TDS5_PARAMFMT2_TOKEN = (byte) 32; // 0x20
/** TDS 5.0 Language token. */
private static final byte TDS_LANG_TOKEN = (byte) 33; // 0x21
/** TSD 5.0 Wide result set token. */
private static final byte TDS5_WIDE_RESULT = (byte) 97; // 0x61
/** TDS 5.0 Close token. */
private static final byte TDS_CLOSE_TOKEN = (byte) 113; // 0x71
/** TDS DBLIB Offsets token. */
private static final byte TDS_OFFSETS_TOKEN = (byte) 120; // 0x78
/** TDS Procedure call return status token. */
private static final byte TDS_RETURNSTATUS_TOKEN= (byte) 121; // 0x79
/** TDS Procedure ID token. */
private static final byte TDS_PROCID = (byte) 124; // 0x7C
/** TDS 7.0 Result set column meta data token. */
private static final byte TDS7_RESULT_TOKEN = (byte) 129; // 0x81
/** TDS 7.0 Computed Result set column meta data token. */
private static final byte TDS7_COMP_RESULT_TOKEN= (byte) 136; // 0x88
/** TDS 4.2 Column names token. */
private static final byte TDS_COLNAME_TOKEN = (byte) 160; // 0xA0
/** TDS 4.2 Column meta data token. */
private static final byte TDS_COLFMT_TOKEN = (byte) 161; // 0xA1
/** TDS Table name token. */
private static final byte TDS_TABNAME_TOKEN = (byte) 164; // 0xA4
/** TDS Cursor results column infomation token. */
private static final byte TDS_COLINFO_TOKEN = (byte) 165; // 0xA5
/** TDS Optional command token. */
private static final byte TDS_OPTIONCMD_TOKEN = (byte) 166; // 0xA6
/** TDS Computed result set names token. */
private static final byte TDS_COMP_NAMES_TOKEN = (byte) 167; // 0xA7
/** TDS Computed result set token. */
private static final byte TDS_COMP_RESULT_TOKEN = (byte) 168; // 0xA8
/** TDS Order by columns token. */
private static final byte TDS_ORDER_TOKEN = (byte) 169; // 0xA9
/** TDS error result token. */
private static final byte TDS_ERROR_TOKEN = (byte) 170; // 0xAA
/** TDS Information message token. */
private static final byte TDS_INFO_TOKEN = (byte) 171; // 0xAB
/** TDS Output parameter value token. */
private static final byte TDS_PARAM_TOKEN = (byte) 172; // 0xAC
/** TDS Login acknowledgement token. */
private static final byte TDS_LOGINACK_TOKEN = (byte) 173; // 0xAD
/** TDS control token. */
private static final byte TDS_CONTROL_TOKEN = (byte) 174; // 0xAE
/** TDS Result set data row token. */
private static final byte TDS_ROW_TOKEN = (byte) 209; // 0xD1
/** TDS Computed result set data row token. */
private static final byte TDS_ALTROW = (byte) 211; // 0xD3
/** TDS 5.0 parameter value token. */
private static final byte TDS5_PARAMS_TOKEN = (byte) 215; // 0xD7
/** TDS 5.0 capabilities token. */
private static final byte TDS_CAP_TOKEN = (byte) 226; // 0xE2
/** TDS environment change token. */
private static final byte TDS_ENVCHANGE_TOKEN = (byte) 227; // 0xE3
/** TDS 5.0 message token. */
private static final byte TDS_MSG50_TOKEN = (byte) 229; // 0xE5
/** TDS 5.0 RPC token. */
private static final byte TDS_DBRPC_TOKEN = (byte) 230; // 0xE6
/** TDS 5.0 Dynamic SQL token. */
private static final byte TDS5_DYNAMIC_TOKEN = (byte) 231; // 0xE7
/** TDS 5.0 parameter descriptor token. */
private static final byte TDS5_PARAMFMT_TOKEN = (byte) 236; // 0xEC
/** TDS 7.0 NTLM authentication challenge token. */
private static final byte TDS_AUTH_TOKEN = (byte) 237; // 0xED
/** TDS 5.0 Result set column meta data token. */
private static final byte TDS_RESULT_TOKEN = (byte) 238; // 0xEE
/** TDS done token. */
private static final byte TDS_DONE_TOKEN = (byte) 253; // 0xFD DONE
/** TDS done procedure token. */
private static final byte TDS_DONEPROC_TOKEN = (byte) 254; // 0xFE DONEPROC
/** TDS done in procedure token. */
private static final byte TDS_DONEINPROC_TOKEN = (byte) 255; // 0xFF DONEINPROC
//
// Environment change payload codes
//
/** Environment change: database changed. */
private static final byte TDS_ENV_DATABASE = (byte) 1;
/** Environment change: language changed. */
private static final byte TDS_ENV_LANG = (byte) 2;
/** Environment change: charset changed. */
private static final byte TDS_ENV_CHARSET = (byte) 3;
/** Environment change: network packet size changed. */
private static final byte TDS_ENV_PACKSIZE = (byte) 4;
/** Environment change: locale changed. */
private static final byte TDS_ENV_LCID = (byte) 5;
/** Environment change: TDS 8 collation changed. */
private static final byte TDS_ENV_SQLCOLLATION = (byte) 7; // TDS8 Collation
//
// Static variables used only for performance
//
/** Used to optimize the {@link #getParameters()} call */
private static final ParamInfo[] EMPTY_PARAMETER_INFO = new ParamInfo[0];
//
// End token status bytes
//
/** Done: more results are expected. */
private static final byte DONE_MORE_RESULTS = (byte) 0x01;
/** Done: command caused an error. */
private static final byte DONE_ERROR = (byte) 0x02;
/** Done: There is a valid row count. */
private static final byte DONE_ROW_COUNT = (byte) 0x10;
/** Done: Cancel acknowledgement. */
static final byte DONE_CANCEL = (byte) 0x20;
/**
* Done: Response terminator (if more than one request packet is sent, each
* response is terminated by a DONE packet with this flag set).
*/
private static final byte DONE_END_OF_RESPONSE = (byte) 0x80;
//
// Prepared SQL types
//
/** Do not prepare SQL */
public static final int UNPREPARED = 0;
/** Prepare SQL using temporary stored procedures */
public static final int TEMPORARY_STORED_PROCEDURES = 1;
/** Prepare SQL using sp_executesql */
public static final int EXECUTE_SQL = 2;
/** Prepare SQL using sp_prepare and sp_execute */
public static final int PREPARE = 3;
//
// Sybase capability flags
//
/** Sybase char and binary > 255.*/
static final int SYB_LONGDATA = 1;
/** Sybase date and time data types.*/
static final int SYB_DATETIME = 2;
/** Sybase nullable bit type.*/
static final int SYB_BITNULL = 4;
/** Sybase extended column meta data.*/
static final int SYB_EXTCOLINFO = 8;
/** Sybase univarchar etc. */
static final int SYB_UNICODE = 16;
/** Sybase 15+ unitext. */
static final int SYB_UNITEXT = 32;
/** Sybase 15+ bigint. */
static final int SYB_BIGINT = 64;
/** Cancel has been generated by Statement.cancel(). */
private final static int ASYNC_CANCEL = 0;
/** Cancel has been generated by a query timeout. */
private final static int TIMEOUT_CANCEL = 1;
/** Map of system stored procedures that have shortcuts in TDS8. */
private static HashMap tds8SpNames = new HashMap();
static {
tds8SpNames.put("sp_cursor", new Integer(1));
tds8SpNames.put("sp_cursoropen", new Integer(2));
tds8SpNames.put("sp_cursorprepare", new Integer(3));
tds8SpNames.put("sp_cursorexecute", new Integer(4));
tds8SpNames.put("sp_cursorprepexec", new Integer(5));
tds8SpNames.put("sp_cursorunprepare", new Integer(6));
tds8SpNames.put("sp_cursorfetch", new Integer(7));
tds8SpNames.put("sp_cursoroption", new Integer(8));
tds8SpNames.put("sp_cursorclose", new Integer(9));
tds8SpNames.put("sp_executesql", new Integer(10));
tds8SpNames.put("sp_prepare", new Integer(11));
tds8SpNames.put("sp_execute", new Integer(12));
tds8SpNames.put("sp_prepexec", new Integer(13));
tds8SpNames.put("sp_prepexecrpc", new Integer(14));
tds8SpNames.put("sp_unprepare", new Integer(15));
}
//
// Class variables
//
/** Name of the client host (it can take quite a while to find it out if DNS is configured incorrectly). */
private static String hostName;
/** A reference to ntlm.SSPIJNIClient. */
private static SSPIJNIClient sspiJNIClient;
//
// Instance variables
//
/** The Connection object that created this object. */
private final ConnectionJDBC2 connection;
/** The TDS version being supported by this connection. */
private int tdsVersion;
/** The make of SQL Server (Sybase/Microsoft). */
private final int serverType;
/** The Shared network socket object. */
private final SharedSocket socket;
/** The output server request stream. */
private final RequestStream out;
/** The input server response stream. */
private final ResponseStream in;
/** True if the server response is fully read. */
private boolean endOfResponse = true;
/** True if the current result set is at end of file. */
private boolean endOfResults = true;
/** The array of column meta data objects for this result set. */
private ColInfo[] columns;
/** The array of column data objects in the current row. */
private Object[] rowData;
/** The array of table names associated with this result. */
private TableMetaData[] tables;
/** The descriptor object for the current TDS token. */
private TdsToken currentToken = new TdsToken();
/** The stored procedure return status. */
private Integer returnStatus;
/** The return parameter meta data object for the current procedure call. */
private ParamInfo returnParam;
/** The array of parameter meta data objects for the current procedure call. */
private ParamInfo[] parameters;
/** The index of the next output parameter to populate. */
private int nextParam = -1;
/** The head of the diagnostic messages chain. */
private final SQLDiagnostic messages;
/** Indicates that this object is closed. */
private boolean isClosed;
/** Flag that indicates if logon() should try to use Windows Single Sign On using SSPI. */
private boolean ntlmAuthSSO;
/** Indicates that a fatal error has occured and the connection will close. */
private boolean fatalError;
/** Mutual exclusion lock on connection. */
private Semaphore connectionLock;
/** Indicates processing a batch. */
private boolean inBatch;
/** Indicates type of SSL connection. */
private int sslMode = SSL_NO_ENCRYPT;
/** Indicates pending cancel that needs to be cleared. */
private boolean cancelPending;
/** Synchronization monitor for {@link #cancelPending}. */
private final int[] cancelMonitor = new int[1];
/**
* Construct a TdsCore object.
*
* @param connection The connection which owns this object.
* @param messages The SQLDiagnostic messages chain.
*/
TdsCore(ConnectionJDBC2 connection, SQLDiagnostic messages) {
this.connection = connection;
this.socket = connection.getSocket();
this.messages = messages;
serverType = connection.getServerType();
tdsVersion = socket.getTdsVersion();
out = socket.getRequestStream(connection.getNetPacketSize(), connection.getMaxPrecision());
in = socket.getResponseStream(out, connection.getNetPacketSize());
}
/**
* Check that the connection is still open.
*
* @throws SQLException
* if the connection is closed
*/
private void checkOpen() throws SQLException {
if (connection.isClosed()) {
throw new SQLException(
Messages.get("error.generic.closed", "Connection"),
"HY010");
}
}
/**
* Retrieve the TDS protocol version.
*
* @return The protocol version as an int.
*/
int getTdsVersion() {
return tdsVersion;
}
/**
* Retrieve the current result set column descriptors.
*
* @return The column descriptors as a ColInfo[].
*/
ColInfo[] getColumns() {
return columns;
}
/**
* Sets the column meta data.
*
* @param columns the column descriptor array
*/
void setColumns(ColInfo[] columns) {
this.columns = columns;
this.rowData = new Object[columns.length];
this.tables = null;
}
/**
* Retrieve the parameter meta data from a Sybase prepare.
*
* @return The parameter descriptors as a ParamInfo[].
*/
ParamInfo[] getParameters() {
if (currentToken.dynamParamInfo != null) {
ParamInfo[] params = new ParamInfo[currentToken.dynamParamInfo.length];
for (int i = 0; i < params.length; i++) {
ColInfo ci = currentToken.dynamParamInfo[i];
params[i] = new ParamInfo(ci, ci.realName, null, 0);
}
return params;
}
return EMPTY_PARAMETER_INFO;
}
/**
* Retrieve the current result set data items.
*
* @return the row data as an Object array
*/
Object[] getRowData() {
return rowData;
}
/**
* Negotiate SSL settings with SQL 2000+ server.
*
* Server returns the following values for SSL mode:
* boolean if the next item is a result set.
* @throws SQLException if an I/O or protocol error occurs; server errors
* are queued up and not thrown
*/
boolean getMoreResults() throws SQLException {
checkOpen();
nextToken();
while (!endOfResponse
&& !currentToken.isUpdateCount()
&& !currentToken.isResultSet()) {
nextToken();
}
//
// Cursor opens are followed by TDS_TAB_INFO and TDS_COL_INFO
// Process these now so that the column descriptors are updated.
// Sybase wide result set headers are followed by a TDS_CONTROL_TOKEN
// skip that as well.
//
if (currentToken.isResultSet()) {
byte saveToken = currentToken.token;
try {
byte x = (byte) in.peek();
while ( x == TDS_TABNAME_TOKEN
|| x == TDS_COLINFO_TOKEN
|| x == TDS_CONTROL_TOKEN) {
nextToken();
x = (byte)in.peek();
}
} catch (IOException e) {
connection.setClosed();
throw Support.linkException(
new SQLException(
Messages.get(
"error.generic.ioerror", e.getMessage()),
"08S01"), e);
}
currentToken.token = saveToken;
}
return currentToken.isResultSet();
}
/**
* Retrieve the status of the next result item.
*
* @return boolean true if the next item is a result set.
*/
boolean isResultSet() {
return currentToken.isResultSet();
}
/**
* Retrieve the status of the next result item.
*
* @return boolean true if the next item is row data.
*/
boolean isRowData() {
return currentToken.isRowData();
}
/**
* Retrieve the status of the next result item.
*
* @return boolean true if the next item is an update count.
*/
boolean isUpdateCount() {
return currentToken.isUpdateCount();
}
/**
* Retrieve the update count from the current TDS token.
*
* @return The update count as an int.
*/
int getUpdateCount() {
if (currentToken.isEndToken()) {
return currentToken.updateCount;
}
return -1;
}
/**
* Retrieve the status of the response stream.
*
* @return boolean true if the response has been entirely consumed
*/
boolean isEndOfResponse() {
return endOfResponse;
}
/**
* Empty the server response queue.
*
* @throws SQLException if an error occurs
*/
void clearResponseQueue() throws SQLException {
checkOpen();
while (!endOfResponse) {
nextToken();
}
}
/**
* Consume packets from the server response queue up to (and including) the
* first response terminator.
*
* @throws SQLException if an I/O or protocol error occurs; server errors
* are queued up and not thrown
*/
void consumeOneResponse() throws SQLException {
checkOpen();
while (!endOfResponse) {
nextToken();
// If it's a response terminator, return
if (currentToken.isEndToken()
&& (currentToken.status & DONE_END_OF_RESPONSE) != 0) {
return;
}
}
}
/**
* Retrieve the next data row from the result set.
*
* @return false if at the end of results, true
* otherwise
* @throws SQLException if an I/O or protocol error occurs; server errors
* are queued up and not thrown
*/
boolean getNextRow() throws SQLException {
if (endOfResponse || endOfResults) {
return false;
}
checkOpen();
nextToken();
// Will either be first or next data row or end.
while (!currentToken.isRowData() && !currentToken.isEndToken()) {
nextToken(); // Could be messages
}
return currentToken.isRowData();
}
/**
* Retrieve the status of result set.
*
* This does a quick read ahead and is needed to support the isLast()
* method in the ResultSet.
*
* @return boolean - true if there is more data
* in the result set.
*/
boolean isDataInResultSet() throws SQLException {
byte x;
checkOpen();
try {
x = (endOfResponse) ? TDS_DONE_TOKEN : (byte) in.peek();
while (x != TDS_ROW_TOKEN
&& x != TDS_DONE_TOKEN
&& x != TDS_DONEINPROC_TOKEN
&& x != TDS_DONEPROC_TOKEN) {
nextToken();
x = (byte) in.peek();
}
messages.checkErrors();
} catch (IOException e) {
connection.setClosed();
throw Support.linkException(
new SQLException(
Messages.get(
"error.generic.ioerror", e.getMessage()),
"08S01"), e);
}
return x == TDS_ROW_TOKEN;
}
/**
* Retrieve the return status for the current stored procedure.
*
* @return The return status as an Integer.
*/
Integer getReturnStatus() {
return this.returnStatus;
}
/**
* Inform the server that this connection is closing.
*
* Used by Sybase a no-op for Microsoft.
*/
synchronized void closeConnection() {
try {
if (tdsVersion == Driver.TDS50) {
socket.setTimeout(1000);
out.setPacketType(SYBQUERY_PKT);
out.write((byte)TDS_CLOSE_TOKEN);
out.write((byte)0);
out.flush();
endOfResponse = false;
clearResponseQueue();
}
} catch (Exception e) {
// Ignore any exceptions as this connection
// is closing anyway.
}
}
/**
* Close the TdsCore connection object and associated streams.
*/
void close() throws SQLException {
if (!isClosed) {
try {
clearResponseQueue();
out.close();
in.close();
} finally {
isClosed = true;
}
}
}
/**
* Send (only) one cancel packet to the server.
*
* @param timeout true if this is a query timeout cancel
*/
void cancel(boolean timeout) {
Semaphore mutex = null;
try {
mutex = connection.getMutex();
synchronized (cancelMonitor) {
if (!cancelPending && !endOfResponse) {
cancelPending = socket.cancel(out.getStreamId());
}
// If a cancel request was sent, reset the end of response flag
if (cancelPending) {
cancelMonitor[0] = timeout ? TIMEOUT_CANCEL : ASYNC_CANCEL;
endOfResponse = false;
}
}
} finally {
if (mutex != null) {
mutex.release();
}
}
}
/**
* Submit a simple SQL statement to the server and process all output.
*
* @param sql the statement to execute
* @throws SQLException if an error is returned by the server
*/
void submitSQL(String sql) throws SQLException {
checkOpen();
messages.clearWarnings();
if (sql.length() == 0) {
throw new IllegalArgumentException("submitSQL() called with empty SQL String");
}
executeSQL(sql, null, null, false, 0, -1, -1, true);
clearResponseQueue();
messages.checkErrors();
}
/**
* Notifies the TdsCore that a batch is starting. This is so
* that it knows to use sp_executesql for parameterized
* queries (because there's no way to prepare a statement in the middle of
* a batch).
*
* Sets the {@link #inBatch} flag.
*/
void startBatch() {
inBatch = true;
}
/**
* Send an SQL statement with optional parameters to the server.
*
* @param sql SQL statement to execute
* @param procName stored procedure to execute or null
* @param parameters parameters for call or null
* @param noMetaData suppress meta data for cursor calls
* @param timeOut optional query timeout or 0
* @param maxRows the maximum number of data rows to return (-1 to
* leave unaltered)
* @param maxFieldSize the maximum number of bytes in a column to return
* (-1 to leave unaltered)
* @param sendNow whether to send the request now or not
* @throws SQLException if an error occurs
*/
synchronized void executeSQL(String sql,
String procName,
ParamInfo[] parameters,
boolean noMetaData,
int timeOut,
int maxRows,
int maxFieldSize,
boolean sendNow)
throws SQLException {
boolean sendFailed = true; // Used to ensure mutex is released.
try {
//
// Obtain a lock on the connection giving exclusive access
// to the network connection for this thread
//
if (connectionLock == null) {
connectionLock = connection.getMutex();
}
// Also checks if connection is open
clearResponseQueue();
messages.exceptions = null;
//
// Set the connection row count and text size if required.
// Once set these will not be changed within a
// batch so execution of the set rows query will
// only occur once a the start of a batch.
// No other thread can send until this one has finished.
//
setRowCountAndTextSize(maxRows, maxFieldSize);
messages.clearWarnings();
this.returnStatus = null;
//
// Normalize the parameters argument to simplify later checks
//
if (parameters != null && parameters.length == 0) {
parameters = null;
}
this.parameters = parameters;
//
// Normalise the procName argument as well
//
if (procName != null && procName.length() == 0) {
procName = null;
}
if (parameters != null && parameters[0].isRetVal) {
returnParam = parameters[0];
nextParam = 0;
} else {
returnParam = null;
nextParam = -1;
}
if (parameters != null) {
if (procName == null && sql.startsWith("EXECUTE ")) {
//
// If this is a callable statement that could not be fully parsed
// into an RPC call convert to straight SQL now.
// An example of non RPC capable SQL is {?=call sp_example('literal', ?)}
//
for (int i = 0; i < parameters.length; i++){
// Output parameters not allowed.
if (!parameters[i].isRetVal && parameters[i].isOutput){
throw new SQLException(Messages.get("error.prepare.nooutparam",
Integer.toString(i + 1)), "07000");
}
}
sql = Support.substituteParameters(sql, parameters, connection);
parameters = null;
} else {
//
// Check all parameters are either output or have values set
//
for (int i = 0; i < parameters.length; i++){
if (!parameters[i].isSet && !parameters[i].isOutput){
throw new SQLException(Messages.get("error.prepare.paramnotset",
Integer.toString(i + 1)), "07000");
}
parameters[i].clearOutValue();
// FIXME Should only set TDS type if not already set
// but we might need to take a lot of care not to
// exceed size limitations (e.g. write 11 chars in a
// VARCHAR(10) )
TdsData.getNativeType(connection, parameters[i]);
}
}
}
try {
switch (tdsVersion) {
case Driver.TDS42:
executeSQL42(sql, procName, parameters, noMetaData, sendNow);
break;
case Driver.TDS50:
executeSQL50(sql, procName, parameters);
break;
case Driver.TDS70:
case Driver.TDS80:
case Driver.TDS81:
executeSQL70(sql, procName, parameters, noMetaData, sendNow);
break;
default:
throw new IllegalStateException("Unknown TDS version " + tdsVersion);
}
if (sendNow) {
out.flush();
connectionLock.release();
connectionLock = null;
sendFailed = false;
endOfResponse = false;
endOfResults = true;
wait(timeOut);
} else {
sendFailed = false;
}
} catch (IOException ioe) {
connection.setClosed();
throw Support.linkException(
new SQLException(
Messages.get(
"error.generic.ioerror", ioe.getMessage()),
"08S01"), ioe);
}
} finally {
if ((sendNow || sendFailed) && connectionLock != null) {
connectionLock.release();
connectionLock = null;
}
// Clear the in batch flag
if (sendNow) {
inBatch = false;
}
}
}
/**
* Prepares the SQL for use with Microsoft server.
*
* @param sql the SQL statement to prepare.
* @param params the actual parameter list
* @param needCursor true if a cursorprepare is required
* @param resultSetType value of the resultSetType parameter when
* the Statement was created
* @param resultSetConcurrency value of the resultSetConcurrency parameter
* whenthe Statement was created
* @return name of the procedure or prepared statement handle.
* @exception SQLException
*/
String microsoftPrepare(String sql,
ParamInfo[] params,
boolean needCursor,
int resultSetType,
int resultSetConcurrency)
throws SQLException {
//
checkOpen();
messages.clearWarnings();
int prepareSql = connection.getPrepareSql();
if (prepareSql == TEMPORARY_STORED_PROCEDURES) {
StringBuffer spSql = new StringBuffer(sql.length() + 32 + params.length * 15);
String procName = connection.getProcName();
spSql.append("create proc ");
spSql.append(procName);
spSql.append(' ');
for (int i = 0; i < params.length; i++) {
spSql.append("@P");
spSql.append(i);
spSql.append(' ');
spSql.append(params[i].sqlType);
if (i + 1 < params.length) {
spSql.append(',');
}
}
// continue building proc
spSql.append(" as ");
spSql.append(Support.substituteParamMarkers(sql, params));
try {
submitSQL(spSql.toString());
return procName;
} catch (SQLException e) {
if ("08S01".equals(e.getSQLState())) {
// Serious (I/O) error, rethrow
throw e;
}
// This exception probably caused by failure to prepare
// Add a warning
messages.addWarning(Support.linkException(
new SQLWarning(
Messages.get("error.prepare.prepfailed",
e.getMessage()),
e.getSQLState(), e.getErrorCode()),
e));
}
} else if (prepareSql == PREPARE) {
int scrollOpt, ccOpt;
ParamInfo prepParam[] = new ParamInfo[needCursor ? 6 : 4];
// Setup prepare handle param
prepParam[0] = new ParamInfo(Types.INTEGER, null, ParamInfo.OUTPUT);
// Setup parameter descriptor param
prepParam[1] = new ParamInfo(Types.LONGVARCHAR,
Support.getParameterDefinitions(params),
ParamInfo.UNICODE);
// Setup sql statemement param
prepParam[2] = new ParamInfo(Types.LONGVARCHAR,
Support.substituteParamMarkers(sql, params),
ParamInfo.UNICODE);
// Setup options param
prepParam[3] = new ParamInfo(Types.INTEGER, new Integer(1), ParamInfo.INPUT);
if (needCursor) {
// Select the correct type of Server side cursor to
// match the scroll and concurrency options.
scrollOpt = MSCursorResultSet.getCursorScrollOpt(resultSetType,
resultSetConcurrency, true);
ccOpt = MSCursorResultSet.getCursorConcurrencyOpt(resultSetConcurrency);
// Setup scroll options parameter
prepParam[4] = new ParamInfo(Types.INTEGER,
new Integer(scrollOpt),
ParamInfo.OUTPUT);
// Setup concurrency options parameter
prepParam[5] = new ParamInfo(Types.INTEGER,
new Integer(ccOpt),
ParamInfo.OUTPUT);
}
columns = null; // Will be populated if preparing a select
try {
executeSQL(null, needCursor ? "sp_cursorprepare" : "sp_prepare",
prepParam, false, 0, -1, -1, true);
int resultCount = 0;
while (!endOfResponse) {
nextToken();
if (isResultSet()) {
resultCount++;
}
}
// columns will now hold meta data for any select statements
if (resultCount != 1) {
// More than one result set was returned or none
// therefore metadata not available or unsafe.
columns = null;
}
Integer prepareHandle = (Integer) prepParam[0].getOutValue();
if (prepareHandle != null) {
return prepareHandle.toString();
}
// Probably an exception occurred, check for it
messages.checkErrors();
} catch (SQLException e) {
if ("08S01".equals(e.getSQLState())) {
// Serious (I/O) error, rethrow
throw e;
}
// This exception probably caused by failure to prepare
// Add a warning
messages.addWarning(Support.linkException(
new SQLWarning(
Messages.get("error.prepare.prepfailed",
e.getMessage()),
e.getSQLState(), e.getErrorCode()),
e));
}
}
return null;
}
/**
* Creates a light weight stored procedure on a Sybase server.
*
* @param sql SQL statement to prepare
* @param params the actual parameter list
* @return name of the procedure
* @throws SQLException if an error occurs
*/
synchronized String sybasePrepare(String sql, ParamInfo[] params)
throws SQLException {
checkOpen();
messages.clearWarnings();
if (sql == null || sql.length() == 0) {
throw new IllegalArgumentException(
"sql parameter must be at least 1 character long.");
}
String procName = connection.getProcName();
if (procName == null || procName.length() != 11) {
throw new IllegalArgumentException(
"procName parameter must be 11 characters long.");
}
// TODO Check if output parameters are handled ok
// Check no text/image parameters
for (int i = 0; i < params.length; i++) {
if ("text".equals(params[i].sqlType)
|| "unitext".equals(params[i].sqlType)
|| "image".equals(params[i].sqlType)) {
return null; // Sadly no way
}
}
Semaphore mutex = null;
try {
mutex = connection.getMutex();
out.setPacketType(SYBQUERY_PKT);
out.write((byte)TDS5_DYNAMIC_TOKEN);
byte buf[] = Support.encodeString(connection.getCharset(), sql);
out.write((short) (buf.length + 41));
out.write((byte) 1);
out.write((byte) 0);
out.write((byte) 10);
out.writeAscii(procName.substring(1));
out.write((short) (buf.length + 26));
out.writeAscii("create proc ");
out.writeAscii(procName.substring(1));
out.writeAscii(" as ");
out.write(buf);
out.flush();
endOfResponse = false;
clearResponseQueue();
messages.checkErrors();
return procName;
} catch (IOException ioe) {
connection.setClosed();
throw Support.linkException(
new SQLException(
Messages.get(
"error.generic.ioerror", ioe.getMessage()),
"08S01"), ioe);
} catch (SQLException e) {
if ("08S01".equals(e.getSQLState())) {
// Serious error rethrow
throw e;
}
// This exception probably caused by failure to prepare
// Return null;
return null;
} finally {
if (mutex != null) {
mutex.release();
}
}
}
/**
* Drops a Sybase temporary stored procedure.
*
* @param procName the temporary procedure name
* @throws SQLException if an error occurs
*/
synchronized void sybaseUnPrepare(String procName)
throws SQLException {
checkOpen();
messages.clearWarnings();
if (procName == null || procName.length() != 11) {
throw new IllegalArgumentException(
"procName parameter must be 11 characters long.");
}
Semaphore mutex = null;
try {
mutex = connection.getMutex();
out.setPacketType(SYBQUERY_PKT);
out.write((byte)TDS5_DYNAMIC_TOKEN);
out.write((short) (15));
out.write((byte) 4);
out.write((byte) 0);
out.write((byte) 10);
out.writeAscii(procName.substring(1));
out.write((short)0);
out.flush();
endOfResponse = false;
clearResponseQueue();
messages.checkErrors();
} catch (IOException ioe) {
connection.setClosed();
throw Support.linkException(
new SQLException(
Messages.get(
"error.generic.ioerror", ioe.getMessage()),
"08S01"), ioe);
} catch (SQLException e) {
if ("08S01".equals(e.getSQLState())) {
// Serious error rethrow
throw e;
}
// This exception probably caused by failure to unprepare
} finally {
if (mutex != null) {
mutex.release();
}
}
}
/**
* Enlist the current connection in a distributed transaction or request the location of the
* MSDTC instance controlling the server we are connected to.
*
* @param type set to 0 to request TM address or 1 to enlist connection
* @param oleTranID the 40 OLE transaction ID
* @return a byte[] array containing the TM address data
* @throws SQLException
*/
synchronized byte[] enlistConnection(int type, byte[] oleTranID) throws SQLException {
Semaphore mutex = null;
try {
mutex = connection.getMutex();
out.setPacketType(MSDTC_PKT);
out.write((short)type);
switch (type) {
case 0: // Get result set with location of MSTDC
out.write((short)0);
break;
case 1: // Set OLE transaction ID
if (oleTranID != null) {
out.write((short)oleTranID.length);
out.write(oleTranID);
} else {
// Delist the connection from all transactions.
out.write((short)0);
}
break;
}
out.flush();
endOfResponse = false;
endOfResults = true;
} catch (IOException ioe) {
connection.setClosed();
throw Support.linkException(
new SQLException(
Messages.get(
"error.generic.ioerror", ioe.getMessage()),
"08S01"),
ioe);
} finally {
if (mutex != null) {
mutex.release();
}
}
byte[] tmAddress = null;
if (getMoreResults() && getNextRow()) {
if (rowData.length == 1) {
Object x = rowData[0];
if (x instanceof byte[]) {
tmAddress = (byte[])x;
}
}
}
clearResponseQueue();
messages.checkErrors();
return tmAddress;
}
/**
* Obtain the counts from a batch of SQL updates.
*
SQLExceptions are chained
* because there could be several errors reported in a batch.
*
* @param counts the ArrayList containing the update counts
* @param sqlEx any previous SQLException(s) encountered
* @return updated SQLException or null if no
* error has yet occurred
* @throws SQLException
* if the connection is closed
*/
SQLException getBatchCounts(ArrayList counts, SQLException sqlEx) throws SQLException {
Integer lastCount = JtdsStatement.SUCCESS_NO_INFO;
try {
checkOpen();
while (!endOfResponse) {
nextToken();
if (currentToken.isResultSet()) {
// Serious error, statement must not return a result set
throw new SQLException(
Messages.get("error.statement.batchnocount"),
"07000");
}
//
// Analyse type of end token and try to extract correct
// update count when calling stored procs.
//
switch (currentToken.token) {
case TDS_DONE_TOKEN:
if ((currentToken.status & DONE_ERROR) != 0
|| lastCount == JtdsStatement.EXECUTE_FAILED) {
counts.add(JtdsStatement.EXECUTE_FAILED);
} else {
if (currentToken.isUpdateCount()) {
counts.add(new Integer(currentToken.updateCount));
} else {
counts.add(lastCount);
}
}
lastCount = JtdsStatement.SUCCESS_NO_INFO;
break;
case TDS_DONEINPROC_TOKEN:
if ((currentToken.status & DONE_ERROR) != 0) {
lastCount = JtdsStatement.EXECUTE_FAILED;
} else if (currentToken.isUpdateCount()) {
lastCount = new Integer(currentToken.updateCount);
}
break;
case TDS_DONEPROC_TOKEN:
if ((currentToken.status & DONE_ERROR) != 0
|| lastCount == JtdsStatement.EXECUTE_FAILED) {
counts.add(JtdsStatement.EXECUTE_FAILED);
} else {
counts.add(lastCount);
}
lastCount = JtdsStatement.SUCCESS_NO_INFO;
break;
}
}
//
// Check for any exceptions
//
messages.checkErrors();
} catch (SQLException e) {
//
// Chain all exceptions
//
if (sqlEx != null) {
sqlEx.setNextException(e);
} else {
sqlEx = e;
}
} finally {
while (!endOfResponse) {
// Flush rest of response
try {
nextToken();
} catch (SQLException ex) {
checkOpen(); // fix for bug [1843801]
// Chain any exceptions to the BatchUpdateException
if (sqlEx != null) {
sqlEx.setNextException(ex);
} else {
sqlEx = ex;
}
}
}
}
return sqlEx;
}
// ---------------------- Private Methods from here ---------------------
/**
* Write a TDS login packet string. Text followed by padding followed
* by a byte sized length.
*/
private void putLoginString(String txt, int len)
throws IOException {
byte[] tmp = Support.encodeString(connection.getCharset(), txt);
out.write(tmp, 0, len);
out.write((byte) (tmp.length < len ? tmp.length : len));
}
/**
* Send the SQL Server 2000 pre login packet.
* Packet contains; netlib version, ssl mode, instance * and process ID. * @param instance * @param forceEncryption * @throws IOException */ private void sendPreLoginPacket(String instance, boolean forceEncryption) throws IOException { out.setPacketType(PRELOGIN_PKT); // Write Netlib pointer out.write((short)0); out.write((short)21); out.write((byte)6); // Write Encrypt flag pointer out.write((short)1); out.write((short)27); out.write((byte)1); // Write Instance name pointer out.write((short)2); out.write((short)28); out.write((byte)(instance.length()+1)); // Write process ID pointer out.write((short)3); out.write((short)(28+instance.length()+1)); out.write((byte)4); // Write terminator out.write((byte)0xFF); // Write fake net lib ID 8.341.0 out.write(new byte[]{0x08, 0x00, 0x01, 0x55, 0x00, 0x00}); // Write force encryption flag out.write((byte)(forceEncryption? 1: 0)); // Write instance name out.writeAscii(instance); out.write((byte)0); // Write dummy process ID out.write(new byte[]{0x01, 0x02, 0x00, 0x00}); // out.flush(); } /** * Process the pre login acknowledgement from the server. *
Packet contains; server version no, SSL mode, instance name * and process id. *
Server returns the following values for SSL mode: *
* @param serverName server host name * @param user user name * @param password user password * @param charset required server character set * @param appName application name * @param progName library name * @param wsid workstation ID * @param language server language for messages * @param packetSize required network packet size * @throws IOException if an I/O error occurs */ private void send50LoginPkt(final String serverName, final String user, final String password, final String charset, final String appName, final String progName, final String wsid, final String language, final int packetSize) throws IOException { final byte[] empty = new byte[0]; out.setPacketType(LOGIN_PKT); putLoginString(wsid, 30); // Host name putLoginString(user, 30); // user name putLoginString(password, 30); // password putLoginString(String.valueOf(connection.getProcessId()), 30); // hostproc (offset 93 0x5d) out.write((byte) 3); // type of int2 out.write((byte) 1); // type of int4 out.write((byte) 6); // type of char out.write((byte) 10);// type of flt out.write((byte) 9); // type of date out.write((byte) 1); // notify of use db out.write((byte) 1); // disallow dump/load and bulk insert out.write((byte) 0); // sql interface type out.write((byte) 0); // type of network connection out.write(empty, 0, 7); putLoginString(appName, 30); // appname putLoginString(serverName, 30); // server name out.write((byte)0); // remote passwords out.write((byte)password.length()); byte[] tmp = Support.encodeString(connection.getCharset(), password); out.write(tmp, 0, 253); out.write((byte) (tmp.length + 2)); out.write((byte) 5); // tds version out.write((byte) 0); out.write((byte) 0); out.write((byte) 0); putLoginString(progName, 10); // prog name out.write((byte) 5); // prog version out.write((byte) 0); out.write((byte) 0); out.write((byte) 0); out.write((byte) 0); // auto convert short out.write((byte) 0x0D); // type of flt4 out.write((byte) 0x11); // type of date4 putLoginString(language, 30); // language out.write((byte) 1); // notify on lang change out.write((short) 0); // security label hierachy out.write((byte) 0); // security encrypted out.write(empty, 0, 8); // security components out.write((short) 0); // security spare putLoginString(charset, 30); // Character set out.write((byte) 1); // notify on charset change if (packetSize > 0) { putLoginString(String.valueOf(packetSize), 6); // specified length of tds packets } else { putLoginString(String.valueOf(MIN_PKT_SIZE), 6); // Default length of tds packets } out.write(empty, 0, 4); // // Request capabilities // // jTDS sends 01 0B 4F FF 85 EE EF 65 7F FF FF FF D6 // Sybase 11.92 01 0A 00 00 00 23 61 41 CF FF FF C6 // Sybase 12.52 01 0A 03 84 0A E3 61 41 FF FF FF C6 // Sybase 15.00 01 0B 4F F7 85 EA EB 61 7F FF FF FF C6 // // Response capabilities // // jTDS sends 02 0A 00 00 04 06 80 06 48 00 00 00 // Sybase 11.92 02 0A 00 00 00 00 00 06 00 00 00 00 // Sybase 12.52 02 0A 00 00 00 00 00 06 00 00 00 00 // Sybase 15.00 02 0A 00 00 04 00 00 06 00 00 00 00 // byte capString[] = { // Request capabilities (byte)0x01,(byte)0x0B,(byte)0x4F,(byte)0xFF,(byte)0x85,(byte)0xEE,(byte)0xEF, (byte)0x65,(byte)0x7F,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xD6, // Response capabilities (byte)0x02,(byte)0x0A,(byte)0x00,(byte)0x02,(byte)0x04,(byte)0x06, (byte)0x80,(byte)0x06,(byte)0x48,(byte)0x00,(byte)0x00,(byte)0x0C }; if (packetSize == 0) { // Tell the server we will use its packet size capString[17] = 0; } out.write(TDS_CAP_TOKEN); out.write((short)capString.length); out.write(capString); out.flush(); // Send the packet endOfResponse = false; } /** * Send a TDS 7 login packet. *
* This method incorporates the Windows single sign on code contributed by
* Magendran Sathaiah. To invoke single sign on just leave the user name
* blank or null. NB. This can only work if the driver is being executed on
* a Windows PC and When returning output parameters this token will be followed
* by a TDS5_PARAMS_TOKEN with the actual data.
* @throws IOException
* @throws ProtocolException
*/
private void tds5ParamFmt2Token() throws IOException, ProtocolException {
in.readInt(); // Packet length
int paramCnt = in.readShort();
ColInfo[] params = new ColInfo[paramCnt];
for (int i = 0; i < paramCnt; i++) {
//
// Get the parameter details using the
// ColInfo class as the server format is the same.
//
ColInfo col = new ColInfo();
int colNameLen = in.read();
col.realName = in.readNonUnicodeString(colNameLen);
int column_flags = in.readInt(); /* Flags */
col.isCaseSensitive = false;
col.nullable = ((column_flags & 0x20) != 0)?
ResultSetMetaData.columnNullable:
ResultSetMetaData.columnNoNulls;
col.isWriteable = (column_flags & 0x10) != 0;
col.isIdentity = (column_flags & 0x40) != 0;
col.isKey = (column_flags & 0x02) != 0;
col.isHidden = (column_flags & 0x01) != 0;
col.userType = in.readInt();
TdsData.readType(in, col);
// Skip locale information
in.skip(1);
params[i] = col;
}
currentToken.dynamParamInfo = params;
currentToken.dynamParamData = new Object[paramCnt];
}
/**
* Process Sybase 12+ wide result token which provides enhanced
* column meta data.
*
* @throws IOException
*/
private void tds5WideResultToken()
throws IOException, ProtocolException
{
in.readInt(); // Packet length
int colCnt = in.readShort();
this.columns = new ColInfo[colCnt];
this.rowData = new Object[colCnt];
this.tables = null;
for (int colNum = 0; colNum < colCnt; ++colNum) {
ColInfo col = new ColInfo();
//
// Get the alias name
//
int nameLen = in.read();
col.name = in.readNonUnicodeString(nameLen);
//
// Get the catalog name
//
nameLen = in.read();
col.catalog = in.readNonUnicodeString(nameLen);
//
// Get the schema name
//
nameLen = in.read();
col.schema = in.readNonUnicodeString(nameLen);
//
// Get the table name
//
nameLen = in.read();
col.tableName = in.readNonUnicodeString(nameLen);
//
// Get the column name
//
nameLen = in.read();
col.realName = in.readNonUnicodeString(nameLen);
if (col.name == null || col.name.length() == 0) {
col.name = col.realName;
}
int column_flags = in.readInt(); /* Flags */
col.isCaseSensitive = false;
col.nullable = ((column_flags & 0x20) != 0)?
ResultSetMetaData.columnNullable:
ResultSetMetaData.columnNoNulls;
col.isWriteable = (column_flags & 0x10) != 0;
col.isIdentity = (column_flags & 0x40) != 0;
col.isKey = (column_flags & 0x02) != 0;
col.isHidden = (column_flags & 0x01) != 0;
col.userType = in.readInt();
TdsData.readType(in, col);
// Skip locale information
in.skip(1);
columns[colNum] = col;
}
endOfResults = false;
}
/**
* Process stored procedure return status token.
*
* @throws IOException
*/
private void tdsReturnStatusToken() throws IOException, SQLException {
returnStatus = new Integer(in.readInt());
if (this.returnParam != null) {
returnParam.setOutValue(Support.convert(this.connection,
returnStatus,
returnParam.jdbcType,
connection.getCharset()));
}
}
/**
* Process procedure ID token.
*
* Used by DBLIB to obtain the object id of a stored procedure.
*/
private void tdsProcIdToken() throws IOException {
in.skip(8);
}
/**
* Process offsets token.
*
* Used by DBLIB to return the offset of various keywords in a statement.
* This saves the client from having to parse a SQL statement. Enabled with
*
* Note: Will be followed by a COL_FMT token.
*
* @throws IOException
*/
private void tds4ColNamesToken() throws IOException {
ArrayList colList = new ArrayList();
final int pktLen = in.readShort();
this.tables = null;
int bytesRead = 0;
while (bytesRead < pktLen) {
ColInfo col = new ColInfo();
int nameLen = in.read();
String name = in.readNonUnicodeString(nameLen);
bytesRead = bytesRead + 1 + nameLen;
col.realName = name;
col.name = name;
colList.add(col);
}
int colCnt = colList.size();
this.columns = (ColInfo[]) colList.toArray(new ColInfo[colCnt]);
this.rowData = new Object[colCnt];
}
/**
* Process a TDS 4.2 column format token.
*
* @throws IOException
* @throws ProtocolException
*/
private void tds4ColFormatToken()
throws IOException, ProtocolException {
final int pktLen = in.readShort();
int bytesRead = 0;
int numColumns = 0;
while (bytesRead < pktLen) {
if (numColumns > columns.length) {
throw new ProtocolException("Too many columns in TDS_COL_FMT packet");
}
ColInfo col = columns[numColumns];
if (serverType == Driver.SQLSERVER) {
col.userType = in.readShort();
int flags = in.readShort();
col.nullable = ((flags & 0x01) != 0)?
ResultSetMetaData.columnNullable:
ResultSetMetaData.columnNoNulls;
col.isCaseSensitive = (flags & 0x02) != 0;
col.isWriteable = (flags & 0x0C) != 0;
col.isIdentity = (flags & 0x10) != 0;
} else {
// Sybase does not send column flags
col.isCaseSensitive = false;
col.isWriteable = true;
if (col.nullable == ResultSetMetaData.columnNoNulls) {
col.nullable = ResultSetMetaData.columnNullableUnknown;
}
col.userType = in.readInt();
}
bytesRead += 4;
bytesRead += TdsData.readType(in, col);
numColumns++;
}
if (numColumns != columns.length) {
throw new ProtocolException("Too few columns in TDS_COL_FMT packet");
}
endOfResults = false;
}
/**
* Process a table name token.
* Sent by select for browse or cursor functions.
*
* @throws IOException
*/
private void tdsTableNameToken() throws IOException, ProtocolException {
final int pktLen = in.readShort();
int bytesRead = 0;
ArrayList tableList = new ArrayList();
while (bytesRead < pktLen) {
int nameLen;
String tabName;
TableMetaData table;
if (tdsVersion >= Driver.TDS81) {
// TDS8.1 supplies the server.database.owner.table as up to
// four separate components which allows us to have names
// with embedded periods.
table = new TableMetaData();
bytesRead++;
int tableNameToken = in.read();
switch (tableNameToken) {
case 4: nameLen = in.readShort();
bytesRead += nameLen * 2 + 2;
// Read and discard server name; see Bug 1403067
in.readUnicodeString(nameLen);
case 3: nameLen = in.readShort();
bytesRead += nameLen * 2 + 2;
table.catalog = in.readUnicodeString(nameLen);
case 2: nameLen = in.readShort();
bytesRead += nameLen * 2 + 2;
table.schema = in.readUnicodeString(nameLen);
case 1: nameLen = in.readShort();
bytesRead += nameLen * 2 + 2;
table.name = in.readUnicodeString(nameLen);
case 0: break;
default:
throw new ProtocolException("Invalid table TAB_NAME_TOKEN: "
+ tableNameToken);
}
} else {
if (tdsVersion >= Driver.TDS70) {
nameLen = in.readShort();
bytesRead += nameLen * 2 + 2;
tabName = in.readUnicodeString(nameLen);
} else {
// TDS 4.2 or TDS 5.0
nameLen = in.read();
bytesRead++;
if (nameLen == 0) {
continue; // Sybase/SQL 6.5 use a zero length name to terminate list
}
tabName = in.readNonUnicodeString(nameLen);
bytesRead += nameLen;
}
table = new TableMetaData();
// tabName can be a fully qualified name
int dotPos = tabName.lastIndexOf('.');
if (dotPos > 0) {
table.name = tabName.substring(dotPos + 1);
int nextPos = tabName.lastIndexOf('.', dotPos-1);
if (nextPos + 1 < dotPos) {
table.schema = tabName.substring(nextPos + 1, dotPos);
}
dotPos = nextPos;
nextPos = tabName.lastIndexOf('.', dotPos-1);
if (nextPos + 1 < dotPos) {
table.catalog = tabName.substring(nextPos + 1, dotPos);
}
} else {
table.name = tabName;
}
}
tableList.add(table);
}
if (tableList.size() > 0) {
this.tables = (TableMetaData[]) tableList.toArray(new TableMetaData[tableList.size()]);
}
}
/**
* Process a column infomation token.
* Sent by select for browse or cursor functions.
* @throws IOException
* @throws ProtocolException
*/
private void tdsColumnInfoToken()
throws IOException, ProtocolException
{
final int pktLen = in.readShort();
int bytesRead = 0;
int columnIndex = 0;
while (bytesRead < pktLen) {
// Seems like all columns are always returned in the COL_INFO
// packet and there might be more than 255 columns, so we'll
// just increment a counter instead.
// Ignore the column index.
in.read();
if (columnIndex >= columns.length) {
throw new ProtocolException("Column index " + (columnIndex + 1) +
" invalid in TDS_COLINFO packet");
}
ColInfo col = columns[columnIndex++];
int tableIndex = in.read();
// In some cases (e.g. if the user calls 'CREATE CURSOR'), the
// TDS_TABNAME packet seems to be missing although the table index
// in this packet is > 0. Weird.
// If tables are available check for valid table index.
if (tables != null && tableIndex > tables.length) {
throw new ProtocolException("Table index " + tableIndex +
" invalid in TDS_COLINFO packet");
}
byte flags = (byte)in.read(); // flags
bytesRead += 3;
if (tableIndex != 0 && tables != null) {
TableMetaData table = tables[tableIndex-1];
col.catalog = table.catalog;
col.schema = table.schema;
col.tableName = table.name;
}
col.isKey = (flags & 0x08) != 0;
col.isHidden = (flags & 0x10) != 0;
// If bit 5 is set, we have a column name
if ((flags & 0x20) != 0) {
final int nameLen = in.read();
bytesRead += 1;
final String colName = in.readString(nameLen);
bytesRead += (tdsVersion >= Driver.TDS70) ? nameLen * 2 : nameLen;
col.realName = colName;
}
}
}
/**
* Process an order by token.
* Sent to describe columns in an order by clause.
* @throws IOException
*/
private void tdsOrderByToken()
throws IOException
{
// Skip this packet type
int pktLen = in.readShort();
in.skip(pktLen);
}
/**
* Process a TD4/TDS7 error or informational message.
*
* @throws IOException
*/
private void tdsErrorToken()
throws IOException
{
int pktLen = in.readShort(); // Packet length
int sizeSoFar = 6;
int number = in.readInt();
int state = in.read();
int severity = in.read();
int msgLen = in.readShort();
String message = in.readString(msgLen);
sizeSoFar += 2 + ((tdsVersion >= Driver.TDS70) ? msgLen * 2 : msgLen);
final int srvNameLen = in.read();
String server = in.readString(srvNameLen);
sizeSoFar += 1 + ((tdsVersion >= Driver.TDS70) ? srvNameLen * 2 : srvNameLen);
final int procNameLen = in.read();
String procName = in.readString(procNameLen);
sizeSoFar += 1 + ((tdsVersion >= Driver.TDS70) ? procNameLen * 2 : procNameLen);
int line = in.readShort();
sizeSoFar += 2;
// Skip any EED information to read rest of packet
if (pktLen - sizeSoFar > 0)
in.skip(pktLen - sizeSoFar);
if (currentToken.token == TDS_ERROR_TOKEN)
{
if (severity < 10) {
severity = 11; // Ensure treated as error
}
if (severity >= 20) {
// A fatal error has occured, the connection will be closed by
// the server immediately after the last TDS_DONE packet
fatalError = true;
}
} else {
if (severity > 9) {
severity = 9; // Ensure treated as warning
}
}
messages.addDiagnostic(number, state, severity,
message, server, procName, line);
}
/**
* Process output parameters.
* The type of the preceding token is inspected to determine if this packet
* contains output parameter result data. A TDS5_PARAMFMT2_TOKEN is sent before
* this one in Sybase 12 to introduce output parameter results.
* A TDS5_PARAMFMT_TOKEN is sent before this one to introduce extended error
* information.
*
* @throws IOException
*/
private void tds5ParamsToken() throws IOException, ProtocolException, SQLException {
if (currentToken.dynamParamInfo == null) {
throw new ProtocolException(
"TDS 5 Param results token (0xD7) not preceded by param format (0xEC or 0X20).");
}
for (int i = 0; i < currentToken.dynamParamData.length; i++) {
currentToken.dynamParamData[i] =
TdsData.readData(connection, in, currentToken.dynamParamInfo[i]);
String name = currentToken.dynamParamInfo[i].realName;
//
// Real output parameters will either be unnamed or will have a valid
// parameter name beginning with '@'. Ignore any other Spurious parameters
// such as those returned from calls to writetext in the proc.
//
if (parameters != null
&& (name.length() == 0 || name.startsWith("@"))) {
// Sybase 12+ this token used to set output parameter results
while (++nextParam < parameters.length) {
if (parameters[nextParam].isOutput) {
Object value = currentToken.dynamParamData[i];
if (value != null) {
parameters[nextParam].setOutValue(
Support.convert(connection, value,
parameters[nextParam].jdbcType,
connection.getCharset()));
} else {
parameters[nextParam].setOutValue(null);
}
break;
}
}
}
}
}
/**
* Processes a TDS 5.0 capability token.
*
* Sent after login to describe the server's capabilities.
*
* @throws IOException if an I/O error occurs
*/
private void tdsCapabilityToken() throws IOException, ProtocolException {
in.readShort(); // Packet length
if (in.read() != 1) {
throw new ProtocolException("TDS_CAPABILITY: expected request string");
}
int capLen = in.read();
if (capLen != 11 && capLen != 0) {
throw new ProtocolException("TDS_CAPABILITY: byte count not 11");
}
byte capRequest[] = new byte[11];
if (capLen == 0) {
Logger.println("TDS_CAPABILITY: Invalid request length");
} else {
in.read(capRequest);
}
if (in.read() != 2) {
throw new ProtocolException("TDS_CAPABILITY: expected response string");
}
capLen = in.read();
if (capLen != 10 && capLen != 0) {
throw new ProtocolException("TDS_CAPABILITY: byte count not 10");
}
byte capResponse[] = new byte[10];
if (capLen == 0) {
Logger.println("TDS_CAPABILITY: Invalid response length");
} else {
in.read(capResponse);
}
//
// Request capabilities
//
// jTDS sends 01 0B 4F FF 85 EE EF 65 7F FF FF FF D6
// Sybase 11.92 01 0A 00 00 00 23 61 41 CF FF FF C6
// Sybase 12.52 01 0A 03 84 0A E3 61 41 FF FF FF C6
// Sybase 15.00 01 0B 4F F7 85 EA EB 61 7F FF FF FF C6
//
// Response capabilities
//
// jTDS sends 02 0A 00 00 04 06 80 06 48 00 00 00
// Sybase 11.92 02 0A 00 00 00 00 00 06 00 00 00 00
// Sybase 12.52 02 0A 00 00 00 00 00 06 00 00 00 00
// Sybase 15.00 02 0A 00 00 04 00 00 06 00 00 00 00
//
// Now set the correct attributes for this connection.
// See the CT_LIB documentation for details on the bit
// positions.
//
int capMask = 0;
if ((capRequest[0] & 0x02) == 0x02) {
capMask |= SYB_UNITEXT;
}
if ((capRequest[1] & 0x03) == 0x03) {
capMask |= SYB_DATETIME;
}
if ((capRequest[2] & 0x80) == 0x80) {
capMask |= SYB_UNICODE;
}
if ((capRequest[3] & 0x02) == 0x02) {
capMask |= SYB_EXTCOLINFO;
}
if ((capRequest[2] & 0x01) == 0x01) {
capMask |= SYB_BIGINT;
}
if ((capRequest[4] & 0x04) == 0x04) {
capMask |= SYB_BITNULL;
}
if ((capRequest[7] & 0x30) == 0x30) {
capMask |= SYB_LONGDATA;
}
connection.setSybaseInfo(capMask);
}
/**
* Process an environment change packet.
*
* @throws IOException
* @throws SQLException
*/
private void tdsEnvChangeToken()
throws IOException, SQLException
{
int len = in.readShort();
int type = in.read();
switch (type) {
case TDS_ENV_DATABASE:
{
int clen = in.read();
final String newDb = in.readString(clen);
clen = in.read();
final String oldDb = in.readString(clen);
connection.setDatabase(newDb, oldDb);
break;
}
case TDS_ENV_LANG:
{
int clen = in.read();
String language = in.readString(clen);
clen = in.read();
String oldLang = in.readString(clen);
if (Logger.isActive()) {
Logger.println("Language changed from " + oldLang + " to " + language);
}
break;
}
case TDS_ENV_CHARSET:
{
final int clen = in.read();
final String charset = in.readString(clen);
if (tdsVersion >= Driver.TDS70) {
in.skip(len - 2 - clen * 2);
} else {
in.skip(len - 2 - clen);
}
connection.setServerCharset(charset);
break;
}
case TDS_ENV_PACKSIZE:
{
final int blocksize;
final int clen = in.read();
blocksize = Integer.parseInt(in.readString(clen));
if (tdsVersion >= Driver.TDS70) {
in.skip(len - 2 - clen * 2);
} else {
in.skip(len - 2 - clen);
}
this.connection.setNetPacketSize(blocksize);
out.setBufferSize(blocksize);
if (Logger.isActive()) {
Logger.println("Changed blocksize to " + blocksize);
}
}
break;
case TDS_ENV_LCID:
// Only sent by TDS 7
// In TDS 8 replaced by column specific collation info.
// TODO Make use of this for character set conversions?
in.skip(len - 1);
break;
case TDS_ENV_SQLCOLLATION:
{
int clen = in.read();
byte collation[] = new byte[5];
if (clen == 5) {
in.read(collation);
connection.setCollation(collation);
} else {
in.skip(clen);
}
clen = in.read();
in.skip(clen);
break;
}
default:
{
if (Logger.isActive()) {
Logger.println("Unknown environment change type 0x" +
Integer.toHexString(type));
}
in.skip(len - 1);
break;
}
}
}
/**
* Process a TDS 5 error or informational message.
*
* @throws IOException
*/
private void tds5ErrorToken() throws IOException {
int pktLen = in.readShort(); // Packet length
int sizeSoFar = 6;
int number = in.readInt();
int state = in.read();
int severity = in.read();
// Discard text state
int stateLen = in.read();
in.readNonUnicodeString(stateLen);
in.read(); // == 1 if extended error data follows
// Discard status and transaction state
in.readShort();
sizeSoFar += 4 + stateLen;
int msgLen = in.readShort();
String message = in.readNonUnicodeString(msgLen);
sizeSoFar += 2 + msgLen;
final int srvNameLen = in.read();
String server = in.readNonUnicodeString(srvNameLen);
sizeSoFar += 1 + srvNameLen;
final int procNameLen = in.read();
String procName = in.readNonUnicodeString(procNameLen);
sizeSoFar += 1 + procNameLen;
int line = in.readShort();
sizeSoFar += 2;
// Skip any EED information to read rest of packet
if (pktLen - sizeSoFar > 0)
in.skip(pktLen - sizeSoFar);
if (severity > 10)
{
messages.addDiagnostic(number, state, severity,
message, server, procName, line);
} else {
messages.addDiagnostic(number, state, severity,
message, server, procName, line);
}
}
/**
* Process TDS5 dynamic SQL aknowledgements.
*
* @throws IOException
*/
private void tds5DynamicToken()
throws IOException
{
int pktLen = in.readShort();
byte type = (byte)in.read();
/*byte status = (byte)*/in.read();
pktLen -= 2;
if (type == (byte)0x20) {
// Only handle aknowledgements for now
int len = in.read();
in.skip(len);
pktLen -= len+1;
}
in.skip(pktLen);
}
/**
* Process TDS 5 Dynamic results parameter descriptors.
*
* With Sybase 12+ this has been superseded by the TDS5_PARAMFMT2_TOKEN
* except when used to return extended error information.
*
* @throws IOException
* @throws ProtocolException
*/
private void tds5ParamFmtToken() throws IOException, ProtocolException {
in.readShort(); // Packet length
int paramCnt = in.readShort();
ColInfo[] params = new ColInfo[paramCnt];
for (int i = 0; i < paramCnt; i++) {
//
// Get the parameter details using the
// ColInfo class as the server format is the same.
//
ColInfo col = new ColInfo();
int colNameLen = in.read();
col.realName = in.readNonUnicodeString(colNameLen);
int column_flags = in.read(); /* Flags */
col.isCaseSensitive = false;
col.nullable = ((column_flags & 0x20) != 0)?
ResultSetMetaData.columnNullable:
ResultSetMetaData.columnNoNulls;
col.isWriteable = (column_flags & 0x10) != 0;
col.isIdentity = (column_flags & 0x40) != 0;
col.isKey = (column_flags & 0x02) != 0;
col.isHidden = (column_flags & 0x01) != 0;
col.userType = in.readInt();
if ((byte)in.peek() == TDS_DONE_TOKEN) {
// Sybase 11.92 bug data type missing!
currentToken.dynamParamInfo = null;
currentToken.dynamParamData = null;
// error trapped in sybasePrepare();
messages.addDiagnostic(9999, 0, 16,
"Prepare failed", "", "", 0);
return; // Give up
}
TdsData.readType(in, col);
// Skip locale information
in.skip(1);
params[i] = col;
}
currentToken.dynamParamInfo = params;
currentToken.dynamParamData = new Object[paramCnt];
}
/**
* Process a NTLM Authentication challenge.
*
* @throws IOException
* @throws ProtocolException
*/
private void tdsNtlmAuthToken()
throws IOException, ProtocolException
{
int pktLen = in.readShort(); // Packet length
int hdrLen = 40;
if (pktLen < hdrLen)
throw new ProtocolException("NTLM challenge: packet is too small:" + pktLen);
byte[] ntlmMessage = new byte[pktLen];
in.read(ntlmMessage);
final int seq = getIntFromBuffer(ntlmMessage, 8);
if (seq != 2)
throw new ProtocolException("NTLM challenge: got unexpected sequence number:" + seq);
final int flags = getIntFromBuffer( ntlmMessage, 20 );
//NOTE: the context is always included; if not local, then it is just
// set to all zeros.
//boolean hasContext = ((flags & 0x4000) != 0);
//final boolean hasContext = true;
//NOTE: even if target is omitted, the length will be zero.
//final boolean hasTarget = ((flags & 0x800000) != 0);
//extract the target, if present. This will be used for ntlmv2 auth.
final int headerOffset = 40; // The assumes the context is always there, which appears to be the case.
//header has: 2 byte lenght, 2 byte allocated space, and four-byte offset.
int size = getShortFromBuffer( ntlmMessage, headerOffset);
int offset = getIntFromBuffer( ntlmMessage, headerOffset + 4);
currentToken.ntlmTarget = new byte[size];
System.arraycopy(ntlmMessage, offset, currentToken.ntlmTarget, 0, size);
currentToken.nonce = new byte[8];
currentToken.ntlmMessage = ntlmMessage;
System.arraycopy(ntlmMessage, 24, currentToken.nonce, 0, 8);
}
private static int getIntFromBuffer(byte[] buf, int offset)
{
int b1 = ((int) buf[offset] & 0xff);
int b2 = ((int) buf[offset+1] & 0xff) << 8;
int b3 = ((int) buf[offset+2] & 0xff) << 16;
int b4 = ((int) buf[offset+3] & 0xff) << 24;
return b4 | b3 | b2 | b1;
}
private static int getShortFromBuffer(byte[] buf, int offset)
{
int b1 = ((int) buf[offset] & 0xff);
int b2 = ((int) buf[offset+1] & 0xff) << 8;
return b2 | b1;
}
/**
* Process a TDS 5.0 result set packet.
*
* @throws IOException
* @throws ProtocolException
*/
private void tds5ResultToken() throws IOException, ProtocolException {
in.readShort(); // Packet length
int colCnt = in.readShort();
this.columns = new ColInfo[colCnt];
this.rowData = new Object[colCnt];
this.tables = null;
for (int colNum = 0; colNum < colCnt; ++colNum) {
//
// Get the column name
//
ColInfo col = new ColInfo();
int colNameLen = in.read();
col.realName = in.readNonUnicodeString(colNameLen);
col.name = col.realName;
int column_flags = in.read(); /* Flags */
col.isCaseSensitive = false;
col.nullable = ((column_flags & 0x20) != 0)?
ResultSetMetaData.columnNullable:
ResultSetMetaData.columnNoNulls;
col.isWriteable = (column_flags & 0x10) != 0;
col.isIdentity = (column_flags & 0x40) != 0;
col.isKey = (column_flags & 0x02) != 0;
col.isHidden = (column_flags & 0x01) != 0;
col.userType = in.readInt();
TdsData.readType(in, col);
// Skip locale information
in.skip(1);
columns[colNum] = col;
}
endOfResults = false;
}
/**
* Process a DONE, DONEINPROC or DONEPROC token.
*
* @throws IOException
*/
private void tdsDoneToken() throws IOException {
currentToken.status = (byte)in.read();
in.skip(1);
currentToken.operation = (byte)in.read();
in.skip(1);
currentToken.updateCount = in.readInt();
if (!endOfResults) {
// This will eliminate the select row count for sybase
currentToken.status &= ~DONE_ROW_COUNT;
endOfResults = true;
}
//
// Check for cancel ack
//
if ((currentToken.status & DONE_CANCEL) != 0) {
// Synchronize resetting of the cancelPending flag to ensure it
// doesn't happen during the sending of a cancel request
synchronized (cancelMonitor) {
cancelPending = false;
// Only throw an exception if this was a cancel() call
if (cancelMonitor[0] == ASYNC_CANCEL) {
messages.addException(
new SQLException(Messages.get("error.generic.cancelled",
"Statement"),
"HY008"));
}
}
}
if ((currentToken.status & DONE_MORE_RESULTS) == 0) {
//
// There are no more results or pending cancel packets
// to process.
//
endOfResponse = !cancelPending;
if (fatalError) {
// A fatal error has occured, the server has closed the
// connection
connection.setClosed();
}
}
if (serverType == Driver.SQLSERVER) {
//
// MS SQL Server provides additional information we
// can use to return special row counts for DDL etc.
//
if (currentToken.operation == (byte) 0xC1) {
currentToken.status &= ~DONE_ROW_COUNT;
}
}
}
/**
* Execute SQL using TDS 4.2 protocol.
*
* @param sql The SQL statement to execute.
* @param procName Stored procedure to execute or null.
* @param parameters Parameters for call or null.
* @param noMetaData Suppress meta data for cursor calls.
* @throws SQLException
*/
private void executeSQL42(String sql,
String procName,
ParamInfo[] parameters,
boolean noMetaData,
boolean sendNow)
throws IOException, SQLException {
if (procName != null) {
// RPC call
out.setPacketType(RPC_PKT);
byte[] buf = Support.encodeString(connection.getCharset(), procName);
out.write((byte) buf.length);
out.write(buf);
out.write((short) (noMetaData ? 2 : 0));
if (parameters != null) {
for (int i = nextParam + 1; i < parameters.length; i++) {
if (parameters[i].name != null) {
buf = Support.encodeString(connection.getCharset(),
parameters[i].name);
out.write((byte) buf.length);
out.write(buf);
} else {
out.write((byte) 0);
}
out.write((byte) (parameters[i].isOutput ? 1 : 0));
TdsData.writeParam(out,
connection.getCharsetInfo(),
null,
parameters[i]);
}
}
if (!sendNow) {
// Send end of packet byte to batch RPC
out.write((byte) DONE_END_OF_RESPONSE);
}
} else if (sql.length() > 0) {
if (parameters != null) {
sql = Support.substituteParameters(sql, parameters, connection);
}
out.setPacketType(QUERY_PKT);
out.write(sql);
if (!sendNow) {
// Batch SQL statements
out.write(" ");
}
}
}
/**
* Execute SQL using TDS 5.0 protocol.
*
* @param sql The SQL statement to execute.
* @param procName Stored procedure to execute or null.
* @param parameters Parameters for call or null.
* @throws SQLException
*/
private void executeSQL50(String sql,
String procName,
ParamInfo[] parameters)
throws IOException, SQLException {
boolean haveParams = parameters != null;
boolean useParamNames = false;
currentToken.dynamParamInfo = null;
currentToken.dynamParamData = null;
//
// Sybase does not allow text or image parameters as parameters
// to statements or stored procedures. With Sybase 12.5 it is
// possible to use a new TDS data type to send long data as
// parameters to statements (but not procedures). This usage
// replaces the writetext command that had to be used in the past.
// As we do not support writetext, with older versions of Sybase
// we just give up and embed all text/image data in the SQL statement.
//
for (int i = 0; haveParams && i < parameters.length; i++) {
if ("text".equals(parameters[i].sqlType)
|| "image".equals(parameters[i].sqlType)
|| "unitext".equals(parameters[i].sqlType)) {
if (procName != null && procName.length() > 0) {
// Call to store proc nothing we can do
if ("text".equals(parameters[i].sqlType)
|| "unitext".equals(parameters[i].sqlType)) {
throw new SQLException(
Messages.get("error.chartoolong"), "HY000");
}
throw new SQLException(
Messages.get("error.bintoolong"), "HY000");
}
if (parameters[i].tdsType != TdsData.SYBLONGDATA) {
// prepared statement substitute parameters into SQL
sql = Support.substituteParameters(sql, parameters, connection);
haveParams = false;
procName = null;
break;
}
}
}
out.setPacketType(SYBQUERY_PKT);
if (procName == null) {
// Use TDS_LANGUAGE TOKEN with optional parameters
out.write((byte)TDS_LANG_TOKEN);
if (haveParams) {
sql = Support.substituteParamMarkers(sql, parameters);
}
if (connection.isWideChar()) {
// Need to preconvert string to get correct length
byte[] buf = Support.encodeString(connection.getCharset(), sql);
out.write((int) buf.length + 1);
out.write((byte)(haveParams ? 1 : 0));
out.write(buf);
} else {
out.write((int) sql.length() + 1);
out.write((byte) (haveParams ? 1 : 0));
out.write(sql);
}
} else if (procName.startsWith("#jtds")) {
// Dynamic light weight procedure call
out.write((byte) TDS5_DYNAMIC_TOKEN);
out.write((short) (procName.length() + 4));
out.write((byte) 2);
out.write((byte) (haveParams ? 1 : 0));
out.write((byte) (procName.length() - 1));
out.write(procName.substring(1));
out.write((short) 0);
} else {
byte buf[] = Support.encodeString(connection.getCharset(), procName);
// RPC call
out.write((byte) TDS_DBRPC_TOKEN);
out.write((short) (buf.length + 3));
out.write((byte) buf.length);
out.write(buf);
out.write((short) (haveParams ? 2 : 0));
useParamNames = true;
}
//
// Output any parameters
//
if (haveParams) {
// First write parameter descriptors
out.write((byte) TDS5_PARAMFMT_TOKEN);
int len = 2;
for (int i = nextParam + 1; i < parameters.length; i++) {
len += TdsData.getTds5ParamSize(connection.getCharset(),
connection.isWideChar(),
parameters[i],
useParamNames);
}
out.write((short) len);
out.write((short) ((nextParam < 0) ? parameters.length : parameters.length - 1));
for (int i = nextParam + 1; i < parameters.length; i++) {
TdsData.writeTds5ParamFmt(out,
connection.getCharset(),
connection.isWideChar(),
parameters[i],
useParamNames);
}
// Now write the actual data
out.write((byte) TDS5_PARAMS_TOKEN);
for (int i = nextParam + 1; i < parameters.length; i++) {
TdsData.writeTds5Param(out,
connection.getCharsetInfo(),
parameters[i]);
}
}
}
/**
* Returns
* Implementation notes:
*
* This convenience method calls {@link #linkException(Exception, Throwable)}
* and casts the result for cleaner code elsewhere.
*
* @param sqle The
* This convenience method calls {@link #linkException(Exception, Throwable)}
* and casts the result for cleaner code elsewhere.
*
* @param sqle The
* If running under JVM 1.4+ the Format is NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN.
*
* @return The uniqueidentifier as a
* Implementation notes:
*
* Used by the login timer to abort a login attempt.
*/
void forceClose() {
try {
getOut().close();
}
catch (Exception e) {
// Ignore
}
finally {
setOut(null);
}
try {
getIn().close();
}
catch (Exception e) {
// Ignore
}
finally {
setIn(null);
}
try {
if (pipe != null) {
pipe.close();
}
} catch (IOException ex) {
} finally {
pipe = null;
}
}
/**
* Set the socket timeout.
*
* @param timeout the timeout value in milliseconds
*/
protected void setTimeout(int timeout) {
// FIXME - implement timeout functionality
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/ClobImpl.java 0000644 0001750 0001750 00000020646 11316672660 025454 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.io.*;
import java.sql.Clob;
import java.sql.SQLException;
import net.sourceforge.jtds.util.BlobBuffer;
/**
* An in-memory or disk based representation of character data.
* The undocumented Microsoft sp_cursor procedures are used.
*
* Implementation notes:
*
* Implementation notes:
*
* Algorithm from Fliegel, H F and van Flandern, T C (1968).
* Communications of the ACM, Vol 11, No 10 (October, 1968).
*
*
* Implementation notes:
*
* This method will retry for Notes:
*
* Synchronized because it accesses the procedure cache and the
*
* Not explicitly synchronized because it's only called by synchronized
* methods.
*
* @param key The signature of the procedure to cache.
* @param proc The stored procedure descriptor.
*/
void addCachedProcedure(String key, ProcEntry proc) {
statementCache.put(key, proc);
if (!autoCommit
&& proc.getType() == ProcEntry.PROCEDURE
&& serverType == Driver.SQLSERVER) {
procInTran.add(key);
}
}
/**
* Remove a stored procedure from the cache.
*
* Not explicitly synchronized because it's only called by synchronized
* methods.
*
* @param key The signature of the procedure to remove from the cache.
*/
void removeCachedProcedure(String key) {
statementCache.remove(key);
if (!autoCommit) {
procInTran.remove(key);
}
}
/**
* Retrieves the maximum statement cache size.
*
* @return the maximum statement cache size
*/
int getMaxStatements() {
return maxStatements;
}
/**
* Retrieves the server type.
*
* @return the server type as an
* Will throw an
* Should only be called from the constructor.
*
* @return the default server charset
* @throws SQLException if an error condition occurs
*/
private String determineServerCharset() throws SQLException {
String queryStr = null;
switch (serverType) {
case Driver.SQLSERVER:
if (databaseProductVersion.indexOf("6.5") >= 0) {
queryStr = SQL_SERVER_65_CHARSET_QUERY;
} else {
// This will never happen. Versions 7.0 and 2000 of SQL
// Server always send ENVCHANGE packets, even over TDS 4.2.
throw new SQLException(
"Please use TDS protocol version 7.0 or higher");
}
break;
case Driver.SYBASE:
// There's no need to check for versions here
queryStr = SYBASE_SERVER_CHARSET_QUERY;
break;
}
Statement stmt = this.createStatement();
ResultSet rs = stmt.executeQuery(queryStr);
rs.next();
String charset = rs.getString(1);
rs.close();
stmt.close();
return charset;
}
/**
* Set the default collation for this connection.
*
* Set by a SQL Server 2000 environment change packet. The collation
* consists of the following fields:
*
* Synchronized because it accesses the statement list, the statement cache
* and the
* Used to identify same resource manager in XA transactions.
*
* @return the hostname and port as a
* Calling the method close on a
* Note: A
* Synchronized because it accesses the statement list and the
*
* NB. As allowed by the JDBC standard and like most other drivers,
* this implementation only allows one open result set at a time.
*
* Implementation notes:
*
* I experimented with allowing multiple open result sets as supported
* by the origianal jTDS but rejected this approach for the following
* reasons:
*
* There are two types of attributes that the cache is concerned with:
*
* The caching types provided by jTDS should be:
*
* Implementation notes:
*
* Implementation note:
*
* Getter/setter methods have not been provided to avoid clutter
* as this class is used in many places in the driver.
* As the class is package private this seems reasonable.
*
* @author Mike Hutchinson
* @version $Id: ColInfo.java,v 1.4 2004/11/24 06:42:01 alin_sinpalean Exp $
*/
public class ColInfo {
/** Internal TDS data type */
int tdsType;
/** JDBC type constant from java.sql.Types */
int jdbcType;
/** Column actual table name */
String realName;
/** Column label / name */
String name;
/** Table name owning this column */
String tableName;
/** Database owning this column */
String catalog;
/** User owning this column */
String schema;
/** Column data type supports SQL NULL */
int nullable;
/** Column name is case sensitive */
boolean isCaseSensitive;
/** Column may be updated */
boolean isWriteable;
/** Column is an indentity column */
boolean isIdentity;
/** Column may be used as a key */
boolean isKey;
/** Column should be hidden */
boolean isHidden;
/** Database ID for UDT */
int userType;
/** MS SQL2000 collation */
byte[] collation;
/** Character set descriptor (if different from default) */
CharsetInfo charsetInfo;
/** Column display size */
int displaySize;
/** Column buffer (max) size */
int bufferSize;
/** Column decimal precision */
int precision;
/** Column decimal scale */
int scale;
/** The SQL type name for this column. */
String sqlType;
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/SQLDiagnostic.java 0000644 0001750 0001750 00000052467 11316672660 026425 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.sql.DataTruncation;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.util.HashMap;
/**
* Helper class for handling SQL warnings and errors. Assigns SQL state values
* in accordance to the native error number returned by the database server.
*
* @author Alin Sinpalean
* @author Mike Hutchinson
* @version $Id: SQLDiagnostic.java,v 1.12 2007/08/05 20:17:54 bheineman Exp $
*/
class SQLDiagnostic {
/**
* Map to convert Microsoft SQL server error codes to ANSI SQLSTATE codes.
* The values in this table are derived from the list compiled by the
* FreeTDS project. Thank you for the hard work.
*/
private final static HashMap mssqlStates = new HashMap();
/**
* Map to convert Sybase SQL server error codes to ANSI SQLSTATE codes.
* The values in this table are derived from the list compiled by the
* FreeTDS project. Thank you for the hard work.
*/
private final static HashMap sybStates = new HashMap();
static {
// When adding values into this map please ensure that you maintain
// the ascending order. This is for readability purposes only, but it's
// still important.
mssqlStates.put(new Integer(102), "42000"); // ADDED
mssqlStates.put(new Integer(105), "37000"); // ADDED
mssqlStates.put(new Integer(109), "21S01");
mssqlStates.put(new Integer(110), "21S01");
mssqlStates.put(new Integer(113), "42000");
mssqlStates.put(new Integer(131), "37000");
mssqlStates.put(new Integer(168), "22003");
mssqlStates.put(new Integer(170), "37000");
mssqlStates.put(new Integer(174), "37000");
mssqlStates.put(new Integer(195), "42000"); // ADDED
mssqlStates.put(new Integer(201), "37000");
mssqlStates.put(new Integer(206), "22005"); // ADDED
mssqlStates.put(new Integer(207), "42S22"); // (i-net is 42000)
mssqlStates.put(new Integer(208), "S0002"); // MODIFIED: was 42S02 (i-net is 42000) (Microsoft is S0002)
mssqlStates.put(new Integer(210), "22007"); // ? (i-net is 22008)
mssqlStates.put(new Integer(211), "22008"); // ADDED
mssqlStates.put(new Integer(213), "42000"); // MODIFIED: was 21S01
mssqlStates.put(new Integer(220), "22003");
mssqlStates.put(new Integer(229), "42000");
mssqlStates.put(new Integer(230), "42000");
mssqlStates.put(new Integer(232), "22003");
mssqlStates.put(new Integer(233), "23000"); // ADDED
mssqlStates.put(new Integer(234), "22003"); // ADDED
mssqlStates.put(new Integer(235), "22005"); // ADDED
mssqlStates.put(new Integer(236), "22003"); // ADDED
mssqlStates.put(new Integer(237), "22003"); // ADDED
mssqlStates.put(new Integer(238), "22003"); // ADDED
mssqlStates.put(new Integer(241), "22007"); // ? (i-net is 22008)
mssqlStates.put(new Integer(242), "22008");
mssqlStates.put(new Integer(244), "22003"); // ADDED
mssqlStates.put(new Integer(245), "22018"); // ? (i-net is 22005)
mssqlStates.put(new Integer(246), "22003"); // ADDED
mssqlStates.put(new Integer(247), "22005"); // ADDED
mssqlStates.put(new Integer(248), "22003"); // ADDED
mssqlStates.put(new Integer(249), "22005"); // ADDED
mssqlStates.put(new Integer(256), "22005"); // ADDED
mssqlStates.put(new Integer(257), "22005"); // ADDED
mssqlStates.put(new Integer(260), "42000"); // ADDED
mssqlStates.put(new Integer(262), "42000");
mssqlStates.put(new Integer(266), "25000");
mssqlStates.put(new Integer(272), "23000"); // ADDED
mssqlStates.put(new Integer(273), "23000"); // ADDED
mssqlStates.put(new Integer(277), "25000"); // ADDED
mssqlStates.put(new Integer(295), "22007"); // ? (i-net is 22008)
mssqlStates.put(new Integer(296), "22008");
mssqlStates.put(new Integer(298), "22008");
mssqlStates.put(new Integer(305), "22005"); // ADDED
mssqlStates.put(new Integer(307), "42S12");
mssqlStates.put(new Integer(308), "42S12");
mssqlStates.put(new Integer(310), "22025"); // ADDED
mssqlStates.put(new Integer(409), "22005"); // ADDED
mssqlStates.put(new Integer(506), "22019"); // ADDED
mssqlStates.put(new Integer(512), "21000");
mssqlStates.put(new Integer(515), "23000");
mssqlStates.put(new Integer(517), "22008"); // ?
mssqlStates.put(new Integer(518), "22005"); // ADDED
mssqlStates.put(new Integer(519), "22003"); // ADDED
mssqlStates.put(new Integer(520), "22003"); // ADDED
mssqlStates.put(new Integer(521), "22003"); // ADDED
mssqlStates.put(new Integer(522), "22003"); // ADDED
mssqlStates.put(new Integer(523), "22003"); // ADDED
mssqlStates.put(new Integer(524), "22003"); // ADDED
mssqlStates.put(new Integer(529), "22005"); // ADDED
mssqlStates.put(new Integer(530), "23000"); // ADDED
mssqlStates.put(new Integer(532), "01001"); // ADDED
mssqlStates.put(new Integer(535), "22003"); // MODIFIED: was 22008
mssqlStates.put(new Integer(542), "22008");
mssqlStates.put(new Integer(544), "23000");
mssqlStates.put(new Integer(547), "23000");
mssqlStates.put(new Integer(550), "44000"); // MODIFIED: was 23000
mssqlStates.put(new Integer(611), "25000"); // ADDED
mssqlStates.put(new Integer(626), "25000");
mssqlStates.put(new Integer(627), "25000");
mssqlStates.put(new Integer(628), "25000");
mssqlStates.put(new Integer(911), "08004"); // WRONG: db not found != connection rejected
mssqlStates.put(new Integer(1007), "22003");
mssqlStates.put(new Integer(1010), "22019"); // ADDED
mssqlStates.put(new Integer(1205), "40001"); // ADDED
mssqlStates.put(new Integer(1211), "40001"); // ADDED
mssqlStates.put(new Integer(1505), "23000");
mssqlStates.put(new Integer(1508), "23000");
mssqlStates.put(new Integer(1774), "21S02");
mssqlStates.put(new Integer(1911), "42S22");
mssqlStates.put(new Integer(1913), "42S11");
mssqlStates.put(new Integer(2526), "37000");
mssqlStates.put(new Integer(2557), "42000");
mssqlStates.put(new Integer(2571), "42000");
mssqlStates.put(new Integer(2601), "23000"); // ADDED
mssqlStates.put(new Integer(2615), "23000"); // ADDED
mssqlStates.put(new Integer(2625), "40001"); // ADDED
mssqlStates.put(new Integer(2626), "23000"); // ADDED
mssqlStates.put(new Integer(2627), "23000");
mssqlStates.put(new Integer(2714), "S0001"); // MODIFIED: was 42S01 (Microsoft is S0001)
mssqlStates.put(new Integer(2760), "42000");
mssqlStates.put(new Integer(2812), "37000");
mssqlStates.put(new Integer(3110), "42000");
mssqlStates.put(new Integer(3309), "40001"); // ADDED
mssqlStates.put(new Integer(3604), "23000"); // ADDED
mssqlStates.put(new Integer(3605), "23000"); // ADDED
mssqlStates.put(new Integer(3606), "22003");
mssqlStates.put(new Integer(3607), "22012");
mssqlStates.put(new Integer(3621), "01000");
mssqlStates.put(new Integer(3701), "42S02");
mssqlStates.put(new Integer(3704), "42000");
mssqlStates.put(new Integer(3725), "23000");
mssqlStates.put(new Integer(3726), "23000");
mssqlStates.put(new Integer(3902), "25000");
mssqlStates.put(new Integer(3903), "25000");
mssqlStates.put(new Integer(3906), "25000"); // ADDED
mssqlStates.put(new Integer(3908), "25000"); // ADDED
mssqlStates.put(new Integer(3915), "25000"); // ADDED
mssqlStates.put(new Integer(3916), "25000");
mssqlStates.put(new Integer(3918), "25000");
mssqlStates.put(new Integer(3919), "25000");
mssqlStates.put(new Integer(3921), "25000");
mssqlStates.put(new Integer(3922), "25000");
mssqlStates.put(new Integer(3926), "25000");
mssqlStates.put(new Integer(3960), "S0005"); // ADDED for Feature Request 1491811
mssqlStates.put(new Integer(4415), "44000"); // MODIFIED: was 23000
mssqlStates.put(new Integer(4613), "42000");
mssqlStates.put(new Integer(4618), "42000");
mssqlStates.put(new Integer(4712), "23000");
mssqlStates.put(new Integer(4834), "42000");
mssqlStates.put(new Integer(4924), "42S22");
mssqlStates.put(new Integer(4925), "42S21");
mssqlStates.put(new Integer(4926), "42S22");
mssqlStates.put(new Integer(5011), "42000");
mssqlStates.put(new Integer(5116), "42000");
mssqlStates.put(new Integer(5146), "22003");
mssqlStates.put(new Integer(5812), "42000");
mssqlStates.put(new Integer(6004), "42000");
mssqlStates.put(new Integer(6102), "42000");
mssqlStates.put(new Integer(6104), "37000");
mssqlStates.put(new Integer(6401), "25000"); // ADDED
mssqlStates.put(new Integer(7112), "40001"); // ADDED
mssqlStates.put(new Integer(7956), "42000");
mssqlStates.put(new Integer(7969), "25000");
mssqlStates.put(new Integer(8114), "37000");
mssqlStates.put(new Integer(8115), "22003");
mssqlStates.put(new Integer(8134), "22012");
mssqlStates.put(new Integer(8144), "37000");
mssqlStates.put(new Integer(8152), "22001");
mssqlStates.put(new Integer(8162), "37000"); // ADDED
mssqlStates.put(new Integer(8153), "01003");
mssqlStates.put(new Integer(8506), "25000");
mssqlStates.put(new Integer(10015), "22003"); // ADDED
mssqlStates.put(new Integer(10033), "42S12");
mssqlStates.put(new Integer(10055), "23000");
mssqlStates.put(new Integer(10065), "23000");
mssqlStates.put(new Integer(10095), "01001"); // ADDED
mssqlStates.put(new Integer(11010), "42000");
mssqlStates.put(new Integer(11011), "23000");
mssqlStates.put(new Integer(11040), "23000");
mssqlStates.put(new Integer(11045), "42000");
mssqlStates.put(new Integer(14126), "42000");
mssqlStates.put(new Integer(15247), "42000");
mssqlStates.put(new Integer(15323), "42S12");
mssqlStates.put(new Integer(15605), "42S11");
mssqlStates.put(new Integer(15622), "42000");
mssqlStates.put(new Integer(15626), "25000");
mssqlStates.put(new Integer(15645), "42S22");
mssqlStates.put(new Integer(16905), "24000");
mssqlStates.put(new Integer(16909), "24000"); // ADDED
mssqlStates.put(new Integer(16911), "24000"); // ADDED
mssqlStates.put(new Integer(16917), "24000");
mssqlStates.put(new Integer(16934), "24000"); // ADDED
mssqlStates.put(new Integer(16946), "24000");
mssqlStates.put(new Integer(16950), "24000");
mssqlStates.put(new Integer(16999), "24000");
mssqlStates.put(new Integer(17308), "42000");
mssqlStates.put(new Integer(17571), "42000");
mssqlStates.put(new Integer(18002), "42000");
mssqlStates.put(new Integer(18452), "28000");
mssqlStates.put(new Integer(18456), "28000");
mssqlStates.put(new Integer(18833), "42S12");
mssqlStates.put(new Integer(20604), "42000");
mssqlStates.put(new Integer(21049), "42000");
mssqlStates.put(new Integer(21166), "42S22");
mssqlStates.put(new Integer(21255), "42S21");
// When adding values into this map please ensure that you maintain
// the ascending order. This is for readability purposes only, but it's
// still important.
sybStates.put(new Integer(102), "37000");
sybStates.put(new Integer(109), "21S01");
sybStates.put(new Integer(110), "21S01");
sybStates.put(new Integer(113), "42000");
sybStates.put(new Integer(168), "22003");
sybStates.put(new Integer(201), "37000");
sybStates.put(new Integer(207), "42S22");
sybStates.put(new Integer(208), "42S02");
sybStates.put(new Integer(213), "21S01");
sybStates.put(new Integer(220), "22003");
sybStates.put(new Integer(227), "22003");
sybStates.put(new Integer(229), "42000");
sybStates.put(new Integer(230), "42000");
sybStates.put(new Integer(232), "22003");
sybStates.put(new Integer(233), "23000");
sybStates.put(new Integer(245), "22018");
sybStates.put(new Integer(247), "22003");
sybStates.put(new Integer(257), "37000");
sybStates.put(new Integer(262), "42000");
sybStates.put(new Integer(277), "25000");
sybStates.put(new Integer(307), "42S12");
sybStates.put(new Integer(512), "21000");
sybStates.put(new Integer(517), "22008");
sybStates.put(new Integer(535), "22008");
sybStates.put(new Integer(542), "22008");
sybStates.put(new Integer(544), "23000");
sybStates.put(new Integer(545), "23000");
sybStates.put(new Integer(546), "23000");
sybStates.put(new Integer(547), "23000");
sybStates.put(new Integer(548), "23000");
sybStates.put(new Integer(549), "23000");
sybStates.put(new Integer(550), "23000");
sybStates.put(new Integer(558), "24000");
sybStates.put(new Integer(559), "24000");
sybStates.put(new Integer(562), "24000");
sybStates.put(new Integer(565), "24000");
sybStates.put(new Integer(583), "24000");
sybStates.put(new Integer(611), "25000");
sybStates.put(new Integer(627), "25000");
sybStates.put(new Integer(628), "25000");
sybStates.put(new Integer(641), "25000");
sybStates.put(new Integer(642), "25000");
sybStates.put(new Integer(911), "08004");
sybStates.put(new Integer(1276), "25000");
sybStates.put(new Integer(1505), "23000");
sybStates.put(new Integer(1508), "23000");
sybStates.put(new Integer(1715), "21S02");
sybStates.put(new Integer(1720), "42S22");
sybStates.put(new Integer(1913), "42S11");
sybStates.put(new Integer(1921), "42S21");
sybStates.put(new Integer(2526), "37000");
sybStates.put(new Integer(2714), "42S01");
sybStates.put(new Integer(2812), "37000");
sybStates.put(new Integer(3606), "22003");
sybStates.put(new Integer(3607), "22012");
sybStates.put(new Integer(3621), "01000");
sybStates.put(new Integer(3701), "42S02");
sybStates.put(new Integer(3902), "25000");
sybStates.put(new Integer(3903), "25000");
sybStates.put(new Integer(4602), "42000");
sybStates.put(new Integer(4603), "42000");
sybStates.put(new Integer(4608), "42000");
sybStates.put(new Integer(4934), "42S22");
sybStates.put(new Integer(6104), "37000");
sybStates.put(new Integer(6235), "24000");
sybStates.put(new Integer(6259), "24000");
sybStates.put(new Integer(6260), "24000");
sybStates.put(new Integer(7010), "42S12");
sybStates.put(new Integer(7327), "37000");
sybStates.put(new Integer(9501), "01003");
sybStates.put(new Integer(9502), "22001");
sybStates.put(new Integer(10306), "42000");
sybStates.put(new Integer(10323), "42000");
sybStates.put(new Integer(10330), "42000");
sybStates.put(new Integer(10331), "42000");
sybStates.put(new Integer(10332), "42000");
sybStates.put(new Integer(11021), "37000");
sybStates.put(new Integer(11110), "42000");
sybStates.put(new Integer(11113), "42000");
sybStates.put(new Integer(11118), "42000");
sybStates.put(new Integer(11121), "42000");
sybStates.put(new Integer(17222), "42000");
sybStates.put(new Integer(17223), "42000");
sybStates.put(new Integer(18091), "42S12");
sybStates.put(new Integer(18117), "42S22");
sybStates.put(new Integer(18350), "42000");
sybStates.put(new Integer(18351), "42000");
}
/**
* SQL Server type. Either
* An example of the return packet format is as follows:
*
*
* Implementation note:
*
* NB. Only reliable where the charset is single byte.
*
* @param in The Reader object with the data.
* @param length The length of the data in bytes.
* @throws IOException
*/
void writeReaderBytes(Reader in, int length) throws IOException {
char buffer[] = new char[1024];
for (int i = 0; i < length;) {
int result = in.read(buffer);
if (result == -1) {
throw new java.io.IOException(
"Data in stream less than specified by length");
} else if (i + result > length) {
throw new java.io.IOException(
"More data in stream than specified by length");
}
write(Support.encodeString(socket.getCharset(), new String(buffer, 0, result)));
i += result;
}
}
/**
* Write a BigDecimal value to the output stream.
*
* @param value The BigDecimal value to write.
* @throws IOException
*/
void write(BigDecimal value) throws IOException {
if (value == null) {
write((byte) 0);
} else {
byte signum = (byte) (value.signum() < 0 ? 0 : 1);
BigInteger bi = value.unscaledValue();
byte mantisse[] = bi.abs().toByteArray();
byte len = (byte) (mantisse.length + 1);
if (len > getMaxDecimalBytes()) {
// Should never happen now as value is normalized elsewhere
throw new IOException("BigDecimal to big to send");
}
if (socket.serverType == Driver.SYBASE) {
write((byte) len);
// Sybase TDS5 stores MSB first opposite sign!
// length, prec, scale already sent in parameter descriptor.
write((byte) ((signum == 0) ? 1 : 0));
for (int i = 0; i < mantisse.length; i++) {
write((byte) mantisse[i]);
}
} else {
write((byte) len);
write((byte) signum);
for (int i = mantisse.length - 1; i >= 0; i--) {
write((byte) mantisse[i]);
}
}
}
}
/**
* Flush the packet to the output stream setting the last packet flag.
*
* @throws IOException
*/
void flush() throws IOException {
putPacket(1);
}
/**
* Close the output stream.
*/
void close() {
isClosed = true;
}
/**
* Retrieve the TDS version number.
*
* @return The TDS version as an
* Implementation note:
*
* Constraints and assumptions:
* ntlmauth.dll is on the path.
*
* @param serverName server host name
* @param database required database
* @param user user name
* @param password user password
* @param domain Windows NT domain (or null)
* @param appName application name
* @param progName program name
* @param wsid workstation ID
* @param language server language for messages
* @param macAddress client network MAC address
* @param netPacketSize TDS packet size to use
* @throws IOException if an I/O error occurs
*/
private void sendMSLoginPkt(final String serverName,
final String database,
final String user,
final String password,
final String domain,
final String appName,
final String progName,
final String wsid,
final String language,
final String macAddress,
final int netPacketSize)
throws IOException, SQLException {
final byte[] empty = new byte[0];
boolean ntlmAuth = false;
byte[] ntlmMessage = null;
if (user == null || user.length() == 0) {
// See if executing on a Windows platform and if so try and
// use the single sign on native library.
if (Support.isWindowsOS()) {
ntlmAuthSSO = true;
ntlmAuth = true;
} else {
throw new SQLException(Messages.get("error.connection.sso"),
"08001");
}
} else if (domain != null && domain.length() > 0) {
// Assume we want to use Windows authentication with
// supplied user and password.
ntlmAuth = true;
}
if (ntlmAuthSSO) {
try {
// Create the NTLM request block using the native library
sspiJNIClient = SSPIJNIClient.getInstance();
ntlmMessage = sspiJNIClient.invokePrepareSSORequest();
} catch (Exception e) {
throw new IOException("SSO Failed: " + e.getMessage());
}
}
//mdb:begin-change
short packSize = (short) (86 + 2 *
(wsid.length() +
appName.length() +
serverName.length() +
progName.length() +
database.length() +
language.length()));
final short authLen;
//NOTE(mdb): ntlm includes auth block; sql auth includes uname and pwd.
if (ntlmAuth) {
if (ntlmAuthSSO && ntlmMessage != null) {
authLen = (short) ntlmMessage.length;
} else {
authLen = (short) (32 + domain.length());
}
packSize += authLen;
} else {
authLen = 0;
packSize += (2 * (user.length() + password.length()));
}
//mdb:end-change
out.setPacketType(MSLOGIN_PKT);
out.write((int)packSize);
// TDS version
if (tdsVersion == Driver.TDS70) {
out.write((int)0x70000000);
} else {
out.write((int)0x71000001);
}
// Network Packet size requested by client
out.write((int)netPacketSize);
// Program version?
out.write((int)7);
// Process ID
out.write(connection.getProcessId());
// Connection ID
out.write((int)0);
// 0x20: enable warning messages if USE "set offsets from on".
*/
private void tdsOffsetsToken() throws IOException {
/*int keyword =*/ in.read();
/*int unknown =*/ in.read();
/*int offset =*/ in.readShort();
}
/**
* Process a TDS 7.0 result set token.
*
* @throws IOException
* @throws ProtocolException
*/
private void tds7ResultToken()
throws IOException, ProtocolException, SQLException {
endOfResults = false;
int colCnt = in.readShort();
if (colCnt < 0) {
// Short packet returned by TDS8 when the column meta data is
// supressed on cursor fetch etc.
// NB. With TDS7 no result set packet is returned at all.
return;
}
this.columns = new ColInfo[colCnt];
this.rowData = new Object[colCnt];
this.tables = null;
for (int i = 0; i < colCnt; i++) {
ColInfo col = new ColInfo();
col.userType = in.readShort();
int flags = in.readShort();
col.nullable = ((flags & 0x01) != 0) ?
ResultSetMetaData.columnNullable :
ResultSetMetaData.columnNoNulls;
col.isCaseSensitive = (flags & 0X02) != 0;
col.isIdentity = (flags & 0x10) != 0;
col.isWriteable = (flags & 0x0C) != 0;
TdsData.readType(in, col);
// Set the charsetInfo field of col
if (tdsVersion >= Driver.TDS80 && col.collation != null) {
TdsData.setColumnCharset(col, connection);
}
int clen = in.read();
col.realName = in.readUnicodeString(clen);
col.name = col.realName;
this.columns[i] = col;
}
}
/**
* Process a TDS 4.2 column names token.
*
*
* Output parameters are distinguished from procedure return values by the value of
* a byte that immediately follows the parameter name. A value of 1 seems to indicate
* a normal output parameter while a value of 2 indicates a procedure return value.
*
* @throws IOException
* @throws ProtocolException
*/
private void tdsOutputParamToken()
throws IOException, ProtocolException, SQLException {
in.readShort(); // Packet length
String name = in.readString(in.read()); // Column Name
// Next byte indicates if output parameter or return value
// 1 = normal output param, 2 = function or stored proc return
boolean funcReturnVal = (in.read() == 2);
// Next byte is the parameter type that we supplied which
// may not be the same as the parameter definition
/* int inputTdsType = */ in.read();
// Not sure what these bytes are (they always seem to be zero).
in.skip(3);
ColInfo col = new ColInfo();
TdsData.readType(in, col);
// Set the charsetInfo field of col
if (tdsVersion >= Driver.TDS80 && col.collation != null) {
TdsData.setColumnCharset(col, connection);
}
Object value = TdsData.readData(connection, in, col);
//
// Real output parameters will either be unnamed or will have a valid
// parameter name beginning with '@'. Ignore any other spurious parameters
// such as those returned from calls to writetext in the proc.
//
if (parameters != null
&& (name.length() == 0 || name.startsWith("@"))) {
if (tdsVersion >= Driver.TDS80 && funcReturnVal) {
// TDS 8 Allows function return values of types other than int
// Also used to for return value of remote procedure calls.
if (returnParam != null) {
if (value != null) {
returnParam.setOutValue(
Support.convert(connection, value,
returnParam.jdbcType,
connection.getCharset()));
returnParam.collation = col.collation;
returnParam.charsetInfo = col.charsetInfo;
} else {
returnParam.setOutValue(null);
}
}
} else {
// Look for next output parameter in list
while (++nextParam < parameters.length) {
if (parameters[nextParam].isOutput) {
if (value != null) {
parameters[nextParam].setOutValue(
Support.convert(connection, value,
parameters[nextParam].jdbcType,
connection.getCharset()));
parameters[nextParam].collation = col.collation;
parameters[nextParam].charsetInfo = col.charsetInfo;
} else {
parameters[nextParam].setOutValue(null);
}
break;
}
}
}
}
}
/**
* Process a login acknowledgement packet.
*
* @throws IOException
*/
private void tdsLoginAckToken() throws IOException {
String product;
int major, minor, build = 0;
in.readShort(); // Packet length
int ack = in.read(); // Ack TDS 5 = 5 for OK 6 for fail, 1/0 for the others
// Update the TDS protocol version in this TdsCore and in the Socket.
// The Connection will update itself immediately after this call.
// As for other objects containing a TDS version value, there are none
// at this point (we're just constructing the Connection).
tdsVersion = TdsData.getTdsVersion(((int) in.read() << 24) | ((int) in.read() << 16)
| ((int) in.read() << 8) | (int) in.read());
socket.setTdsVersion(tdsVersion);
product = in.readString(in.read());
if (tdsVersion >= Driver.TDS70) {
major = in.read();
minor = in.read();
build = in.read() << 8;
build += in.read();
} else {
if (product.toLowerCase().startsWith("microsoft")) {
in.skip(1);
major = in.read();
minor = in.read();
} else {
major = in.read();
minor = in.read() * 10;
minor += in.read();
}
in.skip(1);
}
if (product.length() > 1 && -1 != product.indexOf('\0')) {
product = product.substring(0, product.indexOf('\0'));
}
connection.setDBServerInfo(product, major, minor, build);
if (tdsVersion == Driver.TDS50 && ack != 5) {
// Login rejected by server create SQLException
messages.addDiagnostic(4002, 0, 14,
"Login failed", "", "", 0);
currentToken.token = TDS_ERROR_TOKEN;
} else {
// MJH 2005-11-02
// If we get this far we are logged in OK so convert
// any exceptions into warnings. Any exceptions are
// likely to be caused by problems in accessing the
// default database for this login id for SQL 6.5 and
// Sybase ASE. SQL 7.0+ will fail to login if there is
// no access to the default or specified database.
// I am not convinced that this is a good idea but it
// appears that other drivers e.g. jConnect do this and
// return the exceptions on the connection warning chain.
//
SQLException ex = messages.exceptions;
// Avoid returning useless warnings about language
// character set etc.
messages.clearWarnings();
//
// Convert exceptions to warnings
//
while (ex != null) {
messages.addWarning(new SQLWarning(ex.getMessage(),
ex.getSQLState(),
ex.getErrorCode()));
ex = ex.getNextException();
}
messages.exceptions = null;
}
}
/**
* Process a control token (function unknown).
*
* @throws IOException
*/
private void tdsControlToken() throws IOException {
int pktLen = in.readShort();
in.skip(pktLen);
}
/**
* Process a row data token.
*
* @throws IOException
* @throws ProtocolException
*/
private void tdsRowToken() throws IOException, ProtocolException {
for (int i = 0; i < columns.length; i++) {
rowData[i] = TdsData.readData(connection, in, columns[i]);
}
endOfResults = false;
}
/**
* Process TDS 5.0 Params Token.
* Stored procedure output parameters or data returned in parameter format
* after a TDS Dynamic packet or as extended error information.
* true if the specified procName
* is a sp_prepare or sp_prepexec handle; returns false
* otherwise.
*
* @param procName Stored procedure to execute or null.
* @return true if the specified procName
* is a sp_prepare or sp_prepexec handle; false
* otherwise.
*/
public static boolean isPreparedProcedureName(final String procName) {
return procName != null && procName.length() > 0
&& Character.isDigit(procName.charAt(0));
}
/**
* Execute SQL using TDS 7.0 protocol.
*
* @param sql The SQL statement to execute.
* @param procName Stored procedure to execute or null.
* @param parameters Parameters for call or null.
* @param noMetaData Suppress meta data for cursor calls.
* @throws SQLException
*/
private void executeSQL70(String sql,
String procName,
ParamInfo[] parameters,
boolean noMetaData,
boolean sendNow)
throws IOException, SQLException {
int prepareSql = connection.getPrepareSql();
if (parameters == null && prepareSql == EXECUTE_SQL) {
// Downgrade EXECUTE_SQL to UNPREPARED
// if there are no parameters.
//
// Should we downgrade TEMPORARY_STORED_PROCEDURES and PREPARE as well?
// No it may be a complex select with no parameters but costly to
// evaluate for each execution.
prepareSql = UNPREPARED;
}
if (inBatch) {
// For batch execution with parameters
// we need to be consistant and use
// execute SQL
prepareSql = EXECUTE_SQL;
}
if (procName == null) {
// No procedure name so not a callable statement and also
// not a temporary stored procedure call.
if (parameters != null) {
if (prepareSql == TdsCore.UNPREPARED) {
// Low tech approach just substitute parameter data into the
// SQL statement.
sql = Support.substituteParameters(sql, parameters, connection);
} else {
// If we have parameters then we need to use sp_executesql to
// parameterise the statement unless the user has specified
ParamInfo[] params;
params = new ParamInfo[2 + parameters.length];
System.arraycopy(parameters, 0, params, 2, parameters.length);
params[0] = new ParamInfo(Types.LONGVARCHAR,
Support.substituteParamMarkers(sql, parameters),
ParamInfo.UNICODE);
TdsData.getNativeType(connection, params[0]);
params[1] = new ParamInfo(Types.LONGVARCHAR,
Support.getParameterDefinitions(parameters),
ParamInfo.UNICODE);
TdsData.getNativeType(connection, params[1]);
parameters = params;
// Use sp_executesql approach
procName = "sp_executesql";
}
}
} else {
// Either a stored procedure name has been supplied or this
// statement should executed using a prepared statement handle
if (isPreparedProcedureName(procName)) {
// If the procedure is a prepared handle then redefine the
// procedure name as sp_execute with the handle as a parameter.
ParamInfo params[];
if (parameters != null) {
params = new ParamInfo[1 + parameters.length];
System.arraycopy(parameters, 0, params, 1, parameters.length);
} else {
params = new ParamInfo[1];
}
params[0] = new ParamInfo(Types.INTEGER, new Integer(procName),
ParamInfo.INPUT);
TdsData.getNativeType(connection, params[0]);
parameters = params;
// Use sp_execute approach
procName = "sp_execute";
}
}
if (procName != null) {
// RPC call
out.setPacketType(RPC_PKT);
Integer shortcut;
if (tdsVersion >= Driver.TDS80
&& (shortcut = (Integer) tds8SpNames.get(procName)) != null) {
// Use the shortcut form of procedure name for TDS8
out.write((short) -1);
out.write((short) shortcut.shortValue());
} else {
out.write((short) procName.length());
out.write(procName);
}
//
// If noMetaData is true then column meta data will be supressed.
// This option is used by sp_cursorfetch or optionally by sp_execute
// provided that the required meta data has been cached.
//
out.write((short) (noMetaData ? 2 : 0));
if (parameters != null) {
// Send the required parameter data
for (int i = nextParam + 1; i < parameters.length; i++) {
if (parameters[i].name != null) {
out.write((byte) parameters[i].name.length());
out.write(parameters[i].name);
} else {
out.write((byte) 0);
}
out.write((byte) (parameters[i].isOutput ? 1 : 0));
TdsData.writeParam(out,
connection.getCharsetInfo(),
connection.getCollation(),
parameters[i]);
}
}
if (!sendNow) {
// Append RPC packets
out.write((byte) DONE_END_OF_RESPONSE);
}
} else if (sql.length() > 0) {
// Simple SQL query with no parameters
out.setPacketType(QUERY_PKT);
out.write(sql);
if (!sendNow) {
// Append SQL packets
out.write(" ");
}
}
}
/**
* Sets the server row count (to limit the number of rows in a result set)
* and text size (to limit the size of returned TEXT/NTEXT fields).
*
* @param rowCount the number of rows to return or 0 for no limit or -1 to
* leave as is
* @param textSize the maximum number of bytes in a TEXT column to return
* or -1 to leave as is
* @throws SQLException if an error is returned by the server
*/
private void setRowCountAndTextSize(int rowCount, int textSize)
throws SQLException {
boolean newRowCount =
rowCount >= 0 && rowCount != connection.getRowCount();
boolean newTextSize =
textSize >= 0 && textSize != connection.getTextSize();
if (newRowCount || newTextSize) {
try {
StringBuffer query = new StringBuffer(64);
if (newRowCount) {
query.append("SET ROWCOUNT ").append(rowCount);
}
if (newTextSize) {
query.append(" SET TEXTSIZE ")
.append(textSize == 0 ? 2147483647 : textSize);
}
out.setPacketType(QUERY_PKT);
out.write(query.toString());
out.flush();
endOfResponse = false;
endOfResults = true;
wait(0);
clearResponseQueue();
messages.checkErrors();
// Update the values stored in the Connection
connection.setRowCount(rowCount);
connection.setTextSize(textSize);
} catch (IOException ioe) {
throw new SQLException(
Messages.get("error.generic.ioerror",
ioe.getMessage()), "08S01");
}
}
}
/**
* Waits for the first byte of the server response.
*
* @param timeOut the timeout period in seconds or 0
*/
private void wait(int timeOut) throws IOException, SQLException {
Object timer = null;
try {
if (timeOut > 0) {
// Start a query timeout timer
timer = TimerThread.getInstance().setTimer(timeOut * 1000,
new TimerThread.TimerListener() {
public void timerExpired() {
TdsCore.this.cancel(true);
}
});
}
in.peek();
} finally {
if (timer != null) {
if (!TimerThread.getInstance().cancelTimer(timer)) {
throw new SQLException(
Messages.get("error.generic.timeout"), "HYT00");
}
}
}
}
/**
* Releases parameter and result set data and metadata to free up memory.
* TdsCore is cached for reuse.
*/
public void cleanUp() {
if (endOfResponse) {
// Clean up parameters
returnParam = null;
parameters = null;
// Clean up result data and meta data
columns = null;
rowData = null;
tables = null;
// Clean up warnings; any exceptions will be cleared when thrown
messages.clearWarnings();
}
}
/**
* Returns the diagnostic chain for this instance.
*/
public SQLDiagnostic getMessages() {
return messages;
}
/**
* Converts a user supplied MAC address into a byte array.
*
* @param macString the MAC address as a hex string
* @return the MAC address as a byte[]
*/
private static byte[] getMACAddress(String macString) {
byte[] mac = new byte[6];
boolean ok = false;
if (macString != null && macString.length() == 12) {
try {
for (int i = 0, j = 0; i < 6; i++, j += 2) {
mac[i] = (byte) Integer.parseInt(
macString.substring(j, j + 2), 16);
}
ok = true;
} catch (Exception ex) {
// Ignore it. ok will be false.
}
}
if (!ok) {
Arrays.fill(mac, (byte) 0);
}
return mac;
}
/**
* Tries to figure out what client name we should identify ourselves as.
* Gets the hostname of this machine,
*
* @return name to use as the client
*/
private static String getHostName() {
if (hostName != null) {
return hostName;
}
String name;
try {
name = java.net.InetAddress.getLocalHost().getHostName().toUpperCase();
} catch (java.net.UnknownHostException e) {
hostName = "UNKNOWN";
return hostName;
}
int pos = name.indexOf('.');
if (pos >= 0) {
name = name.substring(0, pos);
}
if (name.length() == 0) {
hostName = "UNKNOWN";
return hostName;
}
try {
Integer.parseInt(name);
// All numbers probably an IP address
hostName = "UNKNOWN";
return hostName;
} catch (NumberFormatException e) {
// Bit tacky but simple check for all numbers
}
hostName = name;
return name;
}
/**
* A very poor man's "encryption".
*
* @param pw password to encrypt
* @return encrypted password
*/
private static String tds7CryptPass(final String pw) {
final int xormask = 0x5A5A;
final int len = pw.length();
final char[] chars = new char[len];
for (int i = 0; i < len; ++i) {
final int c = (int) (pw.charAt(i)) ^ xormask;
final int m1 = (c >> 4) & 0x0F0F;
final int m2 = (c << 4) & 0xF0F0;
chars[i] = (char) (m1 | m2);
}
return new String(chars);
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/Support.java 0000644 0001750 0001750 00000160666 11316672660 025436 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.io.*;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import net.sourceforge.jtds.util.Logger;
/**
* This class contains static utility methods designed to support the
* main driver classes.
*
*
*
* @author Mike Hutchinson
* @author jTDS project
* @version $Id: Support.java,v 1.56.2.5 2009/10/22 07:28:23 ickzon Exp $
*/
public class Support {
// Constants used in datatype conversions to avoid object allocations.
private static final Integer INTEGER_ZERO = new Integer(0);
private static final Integer INTEGER_ONE = new Integer(1);
private static final Long LONG_ZERO = new Long(0L);
private static final Long LONG_ONE = new Long(1L);
private static final Float FLOAT_ZERO = new Float(0.0);
private static final Float FLOAT_ONE = new Float(1.0);
private static final Double DOUBLE_ZERO = new Double(0.0);
private static final Double DOUBLE_ONE = new Double(1.0);
private static final BigDecimal BIG_DECIMAL_ZERO = new BigDecimal(0.0);
private static final BigDecimal BIG_DECIMAL_ONE = new BigDecimal(1.0);
private static final java.sql.Date DATE_ZERO = new java.sql.Date(0);
private static final java.sql.Time TIME_ZERO = new java.sql.Time(0);
private static final BigInteger MIN_VALUE_LONG_BI = new BigInteger(String.valueOf(Long.MIN_VALUE));
private static final BigInteger MAX_VALUE_LONG_BI = new BigInteger(String.valueOf(Long.MAX_VALUE));
private static final BigDecimal MIN_VALUE_LONG_BD = new BigDecimal(String.valueOf(Long.MIN_VALUE));
private static final BigDecimal MAX_VALUE_LONG_BD = new BigDecimal(String.valueOf(Long.MAX_VALUE));
private static final BigInteger MAX_VALUE_28 = new BigInteger("9999999999999999999999999999");
private static final BigInteger MAX_VALUE_38 = new BigInteger("99999999999999999999999999999999999999");
/**
* Convert java clases to java.sql.Type constant.
*/
private static final HashMap typeMap = new HashMap();
static {
typeMap.put(Byte.class, new Integer(java.sql.Types.TINYINT));
typeMap.put(Short.class, new Integer(java.sql.Types.SMALLINT));
typeMap.put(Integer.class, new Integer(java.sql.Types.INTEGER));
typeMap.put(Long.class, new Integer(java.sql.Types.BIGINT));
typeMap.put(Float.class, new Integer(java.sql.Types.REAL));
typeMap.put(Double.class, new Integer(java.sql.Types.DOUBLE));
typeMap.put(BigDecimal.class, new Integer(java.sql.Types.DECIMAL));
typeMap.put(Boolean.class, new Integer(JtdsStatement.BOOLEAN));
typeMap.put(byte[].class, new Integer(java.sql.Types.VARBINARY));
typeMap.put(java.sql.Date.class, new Integer(java.sql.Types.DATE));
typeMap.put(java.sql.Time.class, new Integer(java.sql.Types.TIME));
typeMap.put(java.sql.Timestamp.class, new Integer(java.sql.Types.TIMESTAMP));
typeMap.put(BlobImpl.class, new Integer(java.sql.Types.LONGVARBINARY));
typeMap.put(ClobImpl.class, new Integer(java.sql.Types.LONGVARCHAR));
typeMap.put(String.class, new Integer(java.sql.Types.VARCHAR));
typeMap.put(Blob.class, new Integer(java.sql.Types.LONGVARBINARY));
typeMap.put(Clob.class, new Integer(java.sql.Types.LONGVARCHAR));
}
/**
* Hex constants to use in conversion routines.
*/
private static final char hex[] = {'0', '1', '2', '3', '4', '5', '6','7',
'8', '9', 'A', 'B', 'C', 'D', 'E','F'
};
/**
* Thread-bound utility Calendar object.
*/
private static final ThreadLocal calendar = new ThreadLocal() {
protected Object initialValue() {
return new GregorianCalendar();
}
};
/**
* Convert a byte[] object to a hex string.
*
* @param bytes The byte array to convert.
* @return The hex equivalent as a String.
*/
public static String toHex(byte[] bytes) {
int len = bytes.length;
if (len > 0) {
StringBuffer buf = new StringBuffer(len * 2);
for (int i = 0; i < len; i++) {
int b1 = bytes[i] & 0xFF;
buf.append(hex[b1 >> 4]);
buf.append(hex[b1 & 0x0F]);
}
return buf.toString();
}
return "";
}
/**
* Normalize a BigDecimal value so that it fits within the
* available precision.
*
* @param value The decimal value to normalize.
* @param maxPrecision The decimal precision supported by the server
* (assumed to be a value of either 28 or 38).
* @return The possibly normalized decimal value as a BigDecimal.
* @throws SQLException If the number is too big.
*/
static BigDecimal normalizeBigDecimal(BigDecimal value, int maxPrecision)
throws SQLException {
if (value == null) {
return null;
}
if (value.scale() < 0) {
// Java 1.5 BigDecimal allows negative scales.
// jTDS cannot send these so re-scale.
value = value.setScale(0);
}
if (value.scale() > maxPrecision) {
// This is an optimization to quickly adjust the scale of a
// very precise BD value. For example
// BigDecimal((double)1.0/3.0) yields a BD 54 digits long!
value = value.setScale(maxPrecision, BigDecimal.ROUND_HALF_UP);
}
BigInteger max = (maxPrecision == TdsData.DEFAULT_PRECISION_28) ? MAX_VALUE_28 : MAX_VALUE_38;
while (value.abs().unscaledValue().compareTo(max) > 0) {
// OK we need to reduce the scale if possible to preserve
// the integer part of the number and still fit within the
// available precision.
int scale = value.scale() - 1;
if (scale < 0) {
// Can't do it number just too big
throw new SQLException(Messages.get("error.normalize.numtoobig",
String.valueOf(maxPrecision)), "22000");
}
value = value.setScale(scale, BigDecimal.ROUND_HALF_UP);
}
return value;
}
static Object castNumeric(Object orig, int sourceType, int targetType) {
return null;
}
/**
* Convert an existing data object to the specified JDBC type.
*
* @param callerReference an object reference to the caller of this method;
* must be a Connection,
* Statement or ResultSet
* @param x the data object to convert
* @param jdbcType the required type constant from
* java.sql.Types
* @return the converted data object
* @throws SQLException if the conversion is not supported or fails
*/
static Object convert(Object callerReference, Object x, int jdbcType, String charSet)
throws SQLException {
// handle null value
if (x == null) {
switch (jdbcType) {
case java.sql.Types.BIT:
case JtdsStatement.BOOLEAN:
return Boolean.FALSE;
case java.sql.Types.TINYINT:
case java.sql.Types.SMALLINT:
case java.sql.Types.INTEGER:
return INTEGER_ZERO;
case java.sql.Types.BIGINT:
return LONG_ZERO;
case java.sql.Types.REAL:
return FLOAT_ZERO;
case java.sql.Types.FLOAT:
case java.sql.Types.DOUBLE:
return DOUBLE_ZERO;
default:
return null;
}
}
try {
switch (jdbcType) {
case java.sql.Types.TINYINT:
if (x instanceof Boolean) {
return ((Boolean) x).booleanValue() ? INTEGER_ONE : INTEGER_ZERO;
} else if (x instanceof Byte) {
return new Integer(((Byte)x).byteValue() & 0xFF);
} else {
long val;
if (x instanceof Number) {
val = ((Number)x).longValue();
} else if (x instanceof String) {
val = new Long(((String) x).trim()).longValue();
} else {
break;
}
if (val < Byte.MIN_VALUE || val > Byte.MAX_VALUE) {
throw new SQLException(Messages.get("error.convert.numericoverflow", x, getJdbcTypeName(jdbcType)), "22003");
} else {
return new Integer(new Long(val).intValue());
}
}
case java.sql.Types.SMALLINT:
if (x instanceof Boolean) {
return ((Boolean) x).booleanValue() ? INTEGER_ONE : INTEGER_ZERO;
} else if (x instanceof Short) {
return new Integer(((Short)x).shortValue());
} else if (x instanceof Byte) {
return new Integer(((Byte)x).byteValue() & 0xFF);
} else {
long val;
if (x instanceof Number) {
val = ((Number)x).longValue();
} else if (x instanceof String) {
val = new Long(((String) x).trim()).longValue();
} else {
break;
}
if (val < Short.MIN_VALUE || val > Short.MAX_VALUE) {
throw new SQLException(Messages.get("error.convert.numericoverflow", x, getJdbcTypeName(jdbcType)), "22003");
} else {
return new Integer(new Long(val).intValue());
}
}
case java.sql.Types.INTEGER:
if (x instanceof Integer) {
return x;
}
else if (x instanceof Boolean) {
return ((Boolean) x).booleanValue() ? INTEGER_ONE : INTEGER_ZERO;
} else if (x instanceof Short) {
return new Integer(((Short)x).shortValue());
} else if (x instanceof Byte) {
return new Integer(((Byte)x).byteValue() & 0xFF);
} else {
long val;
if (x instanceof Number) {
val = ((Number)x).longValue();
} else if (x instanceof String) {
val = new Long(((String) x).trim()).longValue();
} else {
break;
}
if (val < Integer.MIN_VALUE || val > Integer.MAX_VALUE) {
throw new SQLException(Messages.get("error.convert.numericoverflow", x, getJdbcTypeName(jdbcType)), "22003");
} else {
return new Integer(new Long(val).intValue());
}
}
case java.sql.Types.BIGINT:
if (x instanceof BigDecimal ) {
BigDecimal val = (BigDecimal) x;
if (val.compareTo(MIN_VALUE_LONG_BD) < 0 || val.compareTo(MAX_VALUE_LONG_BD) > 0) {
throw new SQLException(Messages.get("error.convert.numericoverflow", x, getJdbcTypeName(jdbcType)), "22003");
} else {
return new Long(val.longValue());
}
} else if (x instanceof Long) {
return x;
} else if (x instanceof Boolean) {
return ((Boolean) x).booleanValue() ? LONG_ONE : LONG_ZERO;
} else if (x instanceof Byte) {
return new Long(((Byte)x).byteValue() & 0xFF);
} else if (x instanceof BigInteger) {
BigInteger val = (BigInteger) x;
if (val.compareTo(MIN_VALUE_LONG_BI) < 0 || val.compareTo(MAX_VALUE_LONG_BI) > 0) {
throw new SQLException(Messages.get("error.convert.numericoverflow", x, getJdbcTypeName(jdbcType)), "22003");
} else {
return new Long(val.longValue());
}
} else if (x instanceof Number) {
return new Long(((Number) x).longValue());
} else if (x instanceof String) {
return new Long(((String) x).trim());
} else {
break;
}
case java.sql.Types.REAL:
if (x instanceof Float) {
return x;
} else if (x instanceof Byte) {
return new Float(((Byte)x).byteValue() & 0xFF);
} else if (x instanceof Number) {
return new Float(((Number) x).floatValue());
} else if (x instanceof String) {
return new Float(((String) x).trim());
} else if (x instanceof Boolean) {
return ((Boolean) x).booleanValue() ? FLOAT_ONE : FLOAT_ZERO;
}
break;
case java.sql.Types.FLOAT:
case java.sql.Types.DOUBLE:
if (x instanceof Double) {
return x;
} else if (x instanceof Byte) {
return new Double(((Byte)x).byteValue() & 0xFF);
} else if (x instanceof Number) {
return new Double(((Number) x).doubleValue());
} else if (x instanceof String) {
return new Double(((String) x).trim());
} else if (x instanceof Boolean) {
return ((Boolean) x).booleanValue() ? DOUBLE_ONE : DOUBLE_ZERO;
}
break;
case java.sql.Types.NUMERIC:
case java.sql.Types.DECIMAL:
if (x instanceof BigDecimal) {
return x;
} else if (x instanceof Number) {
return new BigDecimal(x.toString());
} else if (x instanceof String) {
return new BigDecimal((String) x);
} else if (x instanceof Boolean) {
return ((Boolean) x).booleanValue() ? BIG_DECIMAL_ONE : BIG_DECIMAL_ZERO;
}
break;
case java.sql.Types.VARCHAR:
case java.sql.Types.CHAR:
if (x instanceof String) {
return x;
} else if (x instanceof Number) {
return x.toString();
} else if (x instanceof Boolean) {
return((Boolean) x).booleanValue() ? "1" : "0";
} else if (x instanceof Clob) {
Clob clob = (Clob) x;
long length = clob.length();
if (length > Integer.MAX_VALUE) {
throw new SQLException(Messages.get("error.normalize.lobtoobig"),
"22000");
}
return clob.getSubString(1, (int) length);
} else if (x instanceof Blob) {
Blob blob = (Blob) x;
long length = blob.length();
if (length > Integer.MAX_VALUE) {
throw new SQLException(Messages.get("error.normalize.lobtoobig"),
"22000");
}
x = blob.getBytes(1, (int) length);
}
if (x instanceof byte[]) {
return toHex((byte[])x);
}
return x.toString(); // Last hope!
case java.sql.Types.BIT:
case JtdsStatement.BOOLEAN:
if (x instanceof Boolean) {
return x;
} else if (x instanceof Number) {
return(((Number) x).intValue() == 0) ? Boolean.FALSE : Boolean.TRUE;
} else if (x instanceof String) {
String tmp = ((String) x).trim();
return ("1".equals(tmp) || "true".equalsIgnoreCase(tmp)) ? Boolean.TRUE : Boolean.FALSE;
}
break;
case java.sql.Types.VARBINARY:
case java.sql.Types.BINARY:
if (x instanceof byte[]) {
return x;
} else if (x instanceof Blob) {
Blob blob = (Blob) x;
return blob.getBytes(1, (int) blob.length());
} else if (x instanceof Clob) {
Clob clob = (Clob) x;
long length = clob.length();
if (length > Integer.MAX_VALUE) {
throw new SQLException(Messages.get("error.normalize.lobtoobig"),
"22000");
}
x = clob.getSubString(1, (int) length);
}
if (x instanceof String) {
//
// Strictly speaking this conversion is not required by
// the JDBC standard but jTDS has always supported it.
//
if (charSet == null) {
charSet = "ISO-8859-1";
}
try {
return ((String) x).getBytes(charSet);
} catch (UnsupportedEncodingException e) {
return ((String) x).getBytes();
}
} else if (x instanceof UniqueIdentifier) {
return ((UniqueIdentifier) x).getBytes();
}
break;
case java.sql.Types.TIMESTAMP:
if (x instanceof DateTime) {
return ((DateTime) x).toTimestamp();
} else if (x instanceof java.sql.Timestamp) {
return x;
} else if (x instanceof java.sql.Date) {
return new java.sql.Timestamp(((java.sql.Date) x).getTime());
} else if (x instanceof java.sql.Time) {
return new java.sql.Timestamp(((java.sql.Time) x).getTime());
} else if (x instanceof java.lang.String) {
return java.sql.Timestamp.valueOf(((String)x).trim());
}
break;
case java.sql.Types.DATE:
if (x instanceof DateTime) {
return ((DateTime) x).toDate();
} else if (x instanceof java.sql.Date) {
return x;
} else if (x instanceof java.sql.Time) {
return DATE_ZERO;
} else if (x instanceof java.sql.Timestamp) {
GregorianCalendar cal = (GregorianCalendar) calendar.get();
cal.setTime((java.util.Date) x);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// VM1.4+ only return new java.sql.Date(cal.getTimeInMillis());
return new java.sql.Date(cal.getTime().getTime());
} else if (x instanceof java.lang.String) {
return java.sql.Date.valueOf(((String) x).trim());
}
break;
case java.sql.Types.TIME:
if (x instanceof DateTime) {
return ((DateTime) x).toTime();
} else if (x instanceof java.sql.Time) {
return x;
} else if (x instanceof java.sql.Date) {
return TIME_ZERO;
} else if (x instanceof java.sql.Timestamp) {
GregorianCalendar cal = (GregorianCalendar) calendar.get();
// VM 1.4+ only cal.setTimeInMillis(((java.sql.Timestamp)x).getTime());
cal.setTime((java.util.Date)x);
cal.set(Calendar.YEAR, 1970);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH,1);
// VM 1.4+ only return new java.sql.Time(cal.getTimeInMillis());*/
return new java.sql.Time(cal.getTime().getTime());
} else if (x instanceof java.lang.String) {
return java.sql.Time.valueOf(((String) x).trim());
}
break;
case java.sql.Types.OTHER:
return x;
case java.sql.Types.JAVA_OBJECT:
throw new SQLException(
Messages.get("error.convert.badtypes",
x.getClass().getName(),
getJdbcTypeName(jdbcType)), "22005");
case java.sql.Types.LONGVARBINARY:
case java.sql.Types.BLOB:
if (x instanceof Blob) {
return x;
} else if (x instanceof byte[]) {
return new BlobImpl(getConnection(callerReference), (byte[]) x);
} else if (x instanceof Clob) {
//
// Convert CLOB to BLOB. Not required by the standard but we will
// do it anyway.
//
Clob clob = (Clob) x;
try {
if (charSet == null) {
charSet = "ISO-8859-1";
}
Reader rdr = clob.getCharacterStream();
BlobImpl blob = new BlobImpl(getConnection(callerReference));
BufferedWriter out =
new BufferedWriter(new OutputStreamWriter(blob.setBinaryStream(1), charSet));
// TODO Use a buffer to improve performance
int c;
while ((c = rdr.read()) >= 0) {
out.write(c);
}
out.close();
rdr.close();
return blob;
} catch (UnsupportedEncodingException e) {
// Unlikely to happen but fall back on in memory copy
x = clob.getSubString(1, (int) clob.length());
} catch (IOException e) {
throw new SQLException(Messages.get("error.generic.ioerror", e.getMessage()),
"HY000");
}
}
if (x instanceof String) {
//
// Strictly speaking this conversion is also not required by
// the JDBC standard but jTDS has always supported it.
//
BlobImpl blob = new BlobImpl(getConnection(callerReference));
String data = (String) x;
if (charSet == null) {
charSet = "ISO-8859-1";
}
try {
blob.setBytes(1, data.getBytes(charSet));
} catch (UnsupportedEncodingException e) {
blob.setBytes(1, data.getBytes());
}
return blob;
}
break;
case java.sql.Types.LONGVARCHAR:
case java.sql.Types.CLOB:
if (x instanceof Clob) {
return x;
} else if (x instanceof Blob) {
//
// Convert BLOB to CLOB
//
Blob blob = (Blob) x;
try {
InputStream is = blob.getBinaryStream();
ClobImpl clob = new ClobImpl(getConnection(callerReference));
Writer out = clob.setCharacterStream(1);
// TODO Use a buffer to improve performance
int b;
// These reads/writes are buffered by the underlying blob buffers
while ((b = is.read()) >= 0) {
out.write(hex[b >> 4]);
out.write(hex[b & 0x0F]);
}
out.close();
is.close();
return clob;
} catch (IOException e) {
throw new SQLException(Messages.get("error.generic.ioerror", e.getMessage()),
"HY000");
}
} else if (x instanceof Boolean) {
x = ((Boolean) x).booleanValue() ? "1" : "0";
} else if (!(x instanceof byte[])) {
x = x.toString();
}
if (x instanceof byte[]) {
ClobImpl clob = new ClobImpl(getConnection(callerReference));
clob.setString(1, toHex((byte[]) x));
return clob;
} else if (x instanceof String) {
return new ClobImpl(getConnection(callerReference), (String) x);
}
break;
default:
throw new SQLException(
Messages.get("error.convert.badtypeconst",
getJdbcTypeName(jdbcType)), "HY004");
}
throw new SQLException(
Messages.get("error.convert.badtypes",
x.getClass().getName(),
getJdbcTypeName(jdbcType)), "22005");
} catch (NumberFormatException nfe) {
throw new SQLException(
Messages.get("error.convert.badnumber",
getJdbcTypeName(jdbcType)), "22000");
}
}
/**
* Get the JDBC type constant which matches the supplied Object type.
*
* @param value The object to analyse.
* @return The JDBC type constant as an int.
*/
static int getJdbcType(Object value) {
if (value == null) {
return java.sql.Types.NULL;
}
return getJdbcType(value.getClass());
}
/**
* Get the JDBC type constant which matches the supplied Class.
*
* @param typeClass the Class to analyse
* @return the JDBC type constant as an int
*/
static int getJdbcType(Class typeClass) {
if (typeClass == null) {
return java.sql.Types.JAVA_OBJECT;
}
Object type = typeMap.get(typeClass);
if (type == null) {
// not in typeMap - try recursion through superclass hierarchy
return getJdbcType(typeClass.getSuperclass());
}
return ((Integer) type).intValue();
}
/**
* Get a String describing the supplied JDBC type constant.
*
* @param jdbcType The constant to be decoded.
* @return The text decode of the type constant as a String.
*/
static String getJdbcTypeName(int jdbcType) {
switch (jdbcType) {
case java.sql.Types.ARRAY: return "ARRAY";
case java.sql.Types.BIGINT: return "BIGINT";
case java.sql.Types.BINARY: return "BINARY";
case java.sql.Types.BIT: return "BIT";
case java.sql.Types.BLOB: return "BLOB";
case JtdsStatement.BOOLEAN: return "BOOLEAN";
case java.sql.Types.CHAR: return "CHAR";
case java.sql.Types.CLOB: return "CLOB";
case JtdsStatement.DATALINK: return "DATALINK";
case java.sql.Types.DATE: return "DATE";
case java.sql.Types.DECIMAL: return "DECIMAL";
case java.sql.Types.DISTINCT: return "DISTINCT";
case java.sql.Types.DOUBLE: return "DOUBLE";
case java.sql.Types.FLOAT: return "FLOAT";
case java.sql.Types.INTEGER: return "INTEGER";
case java.sql.Types.JAVA_OBJECT: return "JAVA_OBJECT";
case java.sql.Types.LONGVARBINARY: return "LONGVARBINARY";
case java.sql.Types.LONGVARCHAR: return "LONGVARCHAR";
case java.sql.Types.NULL: return "NULL";
case java.sql.Types.NUMERIC: return "NUMERIC";
case java.sql.Types.OTHER: return "OTHER";
case java.sql.Types.REAL: return "REAL";
case java.sql.Types.REF: return "REF";
case java.sql.Types.SMALLINT: return "SMALLINT";
case java.sql.Types.STRUCT: return "STRUCT";
case java.sql.Types.TIME: return "TIME";
case java.sql.Types.TIMESTAMP: return "TIMESTAMP";
case java.sql.Types.TINYINT: return "TINYINT";
case java.sql.Types.VARBINARY: return "VARBINARY";
case java.sql.Types.VARCHAR: return "VARCHAR";
default: return "ERROR";
}
}
/**
* Retrieve the fully qualified java class name for the
* supplied JDBC Types constant.
*
* @param jdbcType The JDBC Types constant.
* @return The fully qualified java class name as a String.
*/
static String getClassName(int jdbcType) {
switch (jdbcType) {
case JtdsStatement.BOOLEAN:
case java.sql.Types.BIT:
return "java.lang.Boolean";
case java.sql.Types.TINYINT:
case java.sql.Types.SMALLINT:
case java.sql.Types.INTEGER:
return "java.lang.Integer";
case java.sql.Types.BIGINT:
return "java.lang.Long";
case java.sql.Types.NUMERIC:
case java.sql.Types.DECIMAL:
return "java.math.BigDecimal";
case java.sql.Types.REAL:
return "java.lang.Float";
case java.sql.Types.FLOAT:
case java.sql.Types.DOUBLE:
return "java.lang.Double";
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
return "java.lang.String";
case java.sql.Types.BINARY:
case java.sql.Types.VARBINARY:
return "[B";
case java.sql.Types.LONGVARBINARY:
case java.sql.Types.BLOB:
return "java.sql.Blob";
case java.sql.Types.LONGVARCHAR:
case java.sql.Types.CLOB:
return "java.sql.Clob";
case java.sql.Types.DATE:
return "java.sql.Date";
case java.sql.Types.TIME:
return "java.sql.Time";
case java.sql.Types.TIMESTAMP:
return "java.sql.Timestamp";
}
return "java.lang.Object";
}
/**
* Embed the data object as a string literal in the buffer supplied.
*
* @param buf The buffer in which the data will be embedded.
* @param value The data object.
* @param isUnicode Set to true if Unicode strings should be used, else false.
* @param connection The {@link ConnectionJDBC2} object.
*/
static void embedData(StringBuffer buf, Object value, boolean isUnicode, ConnectionJDBC2 connection)
throws SQLException {
buf.append(' ');
if (value == null) {
buf.append("NULL ");
return;
}
if (value instanceof Blob) {
Blob blob = (Blob) value;
value = blob.getBytes(1, (int) blob.length());
} else if (value instanceof Clob) {
Clob clob = (Clob) value;
value = clob.getSubString(1, (int) clob.length());
}
if (value instanceof DateTime) {
buf.append('\'');
buf.append(value);
buf.append('\'');
} else
if (value instanceof byte[]) {
byte[] bytes = (byte[]) value;
int len = bytes.length;
if (len >= 0) {
buf.append('0').append('x');
if (len == 0 && connection.getTdsVersion() < Driver.TDS70) {
// Zero length binary values are not allowed
buf.append('0').append('0');
} else {
for (int i = 0; i < len; i++) {
int b1 = bytes[i] & 0xFF;
buf.append(hex[b1 >> 4]);
buf.append(hex[b1 & 0x0F]);
}
}
}
} else if (value instanceof String) {
String tmp = (String) value;
int len = tmp.length();
if (isUnicode) {
buf.append('N');
}
buf.append('\'');
for (int i = 0; i < len; i++) {
char c = tmp.charAt(i);
if (c == '\'') {
buf.append('\'');
}
buf.append(c);
}
buf.append('\'');
} else if (value instanceof java.sql.Date) {
DateTime dt = new DateTime((java.sql.Date)value);
buf.append('\'');
buf.append(dt);
buf.append('\'');
} else if (value instanceof java.sql.Time) {
DateTime dt = new DateTime((java.sql.Time)value);
buf.append('\'');
buf.append(dt);
buf.append('\'');
} else if (value instanceof java.sql.Timestamp) {
DateTime dt = new DateTime((java.sql.Timestamp)value);
buf.append('\'');
buf.append(dt);
buf.append('\'');
} else if (value instanceof Boolean) {
buf.append(((Boolean) value).booleanValue() ? '1' : '0');
} else if (value instanceof BigDecimal) {
//
// Ensure large decimal number does not overflow the
// maximum precision of the server.
// Main problem is with small numbers e.g. BigDecimal(1.0).toString() =
// 0.1000000000000000055511151231....
//
String tmp = value.toString();
int maxlen = connection.getMaxPrecision();
if (tmp.charAt(0) == '-') {
maxlen++;
}
if (tmp.indexOf('.') >= 0) {
maxlen++;
}
if (tmp.length() > maxlen) {
buf.append(tmp.substring(0, maxlen));
} else {
buf.append(tmp);
}
} else {
buf.append(value.toString());
}
buf.append(' ');
}
/**
* Generates a unique statement key for a given SQL statement.
*
* @param sql the sql statement to generate the key for
* @param params the statement parameters
* @param serverType the type of server to generate the key for
* @param catalog the catalog is required for uniqueness on Microsoft
* SQL Server
* @param autoCommit true if in auto commit mode
* @param cursor true if this is a prepared cursor
* @return the unique statement key
*/
static String getStatementKey(String sql, ParamInfo[] params,
int serverType, String catalog,
boolean autoCommit, boolean cursor) {
StringBuffer key;
if (serverType == Driver.SQLSERVER) {
key = new StringBuffer(1 + catalog.length() + sql.length()
+ 11 * params.length);
// Need to distinguish otherwise identical SQL for cursor and
// non cursor prepared statements (sp_prepare/sp_cursorprepare).
key.append((cursor) ? 'C':'X');
// Need to ensure that the current database is included in the key
// as procedures and handles are database specific.
key.append(catalog);
// Now the actual SQL statement
key.append(sql);
//
// Append parameter data types to key.
//
for (int i = 0; i < params.length; i++) {
key.append(params[i].sqlType);
}
} else {
key = new StringBuffer(sql.length() + 2);
// A simple key works for Sybase just need to know if
// proc created in chained mode or not.
key.append((autoCommit) ? 'T': 'F');
// Now the actual SQL statement
key.append(sql);
}
return key.toString();
}
/**
* Constructs a parameter definition string for use with
* sp_executesql, sp_prepare, sp_prepexec, sp_cursoropen,
* sp_cursorprepare and sp_cursorprepexec.
*
* @param parameters Parameters to construct the definition for
* @return a parameter definition string
*/
static String getParameterDefinitions(ParamInfo[] parameters) {
StringBuffer sql = new StringBuffer(parameters.length * 15);
// Build parameter descriptor
for (int i = 0; i < parameters.length; i++) {
if (parameters[i].name == null) {
sql.append("@P");
sql.append(i);
} else {
sql.append(parameters[i].name);
}
sql.append(' ');
sql.append(parameters[i].sqlType);
if (i + 1 < parameters.length) {
sql.append(',');
}
}
return sql.toString();
}
/**
* Update the SQL string and replace the ? markers with parameter names
* eg @P0, @P1 etc.
*
* @param sql the SQL containing markers to substitute
* @param list the parameter list
* @return the modified SQL as a String
*/
static String substituteParamMarkers(String sql, ParamInfo[] list) {
// A parameter can have at most 8 characters: " @P" plus at most 4
// digits plus " ". We subtract the "?" placeholder, that's at most
// 7 extra characters needed for each parameter.
char[] buf = new char[sql.length() + list.length * 7];
int bufferPtr = 0; // Output buffer pointer
int start = 0; // Input string pointer
StringBuffer number = new StringBuffer(4);
for (int i = 0; i < list.length; i++) {
int pos = list[i].markerPos;
if (pos > 0) {
sql.getChars(start, pos, buf, bufferPtr);
bufferPtr += (pos - start);
start = pos + 1;
// Append " @P"
buf[bufferPtr++] = ' ';
buf[bufferPtr++] = '@';
buf[bufferPtr++] = 'P';
// Append parameter number
// Rather complicated, but it's the only way in which no
// unnecessary objects are created
number.setLength(0);
number.append(i);
number.getChars(0, number.length(), buf, bufferPtr);
bufferPtr += number.length();
// Append " "
buf[bufferPtr++] = ' ';
}
}
if (start < sql.length()) {
sql.getChars(start, sql.length(), buf, bufferPtr);
bufferPtr += (sql.length() - start);
}
return new String(buf, 0, bufferPtr);
}
/**
* Substitute actual data for the parameter markers to simulate
* parameter substitution in a PreparedStatement.
*
* @param sql The SQL containing parameter markers to substitute.
* @param list The parameter descriptors.
* @param connection The current connection.
* @return The modified SQL statement.
*/
static String substituteParameters(String sql, ParamInfo[] list, ConnectionJDBC2 connection)
throws SQLException {
int len = sql.length();
for (int i = 0; i < list.length; i++) {
if (!list[i].isRetVal && !list[i].isSet && !list[i].isOutput) {
throw new SQLException(Messages.get("error.prepare.paramnotset",
Integer.toString(i+1)),
"07000");
}
Object value = list[i].value;
if (value instanceof java.io.InputStream
|| value instanceof java.io.Reader) {
try {
if (list[i].jdbcType == java.sql.Types.LONGVARCHAR ||
list[i].jdbcType == java.sql.Types.CLOB ||
list[i].jdbcType == java.sql.Types.VARCHAR) {
// TODO: Should improve the character set handling here
value = list[i].getString("US-ASCII");
} else {
value = list[i].getBytes("US-ASCII");
}
// Replace the stream/reader with the String/byte[]
list[i].value = value;
} catch (java.io.IOException e) {
throw new SQLException(Messages.get("error.generic.ioerror",
e.getMessage()),
"HY000");
}
}
if (value instanceof String) {
len += ((String) value).length() + 5;
} else if (value instanceof byte[]) {
len += ((byte[]) value).length * 2 + 4;
} else {
len += 32; // Default size
}
}
StringBuffer buf = new StringBuffer(len + 16);
int start = 0;
for (int i = 0; i < list.length; i++) {
int pos = list[i].markerPos;
if (pos > 0) {
buf.append(sql.substring(start, list[i].markerPos));
start = pos + 1;
final boolean isUnicode = connection.getTdsVersion() >= Driver.TDS70 && list[i].isUnicode;
Support.embedData(buf, list[i].value, isUnicode, connection);
}
}
if (start < sql.length()) {
buf.append(sql.substring(start));
}
return buf.toString();
}
/**
* Encode a string into a byte array using the specified character set.
*
* @param cs The Charset name.
* @param value The value to encode.
* @return The value of the String as a byte[].
*/
static byte[] encodeString(String cs, String value) {
try {
return value.getBytes(cs);
} catch (UnsupportedEncodingException e) {
return value.getBytes();
}
}
/**
* Link the original cause to an SQLWarning.
* SQLWarning to enhance.
* @param cause The Throwable to link.
* @return The original SQLWarning object.
*/
public static SQLWarning linkException(SQLWarning sqle, Throwable cause) {
return (SQLWarning) linkException((Exception) sqle, cause);
}
/**
* Link the original cause to an SQLException.
* SQLException to enhance.
* @param cause The Throwable to link.
* @return The original SQLException object.
*/
public static SQLException linkException(SQLException sqle, Throwable cause) {
return (SQLException) linkException((Exception) sqle, cause);
}
/**
* Link the original cause to an Exception.
* Throwable.initCause(Throwable)
* method will be invoked to chain the exception, else the exception is
* logged via the {@link Logger} class.
* Modeled after the code written by Brian Heineman.
*
* @param exception The Exception to enhance.
* @param cause The Throwable to link.
* @return The original Exception object.
*/
public static Throwable linkException(Exception exception, Throwable cause) {
Class exceptionClass = exception.getClass();
Class[] parameterTypes = new Class[] {Throwable.class};
Object[] arguments = new Object[] {cause};
try {
Method initCauseMethod = exceptionClass.getMethod("initCause", parameterTypes);
initCauseMethod.invoke(exception, arguments);
} catch (NoSuchMethodException e) {
// Best we can do; this method does not exist in older JVMs.
if (Logger.isActive()) {
Logger.logException((Exception) cause);
}
} catch (Exception e) {
// Ignore all other exceptions. Do not prevent the main exception
// from being returned if reflection fails for any reason.
}
return exception;
}
/**
* Convert a timestamp to a different Timezone.
*
* @param value the timestamp value
* @param target the Calendar containing the TimeZone
* @return the new timestamp value as a long
*/
public static long timeToZone(java.util.Date value, Calendar target) {
java.util.Date tmp = target.getTime();
try {
GregorianCalendar cal = (GregorianCalendar) calendar.get();
cal.setTime(value);
if (!Driver.JDBC3 && value instanceof Timestamp) {
// Not Running under 1.4 so need to add milliseconds
cal.set(Calendar.MILLISECOND,
((Timestamp)value).getNanos() / 1000000);
}
target.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY));
target.set(Calendar.MINUTE, cal.get(Calendar.MINUTE));
target.set(Calendar.SECOND, cal.get(Calendar.SECOND));
target.set(Calendar.MILLISECOND, cal.get(Calendar.MILLISECOND));
target.set(Calendar.YEAR, cal.get(Calendar.YEAR));
target.set(Calendar.MONTH, cal.get(Calendar.MONTH));
target.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH));
return target.getTime().getTime();
}
finally {
target.setTime(tmp);
}
}
/**
* Convert a timestamp from a different Timezone.
* @param value the timestamp value.
* @param target the Calendar containing the TimeZone.
* @return The new timestamp value as a long.
*/
public static long timeFromZone(java.util.Date value , Calendar target) {
java.util.Date tmp = target.getTime();
try {
GregorianCalendar cal = (GregorianCalendar) calendar.get();
target.setTime(value);
if (!Driver.JDBC3 && value instanceof Timestamp) {
// Not Running under 1.4 so need to add milliseconds
target.set(Calendar.MILLISECOND,
((Timestamp)value).getNanos() / 1000000);
}
cal.set(Calendar.HOUR_OF_DAY, target.get(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, target.get(Calendar.MINUTE));
cal.set(Calendar.SECOND, target.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, target.get(Calendar.MILLISECOND));
cal.set(Calendar.YEAR, target.get(Calendar.YEAR));
cal.set(Calendar.MONTH, target.get(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, target.get(Calendar.DAY_OF_MONTH));
return cal.getTime().getTime();
}
finally {
target.setTime(tmp);
}
}
/**
* Converts a LOB to the equivalent Java type, i.e. Clob to
* String and Blob to byte[]. If the
* value passed is not a LOB object, it is left unchanged and no exception
* is thrown; the idea is to transparently convert only LOBs.
*
* @param value an object that may be a LOB
* @return if the value was a LOB, the equivalent Java object, otherwise
* the original value
* @throws SQLException if an error occurs while reading the LOB contents
*/
public static Object convertLOB(Object value) throws SQLException {
if (value instanceof Clob) {
Clob c = (Clob) value;
return c.getSubString(1, (int) c.length());
}
if (value instanceof Blob) {
Blob b = (Blob) value;
return b.getBytes(1, (int) b.length());
}
return value;
}
/**
* Converts a LOB type constant to the equivalent Java type constant, i.e.
* Types.CLOB to Types.LONGVARCHAR and
* Types.BLOB to Types.LONGVARBINARY. If the
* type passed is not that of a LOB, it is left unchanged and no exception
* is thrown; the idea is to transparently convert only LOB types.
*
* @param type a {@link Types} constant defining a JDBC type, possibly a
* LOB
* @return if the type was that of a LOB, the equivalent Java object type,
* otherwise the original type
*/
public static int convertLOBType(int type) {
switch (type) {
case Types.BLOB:
return Types.LONGVARBINARY;
case Types.CLOB:
return Types.LONGVARCHAR;
default:
return type;
}
}
/**
* Checks the os.name system property to see if it starts
* with "windows".
*
* @return true if os.name starts with "windows",
* else false.
*/
public static boolean isWindowsOS() {
return System.getProperty("os.name").toLowerCase().startsWith("windows");
}
// ------------- Private methods ---------
/**
* Returns the connection for a given ResultSet,
* Statement or Connection object.
*
* @param callerReference an object reference to the caller of this method;
* must be a Connection, Statement or
* ResultSet
* @return a connection
*/
private static ConnectionJDBC2 getConnection(Object callerReference) {
if (callerReference == null) {
throw new IllegalArgumentException("callerReference cannot be null.");
}
Connection connection;
try {
if (callerReference instanceof Connection) {
connection = (Connection) callerReference;
} else if (callerReference instanceof Statement) {
connection = ((Statement) callerReference).getConnection();
} else if (callerReference instanceof ResultSet) {
connection = ((ResultSet) callerReference).getStatement().getConnection();
} else {
throw new IllegalArgumentException("callerReference is invalid.");
}
} catch (SQLException e) {
throw new IllegalStateException(e.getMessage());
}
return (ConnectionJDBC2) connection;
}
private Support() {
// Prevent an instance of this class being created.
}
/**
* Calculate the buffer size to use when buffering the InputStream
* for named pipes.
* SmbNamedPipe will send a request for a particular
* size of packet. In other words, if you only request 1 byte, the
* SmbNamedPipe will send a request out and only ask for 1 byte
* back. Buffering the expected packet size ensures that all of the data
* will be returned in the buffer without wasting any space.
*
* @param tdsVersion the TDS version for the connection
* @param packetSize requested packet size for the connection
* @return minimum default packet size if packetSize == 0,
* else packetSize
*/
static int calculateNamedPipeBufferSize(final int tdsVersion, final int packetSize) {
if (packetSize == 0) {
if (tdsVersion >= Driver.TDS70) {
return TdsCore.DEFAULT_MIN_PKT_SIZE_TDS70;
}
return TdsCore.MIN_PKT_SIZE;
}
return packetSize;
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/UniqueIdentifier.java 0000644 0001750 0001750 00000005153 11316672660 027220 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
/**
* This class encapsulates the MS SQL2000 UniqueIdentifer data type.
*
* @author Mike Hutchinson.
* @version $Id: UniqueIdentifier.java,v 1.4 2005/04/28 14:29:30 alin_sinpalean Exp $
*/
public class UniqueIdentifier {
private final byte[] bytes;
/**
* Construct a unique identifier with the supplied byte array.
*/
public UniqueIdentifier(byte[] id) {
bytes = id;
}
/**
* Retrieve the unique identifier as a byte array.
*
* @return The unique identifier as a byte[].
*/
public byte[] getBytes() {
return (byte [])bytes.clone();
}
/**
* Retrieve the unique identifier as a formatted string.
* String.
*/
public String toString() {
byte[] tmp = bytes;
if (bytes.length == 16) {
// Need to swap some bytes for correct text version
tmp = new byte[bytes.length];
System.arraycopy(bytes, 0, tmp, 0, bytes.length);
tmp[0] = bytes[3];
tmp[1] = bytes[2];
tmp[2] = bytes[1];
tmp[3] = bytes[0];
tmp[4] = bytes[5];
tmp[5] = bytes[4];
tmp[6] = bytes[7];
tmp[7] = bytes[6];
}
byte bb[] = new byte[1];
StringBuffer buf = new StringBuffer(36);
for (int i = 0; i < bytes.length; i++) {
bb[0] = tmp[i];
buf.append(Support.toHex(bb));
if (i == 3 || i == 5 || i == 7 || i == 9) {
buf.append('-');
}
}
return buf.toString();
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/JtdsResultSetMetaData.java 0000644 0001750 0001750 00000014365 11316672660 030134 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
/**
* jTDS implementation of the java.sql.ResultSetMetaData interface.
*
*
*
* @author Mike Hutchinson
* @version $Id: JtdsResultSetMetaData.java,v 1.9.2.3 2009/12/30 08:45:34 ickzon Exp $
*/
public class JtdsResultSetMetaData implements ResultSetMetaData {
private final ColInfo[] columns;
private final int columnCount;
private final boolean useLOBs;
/**
* Construct ResultSetMetaData object over the current ColInfo array.
*
* @param columns The current ColInfo row descriptor array.
* @param columnCount The number of visible columns.
*/
JtdsResultSetMetaData(ColInfo[] columns, int columnCount, boolean useLOBs) {
this.columns = columns;
this.columnCount = columnCount;
this.useLOBs = useLOBs;
}
/**
* Return the column descriptor given a column index.
*
* @param column The column index (from 1 .. n).
* @return The column descriptor as a ColInfo.
* @throws SQLException
*/
ColInfo getColumn(int column) throws SQLException {
if (column < 1 || column > columnCount) {
throw new SQLException(
Messages.get("error.resultset.colindex",
Integer.toString(column)), "07009");
}
return columns[column - 1];
}
// ------ java.sql.ResultSetMetaData methods follow -------
public int getColumnCount() throws SQLException {
return this.columnCount;
}
public int getColumnDisplaySize(int column) throws SQLException {
return getColumn(column).displaySize;
}
public int getColumnType(int column) throws SQLException {
if (useLOBs) {
return getColumn(column).jdbcType;
} else {
return Support.convertLOBType(getColumn(column).jdbcType);
}
}
public int getPrecision(int column) throws SQLException {
return getColumn(column).precision;
}
public int getScale(int column) throws SQLException {
return getColumn(column).scale;
}
public int isNullable(int column) throws SQLException {
return getColumn(column).nullable;
}
public boolean isAutoIncrement(int column) throws SQLException {
return getColumn(column).isIdentity;
}
public boolean isCaseSensitive(int column) throws SQLException {
return getColumn(column).isCaseSensitive;
}
public boolean isCurrency(int column) throws SQLException {
return TdsData.isCurrency(getColumn(column));
}
public boolean isDefinitelyWritable(int column) throws SQLException {
getColumn(column);
return false;
}
public boolean isReadOnly(int column) throws SQLException {
return !getColumn(column).isWriteable;
}
public boolean isSearchable(int column) throws SQLException {
return TdsData.isSearchable(getColumn(column));
}
public boolean isSigned(int column) throws SQLException {
return TdsData.isSigned(getColumn(column));
}
public boolean isWritable(int column) throws SQLException {
return getColumn(column).isWriteable;
}
public String getCatalogName(int column) throws SQLException {
ColInfo col = getColumn(column);
return (col.catalog == null) ? "" : col.catalog;
}
public String getColumnClassName(int column) throws SQLException {
String c = Support.getClassName(getColumnType(column));
if (!useLOBs) {
if ("java.sql.Clob".equals(c)) {
return "java.lang.String";
}
if ("java.sql.Blob".equals(c)) {
return "[B";
}
}
return c;
}
public String getColumnLabel(int column) throws SQLException {
return getColumn(column).name;
}
public String getColumnName(int column) throws SQLException {
return getColumn(column).name;
}
public String getColumnTypeName(int column) throws SQLException {
return getColumn(column).sqlType;
}
public String getSchemaName(int column) throws SQLException {
ColInfo col = getColumn(column);
return (col.schema == null) ? "" : col.schema;
}
public String getTableName(int column) throws SQLException {
ColInfo col = getColumn(column);
return (col.tableName == null) ? "" : col.tableName;
}
/////// JDBC4 demarcation, do NOT put any JDBC3 code below this line ///////
/* (non-Javadoc)
* @see java.sql.Wrapper#isWrapperFor(java.lang.Class)
*/
public boolean isWrapperFor(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#unwrap(java.lang.Class)
*/
public Object unwrap(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/Semaphore.java 0000644 0001750 0001750 00000010745 11316672660 025675 0 ustar martin martin //jTDS JDBC Driver for Microsoft SQL Server and Sybase
//Copyright (C) 2004 The jTDS Project
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
/**
* Simple semaphore class used to serialize access requests over the network
* connection.
*
* Based on the code originally written by Doug Lea. Once JDK 1.5 is the
* standard this class can be replaced by the
* java.util.concurrent.Sempahore class.
*
* @author Mike Hutchinson
* @version $Id: Semaphore.java,v 1.1 2004/12/20 15:51:17 alin_sinpalean Exp $
*/
public class Semaphore {
/**
* Current number of available permits.
*/
protected long permits;
/**
* Create a Semaphore with the given initial number of permits. Using a
* seed of one makes the semaphore act as a mutual exclusion lock. Negative
* seeds are also allowed, in which case no acquires will proceed until the
* number of releases has pushed the number of permits past 0.
*/
public Semaphore(long initialPermits) {
permits = initialPermits;
}
/**
* Wait until a permit is available, and take one.
*/
public void acquire() throws InterruptedException {
if (Thread.interrupted()) {
throw new InterruptedException();
}
synchronized (this) {
try {
while (permits <= 0) {
wait();
}
--permits;
} catch (InterruptedException ex) {
notify();
throw ex;
}
}
}
/**
* Wait at most msecs millisconds for a permit.
*/
public boolean attempt(long msecs) throws InterruptedException {
if (Thread.interrupted()) {
throw new InterruptedException();
}
synchronized (this) {
if (permits > 0) {
--permits;
return true;
} else if (msecs <= 0) {
return false;
} else {
try {
long startTime = System.currentTimeMillis();
long waitTime = msecs;
while (true) {
wait(waitTime);
if (permits > 0) {
--permits;
return true;
} else {
waitTime = msecs - (System.currentTimeMillis() - startTime);
if (waitTime <= 0) {
return false;
}
}
}
} catch (InterruptedException ex) {
notify();
throw ex;
}
}
}
}
/**
* Release a permit.
*/
public synchronized void release() {
++permits;
notify();
}
/**
* Release N permits. release(n) is equivalent in effect to:
*
* for (int i = 0; i < n; ++i) release();
*
*
* But may be more efficient in some semaphore implementations.
*
* @exception IllegalArgumentException if n is negative
*/
public synchronized void release(long n) {
if (n < 0) {
throw new IllegalArgumentException("Negative argument");
}
permits += n;
for (long i = 0; i < n; ++i) {
notify();
}
}
/**
* Return the current number of available permits. Returns an accurate, but
* possibly unstable value, that may change immediately after returning.
*/
public synchronized long permits() {
return permits;
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/CachedResultSet.java 0000644 0001750 0001750 00000154250 11316672660 026774 0 ustar martin martin //jTDS JDBC Driver for Microsoft SQL Server and Sybase
//Copyright (C) 2004 The jTDS Project
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashSet;
/**
* A memory cached scrollable/updateable result set.
*
* Notes:
*
*
*
* @author Mike Hutchinson
* @version $Id: CachedResultSet.java,v 1.26 2007/07/08 17:28:23 bheineman Exp $
* @todo Should add a "close statement" flag to the constructors
*/
public class CachedResultSet extends JtdsResultSet {
/** Indicates currently inserting. */
protected boolean onInsertRow;
/** Buffer row used for inserts. */
protected ParamInfo[] insertRow;
/** The "update" row. */
protected ParamInfo[] updateRow;
// FIXME Remember if the row was updated/deleted for each row in the ResultSet
/** Indicates that row has been updated. */
protected boolean rowUpdated;
/** Indicates that row has been deleted. */
protected boolean rowDeleted;
/** The row count of the initial result set. */
protected int initialRowCnt;
/** True if this is a local temporary result set. */
protected final boolean tempResultSet;
/** Cursor TdsCore object. */
protected final TdsCore cursorTds;
/** Updates TdsCore object used for positioned updates. */
protected final TdsCore updateTds;
/** Flag to indicate Sybase. */
protected boolean isSybase;
/** Fetch size has been changed. */
protected boolean sizeChanged;
/** Original SQL statement. */
protected String sql;
/** Original procedure name. */
protected final String procName;
/** Original parameters. */
protected final ParamInfo[] procedureParams;
/** Table is keyed. */
protected boolean isKeyed;
/** First table name in select. */
protected String tableName;
/** The parent connection object */
protected ConnectionJDBC2 connection;
/**
* Constructs a new cached result set.
*
* This result set will either be cached in memory or, if the cursor name
* is set, can be a forward only server side cursor. This latter form of
* cursor can also support positioned updates.
*
* @param statement the parent statement object
* @param sql the SQL statement used to build the result set
* @param procName an optional stored procedure name
* @param procedureParams parameters for prepared statements
* @param resultSetType the result set type eg scrollable
* @param concurrency the result set concurrency eg updateable
* @exception SQLException if an error occurs
*/
CachedResultSet(JtdsStatement statement,
String sql,
String procName,
ParamInfo[] procedureParams,
int resultSetType,
int concurrency) throws SQLException {
super(statement, resultSetType, concurrency, null);
this.connection = (ConnectionJDBC2) statement.getConnection();
this.cursorTds = statement.getTds();
this.sql = sql;
this.procName = procName;
this.procedureParams = procedureParams;
if (resultSetType == ResultSet.TYPE_FORWARD_ONLY
&& concurrency != ResultSet.CONCUR_READ_ONLY
&& cursorName != null) {
// Need an addtional TDS for positioned updates
this.updateTds = new TdsCore(connection, statement.getMessages());
} else {
this.updateTds = this.cursorTds;
}
this.isSybase = Driver.SYBASE == connection.getServerType();
this.tempResultSet = false;
//
// Now create the specified type of cursor
//
cursorCreate();
}
/**
* Constructs a cached result set based on locally generated data.
*
* @param statement the parent statement object
* @param colName array of column names
* @param colType array of corresponding data types
* @exception SQLException if an error occurs
*/
CachedResultSet(JtdsStatement statement,
String[] colName, int[] colType) throws SQLException {
super(statement, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE, null);
//
// Construct the column descriptor array
//
this.columns = new ColInfo[colName.length];
for (int i = 0; i < colName.length; i++) {
ColInfo ci = new ColInfo();
ci.name = colName[i];
ci.realName = colName[i];
ci.jdbcType = colType[i];
ci.isCaseSensitive = false;
ci.isIdentity = false;
ci.isWriteable = false;
ci.nullable = 2;
ci.scale = 0;
TdsData.fillInType(ci);
columns[i] = ci;
}
this.columnCount = getColumnCount(columns);
this.rowData = new ArrayList(INITIAL_ROW_COUNT);
this.rowsInResult = 0;
this.initialRowCnt = 0;
this.pos = POS_BEFORE_FIRST;
this.tempResultSet = true;
this.cursorName = null;
this.cursorTds = null;
this.updateTds = null;
this.procName = null;
this.procedureParams = null;
}
/**
* Creates a cached result set with the same columns (and optionally data)
* as an existing result set.
*
* @param rs the result set to copy
* @param load load data from the supplied result set
* @throws SQLException if an error occurs
*/
CachedResultSet(JtdsResultSet rs, boolean load) throws SQLException {
super((JtdsStatement)rs.getStatement(),
rs.getStatement().getResultSetType(),
rs.getStatement().getResultSetConcurrency(), null);
//
JtdsStatement stmt = ((JtdsStatement) rs.getStatement());
//
// OK If the user requested an updateable result set tell them
// they can't have one!
//
if (concurrency != ResultSet.CONCUR_READ_ONLY) {
concurrency = ResultSet.CONCUR_READ_ONLY;
stmt.addWarning(new SQLWarning(
Messages.get("warning.cursordowngraded",
"CONCUR_READ_ONLY"), "01000"));
}
//
// If the user requested a scroll sensitive cursor tell them
// they can't have that either!
//
if (resultSetType >= ResultSet.TYPE_SCROLL_SENSITIVE) {
resultSetType = ResultSet.TYPE_SCROLL_INSENSITIVE;
stmt.addWarning(new SQLWarning(
Messages.get("warning.cursordowngraded",
"TYPE_SCROLL_INSENSITIVE"), "01000"));
}
this.columns = rs.getColumns();
this.columnCount = getColumnCount(columns);
this.rowData = new ArrayList(INITIAL_ROW_COUNT);
this.rowsInResult = 0;
this.initialRowCnt = 0;
this.pos = POS_BEFORE_FIRST;
this.tempResultSet = true;
this.cursorName = null;
this.cursorTds = null;
this.updateTds = null;
this.procName = null;
this.procedureParams = null;
//
// Load result set into buffer
//
if (load) {
while (rs.next()) {
rowData.add(copyRow(rs.getCurrentRow()));
}
this.rowsInResult = rowData.size();
this.initialRowCnt = rowsInResult;
}
}
/**
* Creates a cached result set containing one row.
*
* @param statement the parent statement object
* @param columns the column descriptor array
* @param data the row data
* @throws SQLException if an error occurs
*/
CachedResultSet(JtdsStatement statement,
ColInfo columns[], Object data[]) throws SQLException {
super(statement, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, null);
this.columns = columns;
this.columnCount = getColumnCount(columns);
this.rowData = new ArrayList(1);
this.rowsInResult = 1;
this.initialRowCnt = 1;
this.pos = POS_BEFORE_FIRST;
this.tempResultSet = true;
this.cursorName = null;
this.rowData.add(copyRow(data));
this.cursorTds = null;
this.updateTds = null;
this.procName = null;
this.procedureParams = null;
}
/**
* Modify the concurrency of the result set.
*
* Use to make result set read only once loaded.
*
* @param concurrency the concurrency value eg
* ResultSet.CONCUR_READ_ONLY
*/
void setConcurrency(int concurrency) {
this.concurrency = concurrency;
}
/**
* Creates a new scrollable result set in memory or a named server cursor.
*
* @exception SQLException if an error occurs
*/
private void cursorCreate()
throws SQLException {
//
boolean isSelect = false;
int requestedConcurrency = concurrency;
int requestedType = resultSetType;
//
// If the useCursor property is set we will try and use a server
// side cursor for forward read only cursors. With the default
// fetch size of 100 this is a reasonable emulation of the
// MS fast forward cursor.
//
if (cursorName == null
&& connection.getUseCursors()
&& resultSetType == ResultSet.TYPE_FORWARD_ONLY
&& concurrency == ResultSet.CONCUR_READ_ONLY) {
// The useCursors connection property was set true
// so we need to create a private cursor name
cursorName = connection.getCursorName();
}
//
// Validate the SQL statement to ensure we have a select.
//
if (resultSetType != ResultSet.TYPE_FORWARD_ONLY
|| concurrency != ResultSet.CONCUR_READ_ONLY
|| cursorName != null) {
//
// We are going to need access to a SELECT statement for
// this to work. Reparse the SQL now and check.
//
String tmp[] = SQLParser.parse(sql, new ArrayList(),
(ConnectionJDBC2) statement.getConnection(), true);
if ("select".equals(tmp[2])) {
isSelect = true;
if (tmp[3] != null && tmp[3].length() > 0) {
// OK We have a select with at least one table.
tableName = tmp[3];
} else {
// Can't find a table name so can't update
concurrency = ResultSet.CONCUR_READ_ONLY;
}
} else {
// No good we can't update and we can't declare a cursor
cursorName = null;
concurrency = ResultSet.CONCUR_READ_ONLY;
if (resultSetType != ResultSet.TYPE_FORWARD_ONLY) {
resultSetType = ResultSet.TYPE_SCROLL_INSENSITIVE;
}
}
}
//
// If a cursor name is specified we try and declare a conventional cursor.
// A server error will occur if we try to create a named cursor on a non
// select statement.
//
if (cursorName != null) {
//
// Create and execute DECLARE CURSOR
//
StringBuffer cursorSQL =
new StringBuffer(sql.length() + cursorName.length()+ 128);
cursorSQL.append("DECLARE ").append(cursorName)
.append(" CURSOR FOR ");
//
// We need to adjust any parameter offsets now as the prepended
// DECLARE CURSOR will throw the parameter positions off.
//
ParamInfo[] parameters = procedureParams;
if (procedureParams != null && procedureParams.length > 0) {
parameters = new ParamInfo[procedureParams.length];
int offset = cursorSQL.length();
for (int i = 0; i < parameters.length; i++) {
// Clone parameters to avoid corrupting offsets in original
parameters[i] = (ParamInfo) procedureParams[i].clone();
parameters[i].markerPos += offset;
}
}
cursorSQL.append(sql);
cursorTds.executeSQL(cursorSQL.toString(), null, parameters,
false, statement.getQueryTimeout(), statement.getMaxRows(),
statement.getMaxFieldSize(), true);
cursorTds.clearResponseQueue();
cursorTds.getMessages().checkErrors();
//
// OK now open cursor and fetch the first set (fetchSize) rows
//
cursorSQL.setLength(0);
cursorSQL.append("\r\nOPEN ").append(cursorName);
if (fetchSize > 1 && isSybase) {
cursorSQL.append("\r\nSET CURSOR ROWS ").append(fetchSize);
cursorSQL.append(" FOR ").append(cursorName);
}
cursorSQL.append("\r\nFETCH ").append(cursorName);
cursorTds.executeSQL(cursorSQL.toString(), null, null, false,
statement.getQueryTimeout(), statement.getMaxRows(),
statement.getMaxFieldSize(), true);
//
// Check we have a result set
//
while (!cursorTds.getMoreResults() && !cursorTds.isEndOfResponse());
if (!cursorTds.isResultSet()) {
// Throw exception but queue up any others
SQLException ex = new SQLException(
Messages.get("error.statement.noresult"), "24000");
ex.setNextException(statement.getMessages().exceptions);
throw ex;
}
columns = cursorTds.getColumns();
if (connection.getServerType() == Driver.SQLSERVER) {
// Last column will be rowstat but will not be marked as hidden
// as we do not have the Column meta data returned by the API
// cursor.
// Hide it now to avoid confusion (also should not be updated).
if (columns.length > 0) {
columns[columns.length - 1].isHidden = true;
}
}
columnCount = getColumnCount(columns);
rowsInResult = cursorTds.isDataInResultSet() ? 1 : 0;
} else {
//
// Open a memory cached scrollable or forward only possibly updateable cursor
//
if (isSelect && (concurrency != ResultSet.CONCUR_READ_ONLY
|| resultSetType >= ResultSet.TYPE_SCROLL_SENSITIVE)) {
// Need to execute SELECT .. FOR BROWSE to get
// the MetaData we require for updates etc
// OK Should have an SQL select statement
// append " FOR BROWSE" to obtain table names
// NB. We can't use any jTDS temporary stored proc
cursorTds.executeSQL(sql + " FOR BROWSE", null, procedureParams,
false, statement.getQueryTimeout(),
statement.getMaxRows(), statement.getMaxFieldSize(),
true);
while (!cursorTds.getMoreResults() && !cursorTds.isEndOfResponse());
if (!cursorTds.isResultSet()) {
// Throw exception but queue up any others
SQLException ex = new SQLException(
Messages.get("error.statement.noresult"), "24000");
ex.setNextException(statement.getMessages().exceptions);
throw ex;
}
columns = cursorTds.getColumns();
columnCount = getColumnCount(columns);
rowData = new ArrayList(INITIAL_ROW_COUNT);
//
// Load result set into buffer
//
cacheResultSetRows();
rowsInResult = rowData.size();
initialRowCnt = rowsInResult;
pos = POS_BEFORE_FIRST;
//
// If cursor is built over one table and the table has
// key columns then the result set is updateable and / or
// can be used as a scroll sensitive result set.
//
if (!isCursorUpdateable()) {
// No so downgrade
concurrency = ResultSet.CONCUR_READ_ONLY;
if (resultSetType != ResultSet.TYPE_FORWARD_ONLY) {
resultSetType = ResultSet.TYPE_SCROLL_INSENSITIVE;
}
}
} else {
//
// Create a read only cursor using direct SQL
//
cursorTds.executeSQL(sql, procName, procedureParams, false,
statement.getQueryTimeout(), statement.getMaxRows(),
statement.getMaxFieldSize(), true);
while (!cursorTds.getMoreResults() && !cursorTds.isEndOfResponse());
if (!cursorTds.isResultSet()) {
// Throw exception but queue up any others
SQLException ex = new SQLException(
Messages.get("error.statement.noresult"), "24000");
ex.setNextException(statement.getMessages().exceptions);
throw ex;
}
columns = cursorTds.getColumns();
columnCount = getColumnCount(columns);
rowData = new ArrayList(INITIAL_ROW_COUNT);
//
// Load result set into buffer
//
cacheResultSetRows();
rowsInResult = rowData.size();
initialRowCnt = rowsInResult;
pos = POS_BEFORE_FIRST;
}
}
//
// Report any cursor downgrade warnings
//
if (concurrency < requestedConcurrency) {
statement.addWarning(new SQLWarning(
Messages.get("warning.cursordowngraded",
"CONCUR_READ_ONLY"), "01000"));
}
if (resultSetType < requestedType) {
statement.addWarning(new SQLWarning(
Messages.get("warning.cursordowngraded",
"TYPE_SCROLL_INSENSITIVE"), "01000"));
}
//
// Report any SQLExceptions
//
statement.getMessages().checkErrors();
}
/**
* Analyses the tables in the result set and determines if the primary key
* columns needed to make it updateable exist.
*
* Sybase (and SQL 6.5) will automatically include any additional key and
* timestamp columns as hidden fields even if the user does not reference
* them in the select statement.
*
* If the table is unkeyed but there is an identity column then this is
* promoted to a key.
*
* Alternatively we can update, provided all the columns in the table row
* have been selected, by regarding all of them as keys.
*
* SQL Server 7+ does not return the correct primary key meta data for
* temporary tables so the driver has to query the catalog to locate any
* keys.
*
* @return true if there is one table and it is keyed
*/
boolean isCursorUpdateable() throws SQLException {
//
// Get fully qualified table names and check keys
//
isKeyed = false;
HashSet tableSet = new HashSet();
for (int i = 0; i < columns.length; i++) {
ColInfo ci = columns[i];
if (ci.isKey) {
// If a table lacks a key Sybase flags all columns except timestamps as keys.
// This does not make much sense in the case of text or image fields!
if ("text".equals(ci.sqlType) || "image".equals(ci.sqlType)) {
ci.isKey = false;
} else {
isKeyed = true;
}
} else
if (ci.isIdentity) {
// This is a good choice for a row identifier!
ci.isKey = true;
isKeyed = true;
}
StringBuffer key = new StringBuffer();
if (ci.tableName != null && ci.tableName.length() > 0) {
key.setLength(0);
if (ci.catalog != null) {
key.append(ci.catalog).append('.');
if (ci.schema == null) {
key.append('.');
}
}
if (ci.schema != null) {
key.append(ci.schema).append('.');
}
key.append(ci.tableName);
tableName = key.toString();
tableSet.add(tableName);
}
}
//
// MJH - SQL Server 7/2000 does not return key information for temporary tables.
// I regard this as a bug!
// See if we can find up to the first 8 index columns for ourselves.
//
if (tableName.startsWith("#") && cursorTds.getTdsVersion() >= Driver.TDS70) {
StringBuffer sql = new StringBuffer(1024);
sql.append("SELECT ");
for (int i = 1; i <= 8; i++) {
if (i > 1) {
sql.append(',');
}
sql.append("index_col('tempdb..").append(tableName);
sql.append("', indid, ").append(i).append(')');
}
sql.append(" FROM tempdb..sysindexes WHERE id = object_id('tempdb..");
sql.append(tableName).append("') AND indid > 0 AND ");
sql.append("(status & 2048) = 2048");
cursorTds.executeSQL(sql.toString(), null, null, false, 0,
statement.getMaxRows(), statement.getMaxFieldSize(), true);
while (!cursorTds.getMoreResults() && !cursorTds.isEndOfResponse());
if (cursorTds.isResultSet() && cursorTds.getNextRow())
{
Object row[] = cursorTds.getRowData();
for (int i =0 ; i < row.length; i++) {
String name = (String)row[i];
if (name != null) {
for (int c = 0; c < columns.length; c++) {
if (columns[c].realName != null &&
columns[c].realName.equalsIgnoreCase(name)) {
columns[c].isKey = true;
isKeyed = true;
break;
}
}
}
}
}
// Report any errors found
statement.getMessages().checkErrors();
}
//
// Final fall back make all columns pseudo keys!
// Sybase seems to do this automatically.
//
if (!isKeyed) {
for (int i = 0; i < columns.length; i++) {
String type = columns[i].sqlType;
if (!"ntext".equals(type) &&
!"text".equals(type) &&
!"image".equals(type) &&
!"timestamp".equals(type) &&
columns[i].tableName != null) {
columns[i].isKey = true;
isKeyed = true;
}
}
}
return (tableSet.size() == 1 && isKeyed);
}
/**
* Fetches the next result row from the internal row array.
*
* @param rowNum the row number to fetch
* @return true if a result set row is returned
* @throws SQLException if an error occurs
*/
private boolean cursorFetch(int rowNum)
throws SQLException {
rowUpdated = false;
//
if (cursorName != null) {
//
// Using a conventional forward only server cursor
//
if (!cursorTds.getNextRow()) {
// Need to fetch more rows from server
StringBuffer sql = new StringBuffer(128);
if (isSybase && sizeChanged) {
// Sybase allows us to set a fetch size
sql.append("SET CURSOR ROWS ").append(fetchSize);
sql.append(" FOR ").append(cursorName);
sql.append("\r\n");
}
sql.append("FETCH ").append(cursorName);
// Get the next row or block of rows.
cursorTds.executeSQL(sql.toString(), null, null, false,
statement.getQueryTimeout(), statement.getMaxRows(),
statement.getMaxFieldSize(), true);
while (!cursorTds.getMoreResults() && !cursorTds.isEndOfResponse());
sizeChanged = false; // Indicate fetch size updated
if (!cursorTds.isResultSet() || !cursorTds.getNextRow()) {
pos = POS_AFTER_LAST;
currentRow = null;
statement.getMessages().checkErrors();
return false;
}
}
currentRow = statement.getTds().getRowData();
pos++;
rowsInResult = pos;
statement.getMessages().checkErrors();
return currentRow != null;
}
//
// JDBC2 style Scrollable and/or Updateable cursor
//
if (rowsInResult == 0) {
pos = POS_BEFORE_FIRST;
currentRow = null;
return false;
}
if (rowNum == pos) {
// On current row
//
return true;
}
if (rowNum < 1) {
currentRow = null;
pos = POS_BEFORE_FIRST;
return false;
}
if (rowNum > rowsInResult) {
currentRow = null;
pos = POS_AFTER_LAST;
return false;
}
pos = rowNum;
currentRow = (Object[])rowData.get(rowNum-1);
rowDeleted = currentRow == null;
if (resultSetType >= ResultSet.TYPE_SCROLL_SENSITIVE &&
currentRow != null) {
refreshRow();
}
return true;
}
/**
* Closes the result set.
*/
private void cursorClose() throws SQLException {
if (cursorName != null) {
statement.clearWarnings();
String sql;
if (isSybase) {
sql = "CLOSE " + cursorName +
"\r\nDEALLOCATE CURSOR " + cursorName;
} else {
sql = "CLOSE " + cursorName +
"\r\nDEALLOCATE " + cursorName;
}
cursorTds.submitSQL(sql);
}
rowData = null;
}
/**
* Creates a parameter object for an UPDATE, DELETE or INSERT statement.
*
* @param pos the substitution position of the parameter marker in the SQL
* @param info the ColInfo column descriptor
* @param value the column data item
* @return the new parameter as a ParamInfo object
*/
protected static ParamInfo buildParameter(int pos, ColInfo info, Object value, boolean isUnicode)
throws SQLException {
int length = 0;
if (value instanceof String) {
length = ((String)value).length();
} else
if (value instanceof byte[]) {
length = ((byte[])value).length;
} else
if (value instanceof BlobImpl) {
BlobImpl blob = (BlobImpl)value;
value = blob.getBinaryStream();
length = (int)blob.length();
} else
if (value instanceof ClobImpl) {
ClobImpl clob = (ClobImpl)value;
value = clob.getCharacterStream();
length = (int)clob.length();
}
ParamInfo param = new ParamInfo(info, null, value, length);
param.isUnicode = "nvarchar".equals(info.sqlType) ||
"nchar".equals(info.sqlType) ||
"ntext".equals(info.sqlType) ||
isUnicode;
param.markerPos = pos;
return param;
}
/**
* Sets the specified column's data value.
*
* @param colIndex index of the column
* @param value new column value
* @return the value, possibly converted to an internal type
*/
protected Object setColValue(int colIndex, int jdbcType, Object value, int length)
throws SQLException {
value = super.setColValue(colIndex, jdbcType, value, length);
if (!onInsertRow && currentRow == null) {
throw new SQLException(Messages.get("error.resultset.norow"), "24000");
}
colIndex--;
ParamInfo pi;
ColInfo ci = columns[colIndex];
boolean isUnicode = TdsData.isUnicode(ci);
if (onInsertRow) {
pi = insertRow[colIndex];
if (pi == null) {
pi = new ParamInfo(-1, isUnicode);
pi.collation = ci.collation;
pi.charsetInfo = ci.charsetInfo;
insertRow[colIndex] = pi;
}
} else {
if (updateRow == null) {
updateRow = new ParamInfo[columnCount];
}
pi = updateRow[colIndex];
if (pi == null) {
pi = new ParamInfo(-1, isUnicode);
pi.collation = ci.collation;
pi.charsetInfo = ci.charsetInfo;
updateRow[colIndex] = pi;
}
}
if (value == null) {
pi.value = null;
pi.length = 0;
pi.jdbcType = ci.jdbcType;
pi.isSet = true;
if (pi.jdbcType == Types.NUMERIC || pi.jdbcType == Types.DECIMAL) {
pi.scale = TdsData.DEFAULT_SCALE;
} else {
pi.scale = 0;
}
} else {
pi.value = value;
pi.length = length;
pi.isSet = true;
pi.jdbcType = jdbcType;
if (pi.value instanceof BigDecimal) {
pi.scale = ((BigDecimal)pi.value).scale();
} else {
pi.scale = 0;
}
}
return value;
}
/**
* Builds a WHERE clause for UPDATE or DELETE statements.
*
* @param sql the SQL Statement to append the WHERE clause to
* @param params the parameter descriptor array for this statement
* @param select true if this WHERE clause will be used in a select
* statement
* @return the parameter list as a ParamInfo[]
* @throws SQLException if an error occurs
*/
ParamInfo[] buildWhereClause(StringBuffer sql, ArrayList params, boolean select)
throws SQLException {
//
// Now construct where clause
//
sql.append(" WHERE ");
if (cursorName != null) {
//
// Use a positioned update
//
sql.append(" CURRENT OF ").append(cursorName);
} else {
int count = 0;
for (int i = 0; i < columns.length; i++) {
if (currentRow[i] == null) {
if (!"text".equals(columns[i].sqlType)
&& !"ntext".equals(columns[i].sqlType)
&& !"image".equals(columns[i].sqlType)
&& columns[i].tableName != null) {
if (count > 0) {
sql.append(" AND ");
}
sql.append(columns[i].realName);
sql.append(" IS NULL");
}
} else {
if (isKeyed && select) {
// For refresh select only include key columns
if (columns[i].isKey) {
if (count > 0) {
sql.append(" AND ");
}
sql.append(columns[i].realName);
sql.append("=?");
count++;
params.add(buildParameter(sql.length() - 1, columns[i],
currentRow[i], connection.getUseUnicode()));
}
} else {
// Include all available 'searchable' columns in updates/deletes to protect
// against lost updates.
if (!"text".equals(columns[i].sqlType)
&& !"ntext".equals(columns[i].sqlType)
&& !"image".equals(columns[i].sqlType)
&& columns[i].tableName != null) {
if (count > 0) {
sql.append(" AND ");
}
sql.append(columns[i].realName);
sql.append("=?");
count++;
params.add(buildParameter(sql.length() - 1, columns[i],
currentRow[i], connection.getUseUnicode()));
}
}
}
}
}
return (ParamInfo[]) params.toArray(new ParamInfo[params.size()]);
}
/**
* Refreshes a result set row from keyed tables.
*
* If all the tables in the result set have primary keys then the result
* set row can be refreshed by refetching the individual table rows.
*
* @throws SQLException if an error occurs
*/
protected void refreshKeyedRows() throws SQLException
{
//
// Construct a SELECT statement
//
StringBuffer sql = new StringBuffer(100 + columns.length * 10);
sql.append("SELECT ");
int count = 0;
for (int i = 0; i < columns.length; i++) {
if (!columns[i].isKey && columns[i].tableName != null) {
if (count > 0) {
sql.append(',');
}
sql.append(columns[i].realName);
count++;
}
}
if (count == 0) {
// No non key columns in this table?
return;
}
sql.append(" FROM ");
sql.append(tableName);
//
// Construct a where clause using keyed columns only
//
ArrayList params = new ArrayList();
buildWhereClause(sql, params, true);
ParamInfo parameters[] = (ParamInfo[]) params.toArray(new ParamInfo[params.size()]);
//
// Execute the select
//
TdsCore tds = statement.getTds();
tds.executeSQL(sql.toString(), null, parameters, false, 0,
statement.getMaxRows(), statement.getMaxFieldSize(), true);
if (!tds.isEndOfResponse()) {
if (tds.getMoreResults() && tds.getNextRow()) {
// refresh the row data
Object col[] = tds.getRowData();
count = 0;
for (int i = 0; i < columns.length; i++) {
if (!columns[i].isKey) {
currentRow[i] = col[count++];
}
}
} else {
currentRow = null;
}
} else {
currentRow = null;
}
tds.clearResponseQueue();
statement.getMessages().checkErrors();
if (currentRow == null) {
rowData.set(pos-1, null);
rowDeleted = true;
}
}
/**
* Refreshes the row by rereading the result set.
*
* Obviously very slow on large result sets but may be the only option if
* tables do not have keys.
*/
protected void refreshReRead() throws SQLException
{
int savePos = pos;
cursorCreate();
absolute(savePos);
}
//
// -------------------- java.sql.ResultSet methods -------------------
//
public void setFetchSize(int size) throws SQLException {
sizeChanged = size != fetchSize;
super.setFetchSize(size);
}
public void afterLast() throws SQLException {
checkOpen();
checkScrollable();
if (pos != POS_AFTER_LAST) {
cursorFetch(rowsInResult+1);
}
}
public void beforeFirst() throws SQLException {
checkOpen();
checkScrollable();
if (pos != POS_BEFORE_FIRST) {
cursorFetch(0);
}
}
public void cancelRowUpdates() throws SQLException {
checkOpen();
checkUpdateable();
if (onInsertRow) {
throw new SQLException(Messages.get("error.resultset.insrow"), "24000");
}
if (updateRow != null) {
rowUpdated = false;
for (int i = 0; i < updateRow.length; i++) {
if (updateRow[i] != null) {
updateRow[i].clearInValue();
}
}
}
}
public void close() throws SQLException {
if (!closed) {
try {
cursorClose();
} finally {
closed = true;
statement = null;
}
}
}
public void deleteRow() throws SQLException {
checkOpen();
checkUpdateable();
if (currentRow == null) {
throw new SQLException(Messages.get("error.resultset.norow"), "24000");
}
if (onInsertRow) {
throw new SQLException(Messages.get("error.resultset.insrow"), "24000");
}
//
// Construct an SQL DELETE statement
//
StringBuffer sql = new StringBuffer(128);
ArrayList params = new ArrayList();
sql.append("DELETE FROM ");
sql.append(tableName);
//
// Create the WHERE clause
//
ParamInfo parameters[] = buildWhereClause(sql, params, false);
//
// Execute the delete statement
//
updateTds.executeSQL(sql.toString(), null, parameters, false, 0,
statement.getMaxRows(), statement.getMaxFieldSize(), true);
int updateCount = 0;
while (!updateTds.isEndOfResponse()) {
if (!updateTds.getMoreResults()) {
if (updateTds.isUpdateCount()) {
updateCount = updateTds.getUpdateCount();
}
}
}
updateTds.clearResponseQueue();
statement.getMessages().checkErrors();
if (updateCount == 0) {
// No delete. Possibly row was changed on database by another user?
throw new SQLException(Messages.get("error.resultset.deletefail"), "24000");
}
rowDeleted = true;
currentRow = null;
if (resultSetType != ResultSet.TYPE_FORWARD_ONLY) {
// Leave a 'hole' in the result set array.
rowData.set(pos-1, null);
}
}
public void insertRow() throws SQLException {
checkOpen();
checkUpdateable();
if (!onInsertRow) {
throw new SQLException(Messages.get("error.resultset.notinsrow"), "24000");
}
if (!tempResultSet) {
//
// Construct an SQL INSERT statement
//
StringBuffer sql = new StringBuffer(128);
ArrayList params = new ArrayList();
sql.append("INSERT INTO ");
sql.append(tableName);
int sqlLen = sql.length();
//
// Create column list
//
sql.append(" (");
int count = 0;
for (int i = 0; i < columnCount; i++) {
if (insertRow[i] != null) {
if (count > 0) {
sql.append(", ");
}
sql.append(columns[i].realName);
count++;
}
}
//
// Create new values list
//
sql.append(") VALUES(");
count = 0;
for (int i = 0; i < columnCount; i++) {
if (insertRow[i] != null) {
if (count > 0) {
sql.append(", ");
}
sql.append('?');
insertRow[i].markerPos = sql.length()-1;
params.add(insertRow[i]);
count++;
}
}
sql.append(')');
if (count == 0) {
// Empty insert
sql.setLength(sqlLen);
if (isSybase) {
sql.append(" VALUES()");
} else {
sql.append(" DEFAULT VALUES");
}
}
ParamInfo parameters[] = (ParamInfo[]) params.toArray(new ParamInfo[params.size()]);
//
// execute the insert statement
//
updateTds.executeSQL(sql.toString(), null, parameters, false, 0,
statement.getMaxRows(), statement.getMaxFieldSize(), true);
int updateCount = 0;
while (!updateTds.isEndOfResponse()) {
if (!updateTds.getMoreResults()) {
if (updateTds.isUpdateCount()) {
updateCount = updateTds.getUpdateCount();
}
}
}
updateTds.clearResponseQueue();
statement.getMessages().checkErrors();
if (updateCount < 1) {
// No Insert. Probably will not get here as duplicate key etc
// will have already been reported as an exception.
throw new SQLException(Messages.get("error.resultset.insertfail"), "24000");
}
}
//
if (resultSetType >= ResultSet.TYPE_SCROLL_SENSITIVE
|| (resultSetType == ResultSet.TYPE_FORWARD_ONLY && cursorName == null))
{
//
// Now insert copy of row into result set buffer
//
ConnectionJDBC2 con = (ConnectionJDBC2)statement.getConnection();
Object row[] = newRow();
for (int i = 0; i < insertRow.length; i++) {
if (insertRow[i] != null) {
row[i] = Support.convert(con, insertRow[i].value,
columns[i].jdbcType, con.getCharset());
}
}
rowData.add(row);
}
rowsInResult++;
initialRowCnt++;
//
// Clear row data
//
for (int i = 0; insertRow != null && i < insertRow.length; i++) {
if (insertRow[i] != null) {
insertRow[i].clearInValue();
}
}
}
public void moveToCurrentRow() throws SQLException {
checkOpen();
checkUpdateable();
insertRow = null;
onInsertRow = false;
}
public void moveToInsertRow() throws SQLException {
checkOpen();
checkUpdateable();
insertRow = new ParamInfo[columnCount];
onInsertRow = true;
}
public void refreshRow() throws SQLException {
checkOpen();
if (onInsertRow) {
throw new SQLException(Messages.get("error.resultset.insrow"), "24000");
}
//
// If row is being updated discard updates now
//
if (concurrency != ResultSet.CONCUR_READ_ONLY) {
cancelRowUpdates();
rowUpdated = false;
}
if (resultSetType == ResultSet.TYPE_FORWARD_ONLY ||
currentRow == null) {
// Do not try and refresh the row in these cases.
return;
}
//
// If result set is keyed we can refresh the row data from the
// database using the key.
// NB. MS SQL Server #Temporary tables with keys are not identified correctly
// in the column meta data sent after 'for browse'. This means that
// temporary tables can not be used with this logic.
//
if (isKeyed) {
// OK all tables are keyed
refreshKeyedRows();
} else {
// No good have to use brute force approach
refreshReRead();
}
}
public void updateRow() throws SQLException {
checkOpen();
checkUpdateable();
rowUpdated = false;
rowDeleted = false;
if (currentRow == null) {
throw new SQLException(Messages.get("error.resultset.norow"), "24000");
}
if (onInsertRow) {
throw new SQLException(Messages.get("error.resultset.insrow"), "24000");
}
if (updateRow == null) {
// Nothing to update
return;
}
boolean keysChanged = false;
//
// Construct an SQL UPDATE statement
//
StringBuffer sql = new StringBuffer(128);
ArrayList params = new ArrayList();
sql.append("UPDATE ");
sql.append(tableName);
//
// OK now create assign new values
//
sql.append(" SET ");
int count = 0;
for (int i = 0; i < columnCount; i++) {
if (updateRow[i] != null) {
if (count > 0) {
sql.append(", ");
}
sql.append(columns[i].realName);
sql.append("=?");
updateRow[i].markerPos = sql.length()-1;
params.add(updateRow[i]);
count++;
if (columns[i].isKey) {
// Key is changing so in memory row will need to be deleted
// and reinserted at end of row buffer.
keysChanged = true;
}
}
}
if (count == 0) {
// There are no columns to update in this table
// so bail out now.
return;
}
//
// Now construct where clause
//
ParamInfo parameters[] = buildWhereClause(sql, params, false);
//
// Now execute update
//
updateTds.executeSQL(sql.toString(), null, parameters, false, 0,
statement.getMaxRows(), statement.getMaxFieldSize(), true);
int updateCount = 0;
while (!updateTds.isEndOfResponse()) {
if (!updateTds.getMoreResults()) {
if (updateTds.isUpdateCount()) {
updateCount = updateTds.getUpdateCount();
}
}
}
updateTds.clearResponseQueue();
statement.getMessages().checkErrors();
if (updateCount == 0) {
// No update. Possibly row was changed on database by another user?
throw new SQLException(Messages.get("error.resultset.updatefail"), "24000");
}
//
// Update local copy of data
//
if (resultSetType != ResultSet.TYPE_SCROLL_INSENSITIVE) {
// Make in memory copy reflect database update
// Could use refreshRow but this is much faster.
ConnectionJDBC2 con = (ConnectionJDBC2)statement.getConnection();
for (int i = 0; i < updateRow.length; i++) {
if (updateRow[i] != null) {
if (updateRow[i].value instanceof byte[]
&& (columns[i].jdbcType == Types.CHAR ||
columns[i].jdbcType == Types.VARCHAR ||
columns[i].jdbcType == Types.LONGVARCHAR)) {
// Need to handle byte[] to varchar otherwise field
// will be set to hex string rather than characters.
try {
currentRow[i] = new String((byte[])updateRow[i].value, con.getCharset());
} catch (UnsupportedEncodingException e) {
currentRow[i] = new String((byte[])updateRow[i].value);
}
} else {
currentRow[i] = Support.convert(con, updateRow[i].value,
columns[i].jdbcType, con.getCharset());
}
}
}
}
//
// Update state of cached row data
//
if (keysChanged && resultSetType >= ResultSet.TYPE_SCROLL_SENSITIVE) {
// Leave hole at current position and add updated row to end of set
rowData.add(currentRow);
rowsInResult = rowData.size();
rowData.set(pos-1, null);
currentRow = null;
rowDeleted = true;
} else {
rowUpdated = true;
}
//
// Clear update values
//
cancelRowUpdates();
}
public boolean first() throws SQLException {
checkOpen();
checkScrollable();
return cursorFetch(1);
}
public boolean isLast() throws SQLException {
checkOpen();
return(pos == rowsInResult) && (rowsInResult != 0);
}
public boolean last() throws SQLException {
checkOpen();
checkScrollable();
return cursorFetch(rowsInResult);
}
public boolean next() throws SQLException {
checkOpen();
if (pos != POS_AFTER_LAST) {
return cursorFetch(pos+1);
} else {
return false;
}
}
public boolean previous() throws SQLException {
checkOpen();
checkScrollable();
if (pos == POS_AFTER_LAST) {
pos = rowsInResult+1;
}
return cursorFetch(pos-1);
}
public boolean rowDeleted() throws SQLException {
checkOpen();
return rowDeleted;
}
public boolean rowInserted() throws SQLException {
checkOpen();
// return pos > initialRowCnt;
return false; // Same as MSCursorResultSet
}
public boolean rowUpdated() throws SQLException {
checkOpen();
// return rowUpdated;
return false; // Same as MSCursorResultSet
}
public boolean absolute(int row) throws SQLException {
checkOpen();
checkScrollable();
if (row < 1) {
row = (rowsInResult + 1) + row;
}
return cursorFetch(row);
}
public boolean relative(int row) throws SQLException {
checkScrollable();
if (pos == POS_AFTER_LAST) {
return absolute((rowsInResult+1)+row);
} else {
return absolute(pos+row);
}
}
public String getCursorName() throws SQLException {
checkOpen();
// Hide internal cursor names
if (cursorName != null && !cursorName.startsWith("_jtds")) {
return this.cursorName;
}
throw new SQLException(Messages.get("error.resultset.noposupdate"), "24000");
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/BlobImpl.java 0000644 0001750 0001750 00000011054 11316672660 025444 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.SQLException;
import net.sourceforge.jtds.util.BlobBuffer;
/**
* An in-memory or disk based representation of binary data.
*
* @author Brian Heineman
* @author Mike Hutchinson
* @version $Id: BlobImpl.java,v 1.31.2.3 2009/12/30 08:45:34 ickzon Exp $
*/
public class BlobImpl implements Blob {
/**
* 0 length byte[] as initial value for empty
* Blobs.
*/
private static final byte[] EMPTY_BLOB = new byte[0];
/** The underlying BlobBuffer. */
private final BlobBuffer blobBuffer;
/**
* Constructs a new empty Blob instance.
*
* @param connection a reference to the parent connection object
*/
BlobImpl(ConnectionJDBC2 connection) {
this(connection, EMPTY_BLOB);
}
/**
* Constructs a new Blob instance initialized with data.
*
* @param connection a reference to the parent connection object
* @param bytes the blob object to encapsulate
*/
BlobImpl(ConnectionJDBC2 connection, byte[] bytes) {
if (bytes == null) {
throw new IllegalArgumentException("bytes cannot be null");
}
blobBuffer = new BlobBuffer(connection.getBufferDir(), connection.getLobBuffer());
blobBuffer.setBuffer(bytes, false);
}
//
// ------ java.sql.Blob interface methods from here -------
//
public InputStream getBinaryStream() throws SQLException {
return blobBuffer.getBinaryStream(false);
}
public byte[] getBytes(long pos, int length) throws SQLException {
return blobBuffer.getBytes(pos, length);
}
public long length() throws SQLException {
return blobBuffer.getLength();
}
public long position(byte[] pattern, long start) throws SQLException {
return blobBuffer.position(pattern, start);
}
public long position(Blob pattern, long start) throws SQLException {
if (pattern == null) {
throw new SQLException(Messages.get("error.blob.badpattern"), "HY009");
}
return blobBuffer.position(pattern.getBytes(1, (int) pattern.length()), start);
}
public OutputStream setBinaryStream(final long pos) throws SQLException {
return blobBuffer.setBinaryStream(pos, false);
}
public int setBytes(long pos, byte[] bytes) throws SQLException {
if (bytes == null) {
throw new SQLException(Messages.get("error.blob.bytesnull"), "HY009");
}
return setBytes(pos, bytes, 0, bytes.length);
}
public int setBytes(long pos, byte[] bytes, int offset, int len)
throws SQLException {
if (bytes == null) {
throw new SQLException(Messages.get("error.blob.bytesnull"), "HY009");
}
// Force BlobBuffer to take a copy of the byte array
// In many cases this is wasteful but the user may
// reuse the byte buffer corrupting the original set
return blobBuffer.setBytes(pos, bytes, offset, len, true);
}
public void truncate(long len) throws SQLException {
blobBuffer.truncate(len);
}
/////// JDBC4 demarcation, do NOT put any JDBC3 code below this line ///////
public void free() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
public InputStream getBinaryStream(long pos, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/SharedLocalNamedPipe.java 0000644 0001750 0001750 00000012066 11316672660 027714 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.io.*;
/**
* This class implements inter-process communication (IPC) to the database
* server using local named pipes (will only work on Windows).
*
* @author Adam Etheredge
* @version $Id: SharedLocalNamedPipe.java,v 1.12 2007/07/08 21:38:13 bheineman Exp $
*/
public class SharedLocalNamedPipe extends SharedSocket {
/**
* The named pipe as a file.
*/
RandomAccessFile pipe;
/**
* Creates a new instance of SharedLocalNamedPipe.
*
* @param connection the connection object
* @throws IOException if an I/O error occurs
*/
public SharedLocalNamedPipe(ConnectionJDBC2 connection) throws IOException {
super(connection.getBufferDir(), connection.getTdsVersion(), connection.getServerType());
final String serverName = connection.getServerName();
final String instanceName = connection.getInstanceName();
final StringBuffer pipeName = new StringBuffer(64);
pipeName.append("\\\\");
if (serverName == null || serverName.length() == 0) {
pipeName.append( '.' );
} else {
pipeName.append(serverName);
}
pipeName.append("\\pipe");
if (instanceName != null && instanceName.length() != 0) {
pipeName.append("\\MSSQL$").append(instanceName);
}
String namedPipePath = DefaultProperties.getNamedPipePath(connection.getServerType());
pipeName.append(namedPipePath.replace('/', '\\'));
this.pipe = new RandomAccessFile(pipeName.toString(), "rw");
final int bufferSize = Support.calculateNamedPipeBufferSize(
connection.getTdsVersion(), connection.getPacketSize());
setOut(new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream(this.pipe.getFD()), bufferSize)));
setIn(new DataInputStream(
new BufferedInputStream(
new FileInputStream(this.pipe.getFD()), bufferSize)));
}
/**
* Get the connected status of this socket.
*
* @return true if the underlying named pipe is connected
*/
boolean isConnected() {
return pipe != null;
}
/**
* Send an network packet. If output for another virtual socket is in
* progress this packet will be sent later.
*
* @param streamId the originating RequestStream object
* @param buffer the data to send
* @exception java.io.IOException if an I/O error occurs
*/
byte[] sendNetPacket(int streamId, byte buffer[])
throws IOException {
byte[] ret = super.sendNetPacket(streamId, buffer);
getOut().flush();
return ret;
}
/**
* Close the named pipe and virtual sockets and release any resources.
*/
void close() throws IOException {
try {
// Close virtual sockets
super.close();
getOut().close();
setOut(null);
getIn().close();
setIn(null);
if (pipe != null) {
pipe.close();
}
} finally {
pipe = null;
}
}
/**
* Force close the socket causing any pending reads/writes to fail.
*
*
*
* @author Brian Heineman
* @author Mike Hutchinson
* @version $Id: ClobImpl.java,v 1.36.2.3 2009/12/30 08:45:34 ickzon Exp $
*/
public class ClobImpl implements Clob {
/**
* 0 length BlobBuffer class. Each character is stored in 2
* sequential bytes using UTF-16LE encoding.
* getSubstring, position and the
* set methods refer to 16 bit characters only. The presence
* of supplementary characters will cause the wrong characters to be
* accessed.
* String as initial value for empty
* Clobs.
*/
private static final String EMPTY_CLOB = "";
/** The underlying BlobBuffer. */
private final BlobBuffer blobBuffer;
/**
* Constructs a new empty Clob instance.
*
* @param connection a reference to the parent connection object
*/
ClobImpl(ConnectionJDBC2 connection) {
this(connection, EMPTY_CLOB);
}
/**
* Constructs a new initialized Clob instance.
*
* @param connection a reference to the parent connection object
* @param str the String object to encapsulate
*/
ClobImpl(ConnectionJDBC2 connection, String str) {
if (str == null) {
throw new IllegalArgumentException("str cannot be null");
}
blobBuffer = new BlobBuffer(connection.getBufferDir(), connection.getLobBuffer());
try {
byte[] data = str.getBytes("UTF-16LE");
blobBuffer.setBuffer(data, false);
} catch (UnsupportedEncodingException e) {
// This should never happen!
throw new IllegalStateException("UTF-16LE encoding is not supported.");
}
}
/**
* Obtain this object's backing BlobBuffer object.
*
* @return the underlying BlobBuffer
*/
BlobBuffer getBlobBuffer() {
return this.blobBuffer;
}
//
// ---- java.sql.Blob interface methods from here ----
//
public InputStream getAsciiStream() throws SQLException {
return blobBuffer.getBinaryStream(true);
}
public Reader getCharacterStream() throws SQLException {
try {
return new BufferedReader(new InputStreamReader(
blobBuffer.getBinaryStream(false), "UTF-16LE"));
} catch (UnsupportedEncodingException e) {
// This should never happen!
throw new IllegalStateException(
"UTF-16LE encoding is not supported.");
}
}
public String getSubString(long pos, int length) throws SQLException {
if (length == 0) {
return EMPTY_CLOB;
}
try {
byte data[] = blobBuffer.getBytes((pos - 1) * 2 + 1, length * 2);
return new String(data, "UTF-16LE");
} catch (IOException e) {
throw new SQLException(Messages.get("error.generic.ioerror",
e.getMessage()),
"HY000");
}
}
public long length() throws SQLException {
return blobBuffer.getLength() / 2;
}
public long position(String searchStr, long start) throws SQLException {
if (searchStr == null) {
throw new SQLException(
Messages.get("error.clob.searchnull"), "HY009");
}
try {
byte[] pattern = searchStr.getBytes("UTF-16LE");
int pos = blobBuffer.position(pattern, (start - 1) * 2 + 1);
return (pos < 0) ? pos : (pos - 1) / 2 + 1;
} catch (UnsupportedEncodingException e) {
// This should never happen!
throw new IllegalStateException(
"UTF-16LE encoding is not supported.");
}
}
public long position(Clob searchStr, long start) throws SQLException {
if (searchStr == null) {
throw new SQLException(
Messages.get("error.clob.searchnull"), "HY009");
}
BlobBuffer bbuf = ((ClobImpl) searchStr).getBlobBuffer();
byte[] pattern = bbuf.getBytes(1, (int) bbuf.getLength());
int pos = blobBuffer.position(pattern, (start - 1) * 2 + 1);
return (pos < 0) ? pos : (pos - 1) / 2 + 1;
}
public OutputStream setAsciiStream(final long pos) throws SQLException {
return blobBuffer.setBinaryStream((pos - 1) * 2 + 1, true);
}
public Writer setCharacterStream(final long pos) throws SQLException {
try {
return new BufferedWriter(new OutputStreamWriter(
blobBuffer.setBinaryStream((pos - 1) * 2 + 1, false),
"UTF-16LE"));
} catch (UnsupportedEncodingException e) {
// Should never happen
throw new IllegalStateException("UTF-16LE encoding is not supported.");
}
}
public int setString(long pos, String str) throws SQLException {
if (str == null) {
throw new SQLException(
Messages.get("error.clob.strnull"), "HY009");
}
return setString(pos, str, 0, str.length());
}
public int setString(long pos, String str, int offset, int len)
throws SQLException {
if (offset < 0 || offset > str.length()) {
throw new SQLException(Messages.get(
"error.blobclob.badoffset"), "HY090");
}
if (len < 0 || offset + len > str.length()) {
throw new SQLException(
Messages.get("error.blobclob.badlen"), "HY090");
}
try {
byte[] data = str.substring(offset, offset + len)
.getBytes("UTF-16LE");
// No need to force BlobBuffer to copy the bytes as this is a local
// buffer and cannot be corrupted by the user.
return blobBuffer.setBytes(
(pos - 1) * 2 + 1, data, 0, data.length, false);
} catch (UnsupportedEncodingException e) {
// This should never happen!
throw new IllegalStateException(
"UTF-16LE encoding is not supported.");
}
}
public void truncate(long len) throws SQLException {
blobBuffer.truncate(len * 2);
}
/////// JDBC4 demarcation, do NOT put any JDBC3 code below this line ///////
public void free() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
public Reader getCharacterStream(long pos, long length) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/MSCursorResultSet.java 0000644 0001750 0001750 00000131560 11316672660 027341 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Types;
import java.sql.ResultSet;
/**
* This class extends the JtdsResultSet to support scrollable and or
* updateable cursors on Microsoft servers.
*
*
*
* @author Alin Sinpalean
* @author Mike Hutchinson
* @version $Id: MSCursorResultSet.java,v 1.59 2007/07/11 20:02:45 bheineman Exp $
*/
public class MSCursorResultSet extends JtdsResultSet {
/*
* Constants
*/
private static final Integer FETCH_FIRST = new Integer(1);
private static final Integer FETCH_NEXT = new Integer(2);
private static final Integer FETCH_PREVIOUS = new Integer(4);
private static final Integer FETCH_LAST = new Integer(8);
private static final Integer FETCH_ABSOLUTE = new Integer(16);
private static final Integer FETCH_RELATIVE = new Integer(32);
private static final Integer FETCH_REPEAT = new Integer(128);
private static final Integer FETCH_INFO = new Integer(256);
private static final int CURSOR_TYPE_KEYSET = 0x01;
private static final int CURSOR_TYPE_DYNAMIC = 0x02;
private static final int CURSOR_TYPE_FORWARD = 0x04;
private static final int CURSOR_TYPE_STATIC = 0x08;
private static final int CURSOR_TYPE_FASTFORWARDONLY = 0x10;
private static final int CURSOR_TYPE_PARAMETERIZED = 0x1000;
private static final int CURSOR_TYPE_AUTO_FETCH = 0x2000;
private static final int CURSOR_CONCUR_READ_ONLY = 1;
private static final int CURSOR_CONCUR_SCROLL_LOCKS = 2;
private static final int CURSOR_CONCUR_OPTIMISTIC = 4;
private static final int CURSOR_CONCUR_OPTIMISTIC_VALUES = 8;
private static final Integer CURSOR_OP_INSERT = new Integer(4);
private static final Integer CURSOR_OP_UPDATE = new Integer(33);
private static final Integer CURSOR_OP_DELETE = new Integer(34);
/**
* The row is dirty and needs to be reloaded (internal state).
*/
private static final Integer SQL_ROW_DIRTY = new Integer(0);
/**
* The row is valid.
*/
private static final Integer SQL_ROW_SUCCESS = new Integer(1);
/**
* The row has been deleted.
*/
private static final Integer SQL_ROW_DELETED = new Integer(2);
/*
* Instance variables.
*/
/** Set when moveToInsertRow() was called. */
private boolean onInsertRow;
/** The "insert row". */
private ParamInfo[] insertRow;
/** The "update row". */
private ParamInfo[] updateRow;
/** The row cache used instead {@link #currentRow}. */
private Object[][] rowCache;
/** Actual position of the cursor. */
private int cursorPos;
/** The cursor is being built asynchronously. */
private boolean asyncCursor;
//
// Fixed sp_XXX parameters
//
/** Cursor handle parameter. */
private final ParamInfo PARAM_CURSOR_HANDLE = new ParamInfo(Types.INTEGER, null, ParamInfo.INPUT);
/** sp_cursorfetch fetchtype parameter. */
private final ParamInfo PARAM_FETCHTYPE = new ParamInfo(Types.INTEGER, null, ParamInfo.INPUT);
/** sp_cursorfetch rownum IN parameter (for actual fetches). */
private final ParamInfo PARAM_ROWNUM_IN = new ParamInfo(Types.INTEGER, null, ParamInfo.INPUT);
/** sp_cursorfetch numrows IN parameter (for actual fetches). */
private final ParamInfo PARAM_NUMROWS_IN = new ParamInfo(Types.INTEGER, null, ParamInfo.INPUT);
/** sp_cursorfetch rownum OUT parameter (for FETCH_INFO). */
private final ParamInfo PARAM_ROWNUM_OUT = new ParamInfo(Types.INTEGER, null, ParamInfo.OUTPUT);
/** sp_cursorfetch numrows OUT parameter (for FETCH_INFO). */
private final ParamInfo PARAM_NUMROWS_OUT = new ParamInfo(Types.INTEGER, null, ParamInfo.OUTPUT);
/** sp_cursor optype parameter. */
private final ParamInfo PARAM_OPTYPE = new ParamInfo(Types.INTEGER, null, ParamInfo.INPUT);
/** sp_cursor rownum parameter. */
private final ParamInfo PARAM_ROWNUM = new ParamInfo(Types.INTEGER, new Integer(1), ParamInfo.INPUT);
/** sp_cursor table parameter. */
private final ParamInfo PARAM_TABLE = new ParamInfo(Types.VARCHAR, "", ParamInfo.UNICODE);
/**
* Construct a cursor result set using Microsoft sp_cursorcreate etc.
*
* @param statement The parent statement object or null.
* @param resultSetType one of FORWARD_ONLY, SCROLL_INSENSITIVE, SCROLL_SENSITIVE.
* @param concurrency One of CONCUR_READ_ONLY, CONCUR_UPDATE.
* @throws SQLException
*/
MSCursorResultSet(JtdsStatement statement,
String sql,
String procName,
ParamInfo[] procedureParams,
int resultSetType,
int concurrency)
throws SQLException {
super(statement, resultSetType, concurrency, null);
PARAM_NUMROWS_IN.value = new Integer(fetchSize);
rowCache = new Object[fetchSize][];
cursorCreate(sql, procName, procedureParams);
if (asyncCursor) {
// Obtain a provisional row count for the result set
cursorFetch(FETCH_REPEAT, 0);
}
}
/**
* Set the specified column's data value.
*
* @param colIndex index of the column
* @param value new column value
* @return the value, possibly converted to an internal type
*/
protected Object setColValue(int colIndex, int jdbcType, Object value, int length)
throws SQLException {
value = super.setColValue(colIndex, jdbcType, value, length);
if (!onInsertRow && getCurrentRow() == null) {
throw new SQLException(Messages.get("error.resultset.norow"), "24000");
}
colIndex--;
ParamInfo pi;
ColInfo ci = columns[colIndex];
if (onInsertRow) {
pi = insertRow[colIndex];
} else {
if (updateRow == null) {
updateRow = new ParamInfo[columnCount];
}
pi = updateRow[colIndex];
}
if (pi == null) {
pi = new ParamInfo(-1, TdsData.isUnicode(ci));
pi.name = '@'+ci.realName;
pi.collation = ci.collation;
pi.charsetInfo = ci.charsetInfo;
if (onInsertRow) {
insertRow[colIndex] = pi;
} else {
updateRow[colIndex] = pi;
}
}
if (value == null) {
pi.value = null;
pi.length = 0;
pi.jdbcType = ci.jdbcType;
pi.isSet = true;
if (pi.jdbcType == Types.NUMERIC || pi.jdbcType == Types.DECIMAL) {
pi.scale = TdsData.DEFAULT_SCALE;
} else {
pi.scale = 0;
}
} else {
pi.value = value;
pi.length = length;
pi.isSet = true;
pi.jdbcType = jdbcType;
pi.isUnicode = "ntext".equals(ci.sqlType)
|| "nchar".equals(ci.sqlType)
|| "nvarchar".equals(ci.sqlType);
if (pi.value instanceof BigDecimal) {
pi.scale = ((BigDecimal)pi.value).scale();
} else {
pi.scale = 0;
}
}
return value;
}
/**
* Get the specified column's data item.
*
* @param index the column index in the row
* @return the column value as an Object
* @throws SQLException if the index is out of bounds or there is no
* current row
*/
protected Object getColumn(int index) throws SQLException {
checkOpen();
if (index < 1 || index > columnCount) {
throw new SQLException(Messages.get("error.resultset.colindex",
Integer.toString(index)),
"07009");
}
Object[] currentRow;
if (onInsertRow || (currentRow = getCurrentRow()) == null) {
throw new SQLException(
Messages.get("error.resultset.norow"), "24000");
}
if (SQL_ROW_DIRTY.equals(currentRow[columns.length - 1])) {
cursorFetch(FETCH_REPEAT, 0);
currentRow = getCurrentRow();
}
Object data = currentRow[index - 1];
wasNull = data == null;
return data;
}
/**
* Translates a JDBC result set type into SQL Server native @scrollOpt value
* for use with stored procedures such as sp_cursoropen, sp_cursorprepare
* or sp_cursorprepexec.
*
* @param resultSetType JDBC result set type (one of the
* ResultSet.TYPE_XXX
* values)
* @param resultSetConcurrency JDBC result set concurrency (one of the
* ResultSet.CONCUR_XXX
* values)
* @return a value for the @scrollOpt parameter
*/
static int getCursorScrollOpt(int resultSetType,
int resultSetConcurrency,
boolean parameterized) {
int scrollOpt;
switch (resultSetType) {
case TYPE_SCROLL_INSENSITIVE:
scrollOpt = CURSOR_TYPE_STATIC;
break;
case TYPE_SCROLL_SENSITIVE:
scrollOpt = CURSOR_TYPE_KEYSET;
break;
case TYPE_SCROLL_SENSITIVE + 1:
scrollOpt = CURSOR_TYPE_DYNAMIC;
break;
case TYPE_FORWARD_ONLY:
default:
scrollOpt = (resultSetConcurrency == CONCUR_READ_ONLY)
? (CURSOR_TYPE_FASTFORWARDONLY | CURSOR_TYPE_AUTO_FETCH)
: CURSOR_TYPE_FORWARD;
break;
}
// If using sp_cursoropen need to set a flag on scrollOpt.
// The 0x1000 tells the server that there is a parameter
// definition and user parameters present. If this flag is
// not set the driver will ignore the additional parameters.
if (parameterized) {
scrollOpt |= CURSOR_TYPE_PARAMETERIZED;
}
return scrollOpt;
}
/**
* Translates a JDBC result set concurrency into SQL Server native @ccOpt
* value for use with stored procedures such as sp_cursoropen,
* sp_cursorprepare or sp_cursorprepexec.
*
* @param resultSetConcurrency JDBC result set concurrency (one of the
* ResultSet.CONCUR_XXX
* values)
* @return a value for the @scrollOpt parameter
*/
static int getCursorConcurrencyOpt(int resultSetConcurrency) {
switch (resultSetConcurrency) {
case CONCUR_UPDATABLE:
return CURSOR_CONCUR_OPTIMISTIC;
case CONCUR_UPDATABLE + 1:
return CURSOR_CONCUR_SCROLL_LOCKS;
case CONCUR_UPDATABLE + 2:
return CURSOR_CONCUR_OPTIMISTIC_VALUES;
case CONCUR_READ_ONLY:
default:
return CURSOR_CONCUR_READ_ONLY;
}
}
/**
* Create a new Cursor result set using the internal sp_cursoropen procedure.
*
* @param sql The SQL SELECT statement.
* @param procName Optional procedure name for cursors based on a stored procedure.
* @param parameters Optional stored procedure parameters.
* @throws SQLException
*/
private void cursorCreate(String sql,
String procName,
ParamInfo[] parameters)
throws SQLException {
TdsCore tds = statement.getTds();
int prepareSql = statement.connection.getPrepareSql();
Integer prepStmtHandle = null;
//
// If this cursor is going to be a named forward only cursor
// force the concurrency to be updateable.
// TODO: Cursor is updateable unless user appends FOR READ to the select
// but we would need to parse the SQL to discover this.
//
if (cursorName != null
&& resultSetType == ResultSet.TYPE_FORWARD_ONLY
&& concurrency == ResultSet.CONCUR_READ_ONLY) {
concurrency = ResultSet.CONCUR_UPDATABLE;
}
//
// Simplify future tests for parameters
//
if (parameters != null && parameters.length == 0) {
parameters = null;
}
//
// SQL 6.5 does not support stored procs (with params) in the sp_cursor call
// will need to substitute any parameter values into the SQL.
//
if (tds.getTdsVersion() == Driver.TDS42) {
prepareSql = TdsCore.UNPREPARED;
if (parameters != null) {
procName = null;
}
}
//
// If we are running in unprepare mode and there are parameters
// substitute these into the SQL statement now.
//
if (parameters != null && prepareSql == TdsCore.UNPREPARED) {
sql = Support.substituteParameters(sql, parameters, statement.connection);
parameters = null;
}
//
// For most prepare modes we need to substitute parameter
// names for the ? markers.
//
if (parameters != null) {
if (procName == null || !procName.startsWith("#jtds")) {
sql = Support.substituteParamMarkers(sql, parameters);
}
}
//
// There are generally three situations in which procName is not null:
// 1. Running in prepareSQL=1 and contains a temp proc name e.g. #jtds00001
// in which case we need to generate an SQL statement exec #jtds...
// 2. Running in prepareSQL=4 and contains an existing statement handle.
// 3. CallableStatement in which case the SQL string has a valid exec
// statement and we can ignore procName.
//
if (procName != null) {
if (procName.startsWith("#jtds")) {
StringBuffer buf = new StringBuffer(procName.length() + 16
+ (parameters != null ? parameters.length * 5 : 0));
buf.append("EXEC ").append(procName).append(' ');
for (int i = 0; parameters != null && i < parameters.length; i++) {
if (i != 0) {
buf.append(',');
}
if (parameters[i].name != null) {
buf.append(parameters[i].name);
} else {
buf.append("@P").append(i);
}
}
sql = buf.toString();
} else if (TdsCore.isPreparedProcedureName(procName)) {
//
// Prepared Statement Handle
// At present procName is set to the value obtained by
// the connection.prepareSQL() call in JtdsPreparedStatement.
// This handle was obtained using sp_cursorprepare not sp_prepare
// so it's ok to use here.
//
try {
prepStmtHandle = new Integer(procName);
} catch (NumberFormatException e) {
throw new IllegalStateException(
"Invalid prepared statement handle: " +
procName);
}
}
}
//
// Select the correct type of Server side cursor to
// match the scroll and concurrency options.
//
int scrollOpt = getCursorScrollOpt(resultSetType, concurrency,
parameters != null);
int ccOpt = getCursorConcurrencyOpt(concurrency);
//
// Create parameter objects
//
// Setup scroll options parameter
//
ParamInfo pScrollOpt = new ParamInfo(Types.INTEGER, new Integer(scrollOpt), ParamInfo.OUTPUT);
//
// Setup concurrency options parameter
//
ParamInfo pConCurOpt = new ParamInfo(Types.INTEGER, new Integer(ccOpt), ParamInfo.OUTPUT);
//
// Setup number of rows parameter
//
ParamInfo pRowCount = new ParamInfo(Types.INTEGER, new Integer(fetchSize), ParamInfo.OUTPUT);
//
// Setup cursor handle parameter
//
ParamInfo pCursor = new ParamInfo(Types.INTEGER, null, ParamInfo.OUTPUT);
//
// Setup statement handle param
//
ParamInfo pStmtHand = null;
if (prepareSql == TdsCore.PREPARE) {
pStmtHand = new ParamInfo(Types.INTEGER, prepStmtHandle, ParamInfo.OUTPUT);
}
//
// Setup parameter definitions parameter
//
ParamInfo pParamDef = null;
if (parameters != null ) {
// Parameter declarations
for (int i = 0; i < parameters.length; i++) {
TdsData.getNativeType(statement.connection, parameters[i]);
}
pParamDef = new ParamInfo(Types.LONGVARCHAR,
Support.getParameterDefinitions(parameters),
ParamInfo.UNICODE);
}
//
// Setup SQL statement parameter
//
ParamInfo pSQL = new ParamInfo(Types.LONGVARCHAR, sql, ParamInfo.UNICODE);
//
// OK now open the Cursor
//
if (prepareSql == TdsCore.PREPARE && prepStmtHandle != null) {
// Use sp_cursorexecute approach
procName = "sp_cursorexecute";
if (parameters == null) {
parameters = new ParamInfo[5];
} else {
ParamInfo[] params = new ParamInfo[5 + parameters.length];
System.arraycopy(parameters, 0, params, 5, parameters.length);
parameters = params;
}
// Setup statement handle param
pStmtHand.isOutput = false;
pStmtHand.value = prepStmtHandle;
parameters[0] = pStmtHand;
// Setup cursor handle param
parameters[1] = pCursor;
// Setup scroll options (mask off parameter flag)
pScrollOpt.value = new Integer(scrollOpt & ~CURSOR_TYPE_PARAMETERIZED);
} else {
// Use sp_cursoropen approach
procName = "sp_cursoropen";
if (parameters == null) {
parameters = new ParamInfo[5];
} else {
ParamInfo[] params = new ParamInfo[6 + parameters.length];
System.arraycopy(parameters, 0, params, 6, parameters.length);
parameters = params;
parameters[5] = pParamDef;
}
// Setup cursor handle param
parameters[0] = pCursor;
// Setup statement param
parameters[1] = pSQL;
}
// Setup scroll options
parameters[2] = pScrollOpt;
// Setup concurrency options
parameters[3] = pConCurOpt;
// Setup numRows parameter
parameters[4] = pRowCount;
tds.executeSQL(null, procName, parameters, false,
statement.getQueryTimeout(), statement.getMaxRows(),
statement.getMaxFieldSize(), true);
// Load column meta data and any eventual rows (fast forward cursors)
processOutput(tds, true);
if ((scrollOpt & CURSOR_TYPE_AUTO_FETCH) != 0) {
// If autofetching, the cursor position is on the first row
cursorPos = 1;
}
// Check the return value
Integer retVal = tds.getReturnStatus();
if ((retVal == null) || (retVal.intValue() != 0 && retVal.intValue() != 2)) {
throw new SQLException(Messages.get("error.resultset.openfail"), "24000");
}
// Cursor is being built asynchronously so rowsInResult is not set
asyncCursor = (retVal.intValue() == 2);
//
// Retrieve values of output parameters
//
PARAM_CURSOR_HANDLE.value = pCursor.getOutValue();
int actualScroll = ((Integer) pScrollOpt.getOutValue()).intValue();
int actualCc = ((Integer) pConCurOpt.getOutValue()).intValue();
rowsInResult = ((Integer) pRowCount.getOutValue()).intValue();
//
// Set the cursor name if required allowing positioned updates.
// We need to do this here as any downgrade warnings will be wiped
// out by the executeSQL call.
//
if (cursorName != null) {
ParamInfo params[] = new ParamInfo[3];
params[0] = PARAM_CURSOR_HANDLE;
PARAM_OPTYPE.value = new Integer(2);
params[1] = PARAM_OPTYPE;
params[2] = new ParamInfo(Types.VARCHAR, cursorName, ParamInfo.UNICODE);
tds.executeSQL(null, "sp_cursoroption", params, true, 0, -1, -1, true);
tds.clearResponseQueue();
if (tds.getReturnStatus().intValue() != 0) {
statement.getMessages().addException(
new SQLException(Messages.get("error.resultset.openfail"), "24000"));
}
statement.getMessages().checkErrors();
}
//
// Check for downgrade of scroll or concurrency options
//
if ((actualScroll != (scrollOpt & 0xFFF)) || (actualCc != ccOpt)) {
boolean downgradeWarning = false;
if (actualScroll != scrollOpt) {
int resultSetType;
switch (actualScroll) {
case CURSOR_TYPE_FORWARD:
case CURSOR_TYPE_FASTFORWARDONLY:
resultSetType = TYPE_FORWARD_ONLY;
break;
case CURSOR_TYPE_STATIC:
resultSetType = TYPE_SCROLL_INSENSITIVE;
break;
case CURSOR_TYPE_KEYSET:
resultSetType = TYPE_SCROLL_SENSITIVE;
break;
case CURSOR_TYPE_DYNAMIC:
resultSetType = TYPE_SCROLL_SENSITIVE + 1;
break;
default:
resultSetType = this.resultSetType;
statement.getMessages().addWarning(new SQLWarning(
Messages.get("warning.cursortype", Integer.toString(actualScroll)),
"01000"));
}
downgradeWarning = resultSetType < this.resultSetType;
this.resultSetType = resultSetType;
}
if (actualCc != ccOpt) {
int concurrency;
switch (actualCc) {
case CURSOR_CONCUR_READ_ONLY:
concurrency = CONCUR_READ_ONLY;
break;
case CURSOR_CONCUR_OPTIMISTIC:
concurrency = CONCUR_UPDATABLE;
break;
case CURSOR_CONCUR_SCROLL_LOCKS:
concurrency = CONCUR_UPDATABLE + 1;
break;
case CURSOR_CONCUR_OPTIMISTIC_VALUES:
concurrency = CONCUR_UPDATABLE + 2;
break;
default:
concurrency = this.concurrency;
statement.getMessages().addWarning(new SQLWarning(
Messages.get("warning.concurrtype", Integer.toString(actualCc)),
"01000"));
}
downgradeWarning = concurrency < this.concurrency;
this.concurrency = concurrency;
}
if (downgradeWarning) {
// SAfe This warning goes to the Statement, not the ResultSet
statement.addWarning(new SQLWarning(
Messages.get( "warning.cursordowngraded",
resultSetType + "/" + concurrency),
"01000"));
}
}
}
/**
* Fetch the next result row from a cursor using the internal sp_cursorfetch procedure.
*
* @param fetchType The type of fetch eg FETCH_ABSOLUTE.
* @param rowNum The row number to fetch.
* @return boolean true if a result set row is returned.
* @throws SQLException
*/
private boolean cursorFetch(Integer fetchType, int rowNum)
throws SQLException {
TdsCore tds = statement.getTds();
statement.clearWarnings();
if (fetchType != FETCH_ABSOLUTE && fetchType != FETCH_RELATIVE) {
rowNum = 1;
}
ParamInfo[] param = new ParamInfo[4];
// Setup cursor handle param
param[0] = PARAM_CURSOR_HANDLE;
// Setup fetchtype param
PARAM_FETCHTYPE.value = fetchType;
param[1] = PARAM_FETCHTYPE;
// Setup rownum
PARAM_ROWNUM_IN.value = new Integer(rowNum);
param[2] = PARAM_ROWNUM_IN;
// Setup numRows parameter
if (((Integer) PARAM_NUMROWS_IN.value).intValue() != fetchSize) {
// If the fetch size changed, update the parameter and cache size
PARAM_NUMROWS_IN.value = new Integer(fetchSize);
rowCache = new Object[fetchSize][];
}
param[3] = PARAM_NUMROWS_IN;
synchronized (tds) {
// No meta data, no timeout (we're not sending it yet), no row
// limit, don't send yet
tds.executeSQL(null, "sp_cursorfetch", param, true, 0, 0,
statement.getMaxFieldSize(), false);
// Setup fetchtype param
PARAM_FETCHTYPE.value = FETCH_INFO;
param[1] = PARAM_FETCHTYPE;
// Setup rownum
PARAM_ROWNUM_OUT.clearOutValue();
param[2] = PARAM_ROWNUM_OUT;
// Setup numRows parameter
PARAM_NUMROWS_OUT.clearOutValue();
param[3] = PARAM_NUMROWS_OUT;
// No meta data, use the statement timeout, leave max rows as it is
// (no limit), leave max field size as it is, send now
tds.executeSQL(null, "sp_cursorfetch", param, true,
statement.getQueryTimeout(), -1, -1, true);
}
// Load rows
processOutput(tds, false);
cursorPos = ((Integer) PARAM_ROWNUM_OUT.getOutValue()).intValue();
if (fetchType != FETCH_REPEAT) {
// Do not change ResultSet position when refreshing
pos = cursorPos;
}
rowsInResult = ((Integer) PARAM_NUMROWS_OUT.getOutValue()).intValue();
if (rowsInResult < 0) {
// -1 = Dynamic cursor number of rows cannot be known.
// -n = Async cursor = rows loaded so far
rowsInResult = 0 - rowsInResult;
}
return getCurrentRow() != null;
}
/**
* Support general cursor operations such as delete, update etc.
*
* @param opType the type of operation to perform
* @param row the row number to update
* @throws SQLException
*/
private void cursor(Integer opType , ParamInfo[] row) throws SQLException {
TdsCore tds = statement.getTds();
statement.clearWarnings();
ParamInfo param[];
if (opType == CURSOR_OP_DELETE) {
// 3 parameters for delete
param = new ParamInfo[3];
} else {
if (row == null) {
throw new SQLException(Messages.get("error.resultset.update"), "24000");
}
// 4 parameters plus one for each column for insert/update
param = new ParamInfo[4 + columnCount];
}
// Setup cursor handle param
param[0] = PARAM_CURSOR_HANDLE;
// Setup optype param
PARAM_OPTYPE.value = opType;
param[1] = PARAM_OPTYPE;
// Setup rownum
PARAM_ROWNUM.value = new Integer(pos - cursorPos + 1);
param[2] = PARAM_ROWNUM;
// If row is not null, we're dealing with an insert/update
if (row != null) {
// Setup table
param[3] = PARAM_TABLE;
int colCnt = columnCount;
// Current column; we will only update/insert columns for which
// values were specified
int crtCol = 4;
// Name of the table to insert default values into (if necessary)
String tableName = null;
for (int i = 0; i < colCnt; i++) {
ParamInfo pi = row[i];
ColInfo col = columns[i];
if (pi != null && pi.isSet) {
if (!col.isWriteable) {
// Column is read-only but was updated
throw new SQLException(Messages.get("error.resultset.insert",
Integer.toString(i + 1), col.realName), "24000");
}
param[crtCol++] = pi;
}
if (tableName == null && col.tableName != null) {
if (col.catalog != null || col.schema != null) {
tableName = (col.catalog != null ? col.catalog : "")
+ '.' + (col.schema != null ? col.schema : "")
+ '.' + col.tableName;
} else {
tableName = col.tableName;
}
}
}
if (crtCol == 4) {
if (opType == CURSOR_OP_INSERT) {
// Insert default values for all columns.
// There seem to be two forms of sp_cursor: one with
// parameter names and values and one w/o names and with
// expressions (this is where 'default' comes in).
param[crtCol] = new ParamInfo(Types.VARCHAR,
"insert " + tableName + " default values",
ParamInfo.UNICODE);
crtCol++;
} else {
// No column to update so bail out!
return;
}
}
// If the count is different (i.e. there were read-only
// columns) reallocate the parameters into a shorter array
if (crtCol != colCnt + 4) {
ParamInfo[] newParam = new ParamInfo[crtCol];
System.arraycopy(param, 0, newParam, 0, crtCol);
param = newParam;
}
}
synchronized (tds) {
// With meta data (we're not expecting any ResultSets), no timeout
// (because we're not sending the request yet), don't alter max
// rows, don't alter max field size, don't send yet
tds.executeSQL(null, "sp_cursor", param, false, 0, -1, -1, false);
if (param.length != 4) {
param = new ParamInfo[4];
param[0] = PARAM_CURSOR_HANDLE;
}
// Setup fetchtype param
PARAM_FETCHTYPE.value = FETCH_INFO;
param[1] = PARAM_FETCHTYPE;
// Setup rownum
PARAM_ROWNUM_OUT.clearOutValue();
param[2] = PARAM_ROWNUM_OUT;
// Setup numRows parameter
PARAM_NUMROWS_OUT.clearOutValue();
param[3] = PARAM_NUMROWS_OUT;
// No meta data (no ResultSets expected), use statement timeout,
// don't alter max rows, don't alter max field size, send now
tds.executeSQL(null, "sp_cursorfetch", param, true,
statement.getQueryTimeout(), -1, -1, true);
}
// Consume the sp_cursor response
tds.consumeOneResponse();
statement.getMessages().checkErrors();
Integer retVal = tds.getReturnStatus();
if (retVal.intValue() != 0) {
throw new SQLException(Messages.get("error.resultset.cursorfail"),
"24000");
}
//
// Allow row values to be garbage collected
//
if (row != null) {
for (int i = 0; i < row.length; i++) {
if (row[i] != null) {
row[i].clearInValue();
}
}
}
// Consume the sp_cursorfetch response
tds.clearResponseQueue();
statement.getMessages().checkErrors();
cursorPos = ((Integer) PARAM_ROWNUM_OUT.getOutValue()).intValue();
rowsInResult = ((Integer) PARAM_NUMROWS_OUT.getOutValue()).intValue();
// Update row status
if (opType == CURSOR_OP_DELETE || opType == CURSOR_OP_UPDATE) {
Object[] currentRow = getCurrentRow();
if (currentRow == null) {
throw new SQLException(
Messages.get("error.resultset.updatefail"), "24000");
}
// No need to re-fetch the row, just mark it as deleted or dirty
currentRow[columns.length - 1] =
(opType == CURSOR_OP_DELETE) ? SQL_ROW_DELETED : SQL_ROW_DIRTY;
}
}
/**
* Close a server side cursor.
*
* @throws SQLException
*/
private void cursorClose() throws SQLException {
TdsCore tds = statement.getTds();
statement.clearWarnings();
// Consume rest of output and remember any exceptions
tds.clearResponseQueue();
SQLException ex = statement.getMessages().exceptions;
ParamInfo param[] = new ParamInfo[1];
// Setup cursor handle param
param[0] = PARAM_CURSOR_HANDLE;
tds.executeSQL(null, "sp_cursorclose", param, false,
statement.getQueryTimeout(), -1, -1, true);
tds.clearResponseQueue();
if (ex != null) {
ex.setNextException(statement.getMessages().exceptions);
throw ex;
} else {
statement.getMessages().checkErrors();
}
}
/**
* Processes the output of a cursor open or fetch operation. Fetches a
* batch of rows from the TdsCore, loading them into the row
* cache and optionally sets the column meta data (if called on cursor
* open). Consumes all the response and checks for server returned errors.
*
* @param tds the TdsCore instance
* @param setMeta whether column meta data needs to be loaded (cursor open)
* @throws SQLException if an error occurs or an error message is returned
* by the server
*/
private void processOutput(TdsCore tds, boolean setMeta) throws SQLException {
while (!tds.getMoreResults() && !tds.isEndOfResponse());
int i = 0;
if (tds.isResultSet()) {
// Set column meta data if necessary
if (setMeta) {
this.columns = copyInfo(tds.getColumns());
this.columnCount = getColumnCount(columns);
}
// With TDS 7 the data row (if any) is sent without any
// preceding resultset header.
// With TDS 8 there is a dummy result set header first
// then the data. This case also used if meta data not supressed.
if (tds.isRowData() || tds.getNextRow()) {
do {
rowCache[i++] = copyRow(tds.getRowData());
} while (tds.getNextRow());
}
} else if (setMeta) {
statement.getMessages().addException(new SQLException(
Messages.get("error.statement.noresult"), "24000"));
}
// Set the rest of the rows to null
for (; i < rowCache.length; ++i) {
rowCache[i] = null;
}
tds.clearResponseQueue();
statement.messages.checkErrors();
}
//
// -------------------- java.sql.ResultSet methods -------------------
//
public void afterLast() throws SQLException {
checkOpen();
checkScrollable();
if (pos != POS_AFTER_LAST) {
// SAfe Just fetch a very large absolute value
cursorFetch(FETCH_ABSOLUTE, Integer.MAX_VALUE);
}
}
public void beforeFirst() throws SQLException {
checkOpen();
checkScrollable();
if (pos != POS_BEFORE_FIRST) {
cursorFetch(FETCH_ABSOLUTE, 0);
}
}
public void cancelRowUpdates() throws SQLException {
checkOpen();
checkUpdateable();
if (onInsertRow) {
throw new SQLException(Messages.get("error.resultset.insrow"), "24000");
}
for (int i = 0; updateRow != null && i < updateRow.length; i++) {
if (updateRow[i] != null) {
updateRow[i].clearInValue();
}
}
}
public void close() throws SQLException {
if (!closed) {
try {
if (!statement.getConnection().isClosed()) {
cursorClose();
}
} finally {
closed = true;
statement = null;
}
}
}
public void deleteRow() throws SQLException {
checkOpen();
checkUpdateable();
if (getCurrentRow() == null) {
throw new SQLException(Messages.get("error.resultset.norow"), "24000");
}
if (onInsertRow) {
throw new SQLException(Messages.get("error.resultset.insrow"), "24000");
}
cursor(CURSOR_OP_DELETE, null);
}
public void insertRow() throws SQLException {
checkOpen();
checkUpdateable();
if (!onInsertRow) {
throw new SQLException(Messages.get("error.resultset.notinsrow"), "24000");
}
cursor(CURSOR_OP_INSERT, insertRow);
}
public void moveToCurrentRow() throws SQLException {
checkOpen();
checkUpdateable();
onInsertRow = false;
}
public void moveToInsertRow() throws SQLException {
checkOpen();
checkUpdateable();
if (insertRow == null) {
insertRow = new ParamInfo[columnCount];
}
onInsertRow = true;
}
public void refreshRow() throws SQLException {
checkOpen();
if (onInsertRow) {
throw new SQLException(Messages.get("error.resultset.insrow"), "24000");
}
cursorFetch(FETCH_REPEAT, 0);
}
public void updateRow() throws SQLException {
checkOpen();
checkUpdateable();
if (getCurrentRow() == null) {
throw new SQLException(Messages.get("error.resultset.norow"), "24000");
}
if (onInsertRow) {
throw new SQLException(Messages.get("error.resultset.insrow"), "24000");
}
if (updateRow != null) {
cursor(CURSOR_OP_UPDATE, updateRow);
}
}
public boolean first() throws SQLException {
checkOpen();
checkScrollable();
pos = 1;
if (getCurrentRow() == null) {
return cursorFetch(FETCH_FIRST, 0);
} else {
return true;
}
}
// FIXME Make the isXXX() methods work with forward-only cursors (rowsInResult == -1)
public boolean isLast() throws SQLException {
checkOpen();
return(pos == rowsInResult) && (rowsInResult != 0);
}
public boolean last() throws SQLException {
checkOpen();
checkScrollable();
pos = rowsInResult;
if (asyncCursor || getCurrentRow() == null) {
if (cursorFetch(FETCH_LAST, 0)) {
// Set pos to the last row, as the number of rows can change
pos = rowsInResult;
return true;
} else {
return false;
}
} else {
return true;
}
}
public boolean next() throws SQLException {
checkOpen();
++pos;
if (getCurrentRow() == null) {
return cursorFetch(FETCH_NEXT, 0);
} else {
return true;
}
}
public boolean previous() throws SQLException {
checkOpen();
checkScrollable();
// Don't bother if we're already before the first row
if (pos == POS_BEFORE_FIRST) {
return false;
}
// Save current ResultSet position
int initPos = pos;
// Decrement current position
--pos;
if (initPos == POS_AFTER_LAST || getCurrentRow() == null) {
boolean res = cursorFetch(FETCH_PREVIOUS, 0);
pos = (initPos == POS_AFTER_LAST) ? rowsInResult : (initPos - 1);
return res;
} else {
return true;
}
}
public boolean rowDeleted() throws SQLException {
checkOpen();
Object[] currentRow = getCurrentRow();
// If there is no current row, return false (the row was not deleted)
if (currentRow == null) {
return false;
}
// Reload if dirty
if (SQL_ROW_DIRTY.equals(currentRow[columns.length - 1])) {
cursorFetch(FETCH_REPEAT, 0);
currentRow = getCurrentRow();
}
return SQL_ROW_DELETED.equals(currentRow[columns.length - 1]);
}
public boolean rowInserted() throws SQLException {
checkOpen();
// No way to find out
return false;
}
public boolean rowUpdated() throws SQLException {
checkOpen();
// No way to find out
return false;
}
public boolean absolute(int row) throws SQLException {
checkOpen();
checkScrollable();
pos = (row >= 0) ? row : (rowsInResult - row + 1);
if (getCurrentRow() == null) {
boolean result = cursorFetch(FETCH_ABSOLUTE, row);
if (cursorPos == 1 && row + rowsInResult < 0) {
pos = 0;
result = false;
}
return result;
} else {
return true;
}
}
public boolean relative(int row) throws SQLException {
checkOpen();
checkScrollable();
pos = (pos == POS_AFTER_LAST) ? (rowsInResult + 1 + row) : (pos + row);
if (getCurrentRow() == null) {
if (pos < cursorPos) {
// If fetching backwards fetch the row and the rows before it,
// then restore pos
int savePos = pos;
boolean result = cursorFetch(FETCH_RELATIVE,
pos - cursorPos - fetchSize + 1);
if (result) {
pos = savePos;
} else {
pos = POS_BEFORE_FIRST;
}
return result;
} else {
return cursorFetch(FETCH_RELATIVE, pos - cursorPos);
}
} else {
return true;
}
}
protected Object[] getCurrentRow() {
if (pos < cursorPos || pos >= cursorPos + rowCache.length) {
return null;
}
return rowCache[pos - cursorPos];
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/JtdsResultSet.java 0000644 0001750 0001750 00000162174 11316672660 026535 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.net.MalformedURLException;
import java.sql.*;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.text.NumberFormat;
import java.io.UnsupportedEncodingException;
import java.io.InputStreamReader;
/**
* jTDS Implementation of the java.sql.ResultSet interface supporting forward read
* only result sets.
*
*
*
* @author Mike Hutchinson
* @version $Id: JtdsResultSet.java,v 1.46.2.5 2009/12/30 11:37:21 ickzon Exp $
*/
public class JtdsResultSet implements ResultSet {
/*
* Constants for backwards compatibility with JDK 1.3
*/
static final int HOLD_CURSORS_OVER_COMMIT = 1;
static final int CLOSE_CURSORS_AT_COMMIT = 2;
protected static final int POS_BEFORE_FIRST = 0;
protected static final int POS_AFTER_LAST = -1;
/** Initial size for row array. */
protected static final int INITIAL_ROW_COUNT = 1000;
/*
* Protected Instance variables.
*/
/** The current row number. */
protected int pos = POS_BEFORE_FIRST;
/** The number of rows in the result. */
protected int rowsInResult;
/** The fetch direction. */
protected int direction = FETCH_FORWARD;
/** The result set type. */
protected int resultSetType;
/** The result set concurrency. */
protected int concurrency;
/** Number of visible columns in row. */
protected int columnCount;
/** The array of column descriptors. */
protected ColInfo[] columns;
/** The current result set row. */
protected Object[] currentRow;
/** Cached row data for forward only result set. */
protected ArrayList rowData;
/** Index of current row in rowData. */
protected int rowPtr;
/** True if last column retrieved was null. */
protected boolean wasNull;
/** The parent statement. */
protected JtdsStatement statement;
/** True if this result set is closed. */
protected boolean closed;
/** True if the query has been cancelled by another thread. */
protected boolean cancelled;
/** The fetch direction. */
protected int fetchDirection = FETCH_FORWARD;
/** The fetch size (only applies to cursor ResultSets). */
protected int fetchSize;
/** The cursor name to be used for positioned updates. */
protected String cursorName;
/** Cache to optimize findColumn(String) lookups */
private HashMap columnMap;
/*
* Private instance variables.
*/
/** Used to format numeric values when scale is specified. */
private static NumberFormat f = NumberFormat.getInstance();
/**
* Construct a simple result set from a statement, metadata or generated keys.
*
* @param statement The parent statement object or null.
* @param resultSetType one of FORWARD_ONLY, SCROLL_INSENSITIVE, SCROLL_SENSITIVE.
* @param concurrency One of CONCUR_READ_ONLY, CONCUR_UPDATE.
* @param columns The array of column descriptors for the result set row.
* @throws SQLException
*/
JtdsResultSet(JtdsStatement statement,
int resultSetType,
int concurrency,
ColInfo[] columns)
throws SQLException {
if (statement == null) {
throw new IllegalArgumentException("Statement parameter must not be null");
}
this.statement = statement;
this.resultSetType = resultSetType;
this.concurrency = concurrency;
this.columns = columns;
this.fetchSize = statement.fetchSize;
this.fetchDirection = statement.fetchDirection;
this.cursorName = statement.cursorName;
if (columns != null) {
columnCount = getColumnCount(columns);
rowsInResult = (statement.getTds().isDataInResultSet()) ? 1 : 0;
}
}
/**
* Retrieve the column count excluding hidden columns
*
* @param columns The columns array
* @return The new column count as an int.
*/
protected static int getColumnCount(ColInfo[] columns) {
// MJH - Modified to cope with more than one hidden column
int i;
for (i = columns.length - 1; i >= 0 && columns[i].isHidden; i--);
return i + 1;
}
/**
* Retrieve the column descriptor array.
*
* @return The column descriptors as a ColInfo[].
*/
protected ColInfo[] getColumns() {
return this.columns;
}
/**
* Set the specified column's name.
*
* @param colIndex The index of the column in the row.
* @param name The new name.
*/
protected void setColName(int colIndex, String name) {
if (colIndex < 1 || colIndex > columns.length) {
throw new IllegalArgumentException("columnIndex "
+ colIndex + " invalid");
}
columns[colIndex - 1].realName = name;
}
/**
* Set the specified column's label.
*
* @param colIndex The index of the column in the row.
* @param name The new label.
*/
protected void setColLabel(int colIndex, String name) {
if (colIndex < 1 || colIndex > columns.length) {
throw new IllegalArgumentException("columnIndex "
+ colIndex + " invalid");
}
columns[colIndex - 1].name = name;
}
/**
* Set the specified column's JDBC type.
*
* @param colIndex The index of the column in the row.
* @param jdbcType The new type value.
*/
protected void setColType(int colIndex, int jdbcType) {
if (colIndex < 1 || colIndex > columns.length) {
throw new IllegalArgumentException("columnIndex "
+ colIndex + " invalid");
}
columns[colIndex - 1].jdbcType = jdbcType;
}
/**
* Set the specified column's data value.
*
* @param colIndex index of the column
* @param value new column value
* @param length the length of a stream parameter
* @return the value, possibly converted to an internal type
*/
protected Object setColValue(int colIndex, int jdbcType, Object value, int length)
throws SQLException {
checkOpen();
checkUpdateable();
if (colIndex < 1 || colIndex > columnCount) {
throw new SQLException(Messages.get("error.resultset.colindex",
Integer.toString(colIndex)),
"07009");
}
//
// Convert java date/time objects to internal DateTime objects
//
if (value instanceof java.sql.Timestamp) {
value = new DateTime((java.sql.Timestamp) value);
} else if (value instanceof java.sql.Date) {
value = new DateTime((java.sql.Date) value);
} else if (value instanceof java.sql.Time) {
value = new DateTime((java.sql.Time) value);
}
return value;
}
/**
* Set the current row's column count.
*
* @param columnCount The number of visible columns in the row.
*/
protected void setColumnCount(int columnCount) {
if (columnCount < 1 || columnCount > columns.length) {
throw new IllegalArgumentException("columnCount "
+ columnCount + " is invalid");
}
this.columnCount = columnCount;
}
/**
* Get the specified column's data item.
*
* @param index the column index in the row
* @return the column value as an Object
* @throws SQLException if the connection is closed;
* if index is less than 1;
* if index is greater that the number of columns;
* if there is no current row
*/
protected Object getColumn(int index) throws SQLException {
checkOpen();
if (index < 1 || index > columnCount) {
throw new SQLException(Messages.get("error.resultset.colindex",
Integer.toString(index)),
"07009");
}
if (currentRow == null) {
throw new SQLException(Messages.get("error.resultset.norow"), "24000");
}
Object data = currentRow[index - 1];
wasNull = data == null;
return data;
}
/**
* Check that this connection is still open.
*
* @throws SQLException if connection closed.
*/
protected void checkOpen() throws SQLException {
if (closed) {
throw new SQLException(Messages.get("error.generic.closed", "ResultSet"),
"HY010");
}
if (cancelled) {
throw new SQLException(Messages.get("error.generic.cancelled", "ResultSet"),
"HY010");
}
}
/**
* Check that this resultset is scrollable.
*
* @throws SQLException if connection closed.
*/
protected void checkScrollable() throws SQLException {
if (resultSetType == ResultSet.TYPE_FORWARD_ONLY) {
throw new SQLException(Messages.get("error.resultset.fwdonly"), "24000");
}
}
/**
* Check that this resultset is updateable.
*
* @throws SQLException if connection closed.
*/
protected void checkUpdateable() throws SQLException {
if (concurrency == ResultSet.CONCUR_READ_ONLY) {
throw new SQLException(Messages.get("error.resultset.readonly"), "24000");
}
}
/**
* Report that user tried to call a method which has not been implemented.
*
* @param method The method name to report in the error message.
* @throws SQLException
*/
protected static void notImplemented(String method) throws SQLException {
throw new SQLException(Messages.get("error.generic.notimp", method), "HYC00");
}
/**
* Create a new row containing empty data items.
*
* @return the new row as an Object array
*/
protected Object[] newRow() {
Object row[] = new Object[columns.length];
return row;
}
/**
* Copy an existing result set row.
*
* @param row the result set row to copy
* @return the new row as an Object array
*/
protected Object[] copyRow(Object[] row) {
Object copy[] = new Object[columns.length];
System.arraycopy(row, 0, copy, 0, row.length);
return copy;
}
/**
* Copy an existing result set column descriptor array.
*
* @param info The result set column descriptors to copy.
* @return The new descriptors as a ColInfo[].
*/
protected ColInfo[] copyInfo(ColInfo[] info) {
ColInfo copy[] = new ColInfo[info.length];
System.arraycopy(info, 0, copy, 0, info.length);
return copy;
}
/**
* Retrieve the current row data.
* @return The current row data as an Object[].
*/
protected Object[] getCurrentRow()
{
return this.currentRow;
}
/**
* Cache the remaining results to free up connection.
* @throws SQLException
*/
protected void cacheResultSetRows() throws SQLException {
if (rowData == null) {
rowData = new ArrayList(INITIAL_ROW_COUNT);
}
if (currentRow != null) {
// Need to create local copy of currentRow
// as this is currently a reference to the
// row defined in TdsCore
currentRow = copyRow(currentRow);
}
//
// Now load the remaining result set rows into memory
//
while (statement.getTds().getNextRow()) {
rowData.add(copyRow(statement.getTds().getRowData()));
}
// Allow statement to process output vars etc
statement.cacheResults();
}
/**
* Returns the {@link ConnectionJDBC2} object referenced by the
* {@link #statement} instance variable.
*
* @return {@link ConnectionJDBC2} object.
* @throws SQLException on error.
*/
private ConnectionJDBC2 getConnection() throws SQLException {
return (ConnectionJDBC2) statement.getConnection();
}
//
// -------------------- java.sql.ResultSet methods -------------------
//
public int getConcurrency() throws SQLException {
checkOpen();
return this.concurrency;
}
public int getFetchDirection() throws SQLException {
checkOpen();
return this.fetchDirection;
}
public int getFetchSize() throws SQLException {
checkOpen();
return fetchSize;
}
public int getRow() throws SQLException {
checkOpen();
return pos > 0 ? pos : 0;
}
public int getType() throws SQLException {
checkOpen();
return resultSetType;
}
public void afterLast() throws SQLException {
checkOpen();
checkScrollable();
}
public void beforeFirst() throws SQLException {
checkOpen();
checkScrollable();
}
public void cancelRowUpdates() throws SQLException {
checkOpen();
checkUpdateable();
}
public void clearWarnings() throws SQLException {
checkOpen();
statement.clearWarnings();
}
public void close() throws SQLException {
if (!closed) {
try {
if (!getConnection().isClosed()) {
// Skip to end of result set
// Could send cancel but this is safer as
// cancel could kill other statements in a batch.
while (next());
}
} finally {
closed = true;
statement = null;
}
}
}
public void deleteRow() throws SQLException {
checkOpen();
checkUpdateable();
}
public void insertRow() throws SQLException {
checkOpen();
checkUpdateable();
}
public void moveToCurrentRow() throws SQLException {
checkOpen();
checkUpdateable();
}
public void moveToInsertRow() throws SQLException {
checkOpen();
checkUpdateable();
}
public void refreshRow() throws SQLException {
checkOpen();
checkUpdateable();
}
public void updateRow() throws SQLException {
checkOpen();
checkUpdateable();
}
public boolean first() throws SQLException {
checkOpen();
checkScrollable();
return false;
}
public boolean isAfterLast() throws SQLException {
checkOpen();
return (pos == POS_AFTER_LAST) && (rowsInResult != 0);
}
public boolean isBeforeFirst() throws SQLException {
checkOpen();
return (pos == POS_BEFORE_FIRST) && (rowsInResult != 0);
}
public boolean isFirst() throws SQLException {
checkOpen();
return pos == 1;
}
public boolean isLast() throws SQLException {
checkOpen();
if (statement.getTds().isDataInResultSet()) {
rowsInResult = pos + 1; // Keep rowsInResult 1 ahead of pos
}
return (pos == rowsInResult) && (rowsInResult != 0);
}
public boolean last() throws SQLException {
checkOpen();
checkScrollable();
return false;
}
public boolean next() throws SQLException {
checkOpen();
if (pos == POS_AFTER_LAST) {
// Make sure nothing will happen after the end has been reached
return false;
}
if (rowData != null) {
// The rest of the result rows have been cached so
// return the next row from the buffer.
if (rowPtr < rowData.size()) {
currentRow = (Object[])rowData.get(rowPtr);
// This is a forward only result set so null out the buffer ref
// to allow for garbage collection (we can never access the row
// again once we have moved on).
rowData.set(rowPtr++, null);
pos++;
rowsInResult = pos;
} else {
pos = POS_AFTER_LAST;
currentRow = null;
}
} else {
// Need to read from server response
if (!statement.getTds().getNextRow()) {
statement.cacheResults();
pos = POS_AFTER_LAST;
currentRow = null;
} else {
currentRow = statement.getTds().getRowData();
pos++;
rowsInResult = pos;
}
}
// Check for server side errors
statement.getMessages().checkErrors();
return currentRow != null;
}
public boolean previous() throws SQLException {
checkOpen();
checkScrollable();
return false;
}
public boolean rowDeleted() throws SQLException {
checkOpen();
checkUpdateable();
return false;
}
public boolean rowInserted() throws SQLException {
checkOpen();
checkUpdateable();
return false;
}
public boolean rowUpdated() throws SQLException {
checkOpen();
checkUpdateable();
return false;
}
public boolean wasNull() throws SQLException {
checkOpen();
return wasNull;
}
public byte getByte(int columnIndex) throws SQLException {
return ((Integer) Support.convert(this, getColumn(columnIndex), java.sql.Types.TINYINT, null)).byteValue();
}
public short getShort(int columnIndex) throws SQLException {
return ((Integer) Support.convert(this, getColumn(columnIndex), java.sql.Types.SMALLINT, null)).shortValue();
}
public int getInt(int columnIndex) throws SQLException {
return ((Integer) Support.convert(this, getColumn(columnIndex), java.sql.Types.INTEGER, null)).intValue();
}
public long getLong(int columnIndex) throws SQLException {
return ((Long) Support.convert(this, getColumn(columnIndex), java.sql.Types.BIGINT, null)).longValue();
}
public float getFloat(int columnIndex) throws SQLException {
return ((Float) Support.convert(this, getColumn(columnIndex), java.sql.Types.REAL, null)).floatValue();
}
public double getDouble(int columnIndex) throws SQLException {
return ((Double) Support.convert(this, getColumn(columnIndex), java.sql.Types.DOUBLE, null)).doubleValue();
}
public void setFetchDirection(int direction) throws SQLException {
checkOpen();
switch (direction) {
case FETCH_UNKNOWN:
case FETCH_REVERSE:
if (this.resultSetType == ResultSet.TYPE_FORWARD_ONLY) {
throw new SQLException(Messages.get("error.resultset.fwdonly"), "24000");
}
// Fall through
case FETCH_FORWARD:
this.fetchDirection = direction;
break;
default:
throw new SQLException(
Messages.get("error.generic.badoption",
Integer.toString(direction),
"direction"),
"24000");
}
}
public void setFetchSize(int rows) throws SQLException {
checkOpen();
if (rows < 0 || (statement.getMaxRows() > 0 && rows > statement.getMaxRows())) {
throw new SQLException(
Messages.get("error.generic.badparam",
Integer.toString(rows),
"rows"),
"HY092");
}
if (rows == 0) {
rows = statement.getDefaultFetchSize();
}
this.fetchSize = rows;
}
public void updateNull(int columnIndex) throws SQLException {
setColValue(columnIndex, Types.NULL, null, 0);
}
public boolean absolute(int row) throws SQLException {
checkOpen();
checkScrollable();
return false;
}
public boolean getBoolean(int columnIndex) throws SQLException {
return ((Boolean) Support.convert(this, getColumn(columnIndex), JtdsStatement.BOOLEAN, null)).booleanValue();
}
public boolean relative(int row) throws SQLException {
checkOpen();
checkScrollable();
return false;
}
public byte[] getBytes(int columnIndex) throws SQLException {
checkOpen();
return (byte[]) Support.convert(this, getColumn(columnIndex), java.sql.Types.BINARY, getConnection().getCharset());
}
public void updateByte(int columnIndex, byte x) throws SQLException {
setColValue(columnIndex, Types.INTEGER, new Integer(x & 0xFF), 0);
}
public void updateDouble(int columnIndex, double x) throws SQLException {
setColValue(columnIndex, Types.DOUBLE, new Double(x), 0);
}
public void updateFloat(int columnIndex, float x) throws SQLException {
setColValue(columnIndex, Types.REAL, new Float(x), 0);
}
public void updateInt(int columnIndex, int x) throws SQLException {
setColValue(columnIndex, Types.INTEGER, new Integer(x), 0);
}
public void updateLong(int columnIndex, long x) throws SQLException {
setColValue(columnIndex, Types.BIGINT, new Long(x), 0);
}
public void updateShort(int columnIndex, short x) throws SQLException {
setColValue(columnIndex, Types.INTEGER, new Integer(x), 0);
}
public void updateBoolean(int columnIndex, boolean x) throws SQLException {
setColValue(columnIndex, Types.BIT, x ? Boolean.TRUE : Boolean.FALSE, 0);
}
public void updateBytes(int columnIndex, byte[] x) throws SQLException {
setColValue(columnIndex, Types.VARBINARY, x, (x != null)? x.length: 0);
}
public InputStream getAsciiStream(int columnIndex) throws SQLException {
Clob clob = getClob(columnIndex);
if (clob == null) {
return null;
}
return clob.getAsciiStream();
}
public InputStream getBinaryStream(int columnIndex) throws SQLException {
Blob blob = getBlob(columnIndex);
if (blob == null) {
return null;
}
return blob.getBinaryStream();
}
public InputStream getUnicodeStream(int columnIndex) throws SQLException {
ClobImpl clob = (ClobImpl) getClob(columnIndex);
if (clob == null) {
return null;
}
return clob.getBlobBuffer().getUnicodeStream();
}
public void updateAsciiStream(int columnIndex, InputStream inputStream, int length)
throws SQLException {
if (inputStream == null || length < 0) {
updateCharacterStream(columnIndex, null, 0);
} else {
try {
updateCharacterStream(columnIndex, new InputStreamReader(inputStream, "US-ASCII"), length);
} catch (UnsupportedEncodingException e) {
// Should never happen!
}
}
}
public void updateBinaryStream(int columnIndex, InputStream inputStream, int length)
throws SQLException {
if (inputStream == null || length < 0) {
updateBytes(columnIndex, null);
return;
}
setColValue(columnIndex, java.sql.Types.VARBINARY, inputStream, length);
}
public Reader getCharacterStream(int columnIndex) throws SQLException {
Clob clob = getClob(columnIndex);
if (clob == null) {
return null;
}
return clob.getCharacterStream();
}
public void updateCharacterStream(int columnIndex, Reader reader, int length)
throws SQLException {
if (reader == null || length < 0) {
updateString(columnIndex, null);
return;
}
setColValue(columnIndex, java.sql.Types.VARCHAR, reader, length);
}
public Object getObject(int columnIndex) throws SQLException {
Object value = getColumn(columnIndex);
// Don't return UniqueIdentifier objects as the user won't know how to
// handle them
if (value instanceof UniqueIdentifier) {
return value.toString();
}
// Don't return DateTime objects as the user won't know how to
// handle them
if (value instanceof DateTime) {
return ((DateTime) value).toObject();
}
// If the user requested String/byte[] instead of LOBs, do the conversion
if (!getConnection().getUseLOBs()) {
value = Support.convertLOB(value);
}
return value;
}
public void updateObject(int columnIndex, Object x) throws SQLException {
checkOpen();
int length = 0;
int jdbcType = Types.VARCHAR; // Use for NULL values
if (x != null) {
// Need to do some conversion and testing here
jdbcType = Support.getJdbcType(x);
if (x instanceof BigDecimal) {
int prec = getConnection().getMaxPrecision();
x = Support.normalizeBigDecimal((BigDecimal)x, prec);
} else if (x instanceof Blob) {
Blob blob = (Blob) x;
x = blob.getBinaryStream();
length = (int) blob.length();
} else if (x instanceof Clob) {
Clob clob = (Clob) x;
x = clob.getCharacterStream();
length = (int) clob.length();
} else if (x instanceof String) {
length = ((String)x).length();
} else if (x instanceof byte[]) {
length = ((byte[])x).length;
}
if (jdbcType == Types.JAVA_OBJECT) {
// Unsupported class of object
if (columnIndex < 1 || columnIndex > columnCount) {
throw new SQLException(Messages.get("error.resultset.colindex",
Integer.toString(columnIndex)),
"07009");
}
ColInfo ci = columns[columnIndex-1];
throw new SQLException(
Messages.get("error.convert.badtypes",
x.getClass().getName(),
Support.getJdbcTypeName(ci.jdbcType)), "22005");
}
}
setColValue(columnIndex, jdbcType, x, length);
}
public void updateObject(int columnIndex, Object x, int scale) throws SQLException {
checkOpen();
if (scale < 0 || scale > getConnection().getMaxPrecision()) {
throw new SQLException(Messages.get("error.generic.badscale"), "HY092");
}
if (x instanceof BigDecimal) {
updateObject(columnIndex, ((BigDecimal) x).setScale(scale, BigDecimal.ROUND_HALF_UP));
} else if (x instanceof Number) {
synchronized (f) {
f.setGroupingUsed(false);
f.setMaximumFractionDigits(scale);
updateObject(columnIndex, f.format(x));
}
} else {
updateObject(columnIndex, x);
}
}
public String getCursorName() throws SQLException {
checkOpen();
if (cursorName != null) {
return this.cursorName;
}
throw new SQLException(Messages.get("error.resultset.noposupdate"), "24000");
}
public String getString(int columnIndex) throws SQLException {
Object tmp = getColumn(columnIndex);
if (tmp instanceof String) {
return (String) tmp;
}
return (String) Support.convert(this, tmp, java.sql.Types.VARCHAR, getConnection().getCharset());
}
public void updateString(int columnIndex, String x) throws SQLException {
setColValue(columnIndex, Types.VARCHAR, x , (x != null)? x.length(): 0);
}
public byte getByte(String columnName) throws SQLException {
return getByte(findColumn(columnName));
}
public double getDouble(String columnName) throws SQLException {
return getDouble(findColumn(columnName));
}
public float getFloat(String columnName) throws SQLException {
return getFloat(findColumn(columnName));
}
public int findColumn(String columnName) throws SQLException {
checkOpen();
if (columnMap == null) {
columnMap = new HashMap(columnCount);
} else {
Object pos = columnMap.get(columnName);
if (pos != null) {
return ((Integer) pos).intValue();
}
}
// Rather than use toUpperCase()/toLowerCase(), which are costly,
// just do a sequential search. It's actually faster in most cases.
for (int i = 0; i < columnCount; i++) {
if (columns[i].name.equalsIgnoreCase(columnName)) {
columnMap.put(columnName, new Integer(i + 1));
return i + 1;
}
}
throw new SQLException(Messages.get("error.resultset.colname", columnName), "07009");
}
public int getInt(String columnName) throws SQLException {
return getInt(findColumn(columnName));
}
public long getLong(String columnName) throws SQLException {
return getLong(findColumn(columnName));
}
public short getShort(String columnName) throws SQLException {
return getShort(findColumn(columnName));
}
public void updateNull(String columnName) throws SQLException {
updateNull(findColumn(columnName));
}
public boolean getBoolean(String columnName) throws SQLException {
return getBoolean(findColumn(columnName));
}
public byte[] getBytes(String columnName) throws SQLException {
return getBytes(findColumn(columnName));
}
public void updateByte(String columnName, byte x) throws SQLException {
updateByte(findColumn(columnName), x);
}
public void updateDouble(String columnName, double x) throws SQLException {
updateDouble(findColumn(columnName), x);
}
public void updateFloat(String columnName, float x) throws SQLException {
updateFloat(findColumn(columnName), x);
}
public void updateInt(String columnName, int x) throws SQLException {
updateInt(findColumn(columnName), x);
}
public void updateLong(String columnName, long x) throws SQLException {
updateLong(findColumn(columnName), x);
}
public void updateShort(String columnName, short x) throws SQLException {
updateShort(findColumn(columnName), x);
}
public void updateBoolean(String columnName, boolean x) throws SQLException {
updateBoolean(findColumn(columnName), x);
}
public void updateBytes(String columnName, byte[] x) throws SQLException {
updateBytes(findColumn(columnName), x);
}
public BigDecimal getBigDecimal(int columnIndex) throws SQLException {
return (BigDecimal) Support.convert(this, getColumn(columnIndex), java.sql.Types.DECIMAL, null);
}
public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException {
BigDecimal result = (BigDecimal) Support.convert(this, getColumn(columnIndex), java.sql.Types.DECIMAL, null);
if (result == null) {
return null;
}
return result.setScale(scale, BigDecimal.ROUND_HALF_UP);
}
public void updateBigDecimal(int columnIndex, BigDecimal x)
throws SQLException {
checkOpen();
checkUpdateable();
if (x != null) {
int prec = getConnection().getMaxPrecision();
x = Support.normalizeBigDecimal(x, prec);
}
setColValue(columnIndex, Types.DECIMAL, x, 0);
}
public URL getURL(int columnIndex) throws SQLException {
String url = getString(columnIndex);
try {
return new java.net.URL(url);
} catch (MalformedURLException e) {
throw new SQLException(Messages.get("error.resultset.badurl", url), "22000");
}
}
public Array getArray(int columnIndex) throws SQLException {
checkOpen();
notImplemented("ResultSet.getArray()");
return null;
}
public void updateArray(int columnIndex, Array x) throws SQLException {
checkOpen();
checkUpdateable();
notImplemented("ResultSet.updateArray()");
}
public Blob getBlob(int columnIndex) throws SQLException {
return (Blob) Support.convert(this, getColumn(columnIndex), java.sql.Types.BLOB, null);
}
public void updateBlob(int columnIndex, Blob x) throws SQLException {
if (x == null) {
updateBinaryStream(columnIndex, null, 0);
} else {
updateBinaryStream(columnIndex, x.getBinaryStream(), (int) x.length());
}
}
public Clob getClob(int columnIndex) throws SQLException {
return (Clob) Support.convert(this, getColumn(columnIndex), java.sql.Types.CLOB, null);
}
public void updateClob(int columnIndex, Clob x) throws SQLException {
if (x == null) {
updateCharacterStream(columnIndex, null, 0);
} else {
updateCharacterStream(columnIndex, x.getCharacterStream(), (int) x.length());
}
}
public Date getDate(int columnIndex) throws SQLException {
return (java.sql.Date)Support.convert(this, getColumn(columnIndex), java.sql.Types.DATE, null);
}
public void updateDate(int columnIndex, Date x) throws SQLException {
setColValue(columnIndex, Types.DATE, x, 0);
}
public Ref getRef(int columnIndex) throws SQLException {
checkOpen();
notImplemented("ResultSet.getRef()");
return null;
}
public void updateRef(int columnIndex, Ref x) throws SQLException {
checkOpen();
checkUpdateable();
notImplemented("ResultSet.updateRef()");
}
public ResultSetMetaData getMetaData() throws SQLException {
checkOpen();
// If this is a DatabaseMetaData built result set, avoid getting an
// exception because the statement is closed and assume no LOBs
boolean useLOBs = this instanceof CachedResultSet && statement.closed
? false
: getConnection().getUseLOBs();
return new JtdsResultSetMetaData(this.columns, this.columnCount,
useLOBs);
}
public SQLWarning getWarnings() throws SQLException {
checkOpen();
return statement.getWarnings();
}
public Statement getStatement() throws SQLException {
checkOpen();
return this.statement;
}
public Time getTime(int columnIndex) throws SQLException {
return (java.sql.Time) Support.convert(this, getColumn(columnIndex), java.sql.Types.TIME, null);
}
public void updateTime(int columnIndex, Time x) throws SQLException {
setColValue(columnIndex, Types.TIME, x, 0);
}
public Timestamp getTimestamp(int columnIndex) throws SQLException {
return (Timestamp) Support.convert(this, getColumn(columnIndex), java.sql.Types.TIMESTAMP, null);
}
public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException {
setColValue(columnIndex, Types.TIMESTAMP, x, 0);
}
public InputStream getAsciiStream(String columnName) throws SQLException {
return getAsciiStream(findColumn(columnName));
}
public InputStream getBinaryStream(String columnName) throws SQLException {
return getBinaryStream(findColumn(columnName));
}
public InputStream getUnicodeStream(String columnName) throws SQLException {
return getUnicodeStream(findColumn(columnName));
}
public void updateAsciiStream(String columnName, InputStream x, int length)
throws SQLException {
updateAsciiStream(findColumn(columnName), x, length);
}
public void updateBinaryStream(String columnName, InputStream x, int length)
throws SQLException {
updateBinaryStream(findColumn(columnName), x, length);
}
public Reader getCharacterStream(String columnName) throws SQLException {
return getCharacterStream(findColumn(columnName));
}
public void updateCharacterStream(String columnName, Reader x, int length)
throws SQLException {
updateCharacterStream(findColumn(columnName), x, length);
}
public Object getObject(String columnName) throws SQLException {
return getObject(findColumn(columnName));
}
public void updateObject(String columnName, Object x) throws SQLException {
updateObject(findColumn(columnName), x);
}
public void updateObject(String columnName, Object x, int scale)
throws SQLException {
updateObject(findColumn(columnName), x, scale);
}
public Object getObject(int columnIndex, Map map) throws SQLException {
notImplemented("ResultSet.getObject(int, Map)");
return null;
}
public String getString(String columnName) throws SQLException {
return getString(findColumn(columnName));
}
public void updateString(String columnName, String x) throws SQLException {
updateString(findColumn(columnName), x);
}
public BigDecimal getBigDecimal(String columnName) throws SQLException {
return getBigDecimal(findColumn(columnName));
}
public BigDecimal getBigDecimal(String columnName, int scale)
throws SQLException {
return getBigDecimal(findColumn(columnName), scale);
}
public void updateBigDecimal(String columnName, BigDecimal x)
throws SQLException {
updateObject(findColumn(columnName), x);
}
public URL getURL(String columnName) throws SQLException {
return getURL(findColumn(columnName));
}
public Array getArray(String columnName) throws SQLException {
return getArray(findColumn(columnName));
}
public void updateArray(String columnName, Array x) throws SQLException {
updateArray(findColumn(columnName), x);
}
public Blob getBlob(String columnName) throws SQLException {
return getBlob(findColumn(columnName));
}
public void updateBlob(String columnName, Blob x) throws SQLException {
updateBlob(findColumn(columnName), x);
}
public Clob getClob(String columnName) throws SQLException {
return getClob(findColumn(columnName));
}
public void updateClob(String columnName, Clob x) throws SQLException {
updateClob(findColumn(columnName), x);
}
public Date getDate(String columnName) throws SQLException {
return getDate(findColumn(columnName));
}
public void updateDate(String columnName, Date x) throws SQLException {
updateDate(findColumn(columnName), x);
}
public Date getDate(int columnIndex, Calendar cal) throws SQLException {
java.sql.Date date = getDate(columnIndex);
if (date != null && cal != null) {
date = new java.sql.Date(Support.timeToZone(date, cal));
}
return date;
}
public Ref getRef(String columnName) throws SQLException {
return getRef(findColumn(columnName));
}
public void updateRef(String columnName, Ref x) throws SQLException {
updateRef(findColumn(columnName), x);
}
public Time getTime(String columnName) throws SQLException {
return getTime(findColumn(columnName));
}
public void updateTime(String columnName, Time x) throws SQLException {
updateTime(findColumn(columnName), x);
}
public Time getTime(int columnIndex, Calendar cal) throws SQLException {
checkOpen();
java.sql.Time time = getTime(columnIndex);
if (time != null && cal != null) {
return new Time(Support.timeToZone(time, cal));
}
return time;
}
public Timestamp getTimestamp(String columnName) throws SQLException {
return getTimestamp(findColumn(columnName));
}
public void updateTimestamp(String columnName, Timestamp x)
throws SQLException {
updateTimestamp(findColumn(columnName), x);
}
public Timestamp getTimestamp(int columnIndex, Calendar cal)
throws SQLException {
checkOpen();
Timestamp timestamp = getTimestamp(columnIndex);
if (timestamp != null && cal != null) {
timestamp = new Timestamp(Support.timeToZone(timestamp, cal));
}
return timestamp;
}
public Object getObject(String columnName, Map map) throws SQLException {
return getObject(findColumn(columnName), map);
}
public Date getDate(String columnName, Calendar cal) throws SQLException {
return getDate(findColumn(columnName), cal);
}
public Time getTime(String columnName, Calendar cal) throws SQLException {
return getTime(findColumn(columnName), cal);
}
public Timestamp getTimestamp(String columnName, Calendar cal)
throws SQLException {
return getTimestamp(findColumn(columnName), cal);
}
/////// JDBC4 demarcation, do NOT put any JDBC3 code below this line ///////
/* (non-Javadoc)
* @see java.sql.ResultSet#getHoldability()
*/
public int getHoldability() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#getNCharacterStream(int)
*/
public Reader getNCharacterStream(int columnIndex) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#getNCharacterStream(java.lang.String)
*/
public Reader getNCharacterStream(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#getNClob(int)
*/
public NClob getNClob(int columnIndex) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#getNClob(java.lang.String)
*/
public NClob getNClob(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#getNString(int)
*/
public String getNString(int columnIndex) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#getNString(java.lang.String)
*/
public String getNString(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#getRowId(int)
*/
public RowId getRowId(int columnIndex) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#getRowId(java.lang.String)
*/
public RowId getRowId(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#getSQLXML(int)
*/
public SQLXML getSQLXML(int columnIndex) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#getSQLXML(java.lang.String)
*/
public SQLXML getSQLXML(String columnLabel) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#isClosed()
*/
public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateAsciiStream(int, java.io.InputStream)
*/
public void updateAsciiStream(int columnIndex, InputStream x)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateAsciiStream(java.lang.String, java.io.InputStream)
*/
public void updateAsciiStream(String columnLabel, InputStream x)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateAsciiStream(int, java.io.InputStream, long)
*/
public void updateAsciiStream(int columnIndex, InputStream x, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateAsciiStream(java.lang.String, java.io.InputStream, long)
*/
public void updateAsciiStream(String columnLabel, InputStream x, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateBinaryStream(int, java.io.InputStream)
*/
public void updateBinaryStream(int columnIndex, InputStream x)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateBinaryStream(java.lang.String, java.io.InputStream)
*/
public void updateBinaryStream(String columnLabel, InputStream x)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateBinaryStream(int, java.io.InputStream, long)
*/
public void updateBinaryStream(int columnIndex, InputStream x, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateBinaryStream(java.lang.String, java.io.InputStream, long)
*/
public void updateBinaryStream(String columnLabel, InputStream x,
long length) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateBlob(int, java.io.InputStream)
*/
public void updateBlob(int columnIndex, InputStream inputStream)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateBlob(java.lang.String, java.io.InputStream)
*/
public void updateBlob(String columnLabel, InputStream inputStream)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateBlob(int, java.io.InputStream, long)
*/
public void updateBlob(int columnIndex, InputStream inputStream, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateBlob(java.lang.String, java.io.InputStream, long)
*/
public void updateBlob(String columnLabel, InputStream inputStream,
long length) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateCharacterStream(int, java.io.Reader)
*/
public void updateCharacterStream(int columnIndex, Reader x)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateCharacterStream(java.lang.String, java.io.Reader)
*/
public void updateCharacterStream(String columnLabel, Reader reader)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateCharacterStream(int, java.io.Reader, long)
*/
public void updateCharacterStream(int columnIndex, Reader x, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateCharacterStream(java.lang.String, java.io.Reader, long)
*/
public void updateCharacterStream(String columnLabel, Reader reader,
long length) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateClob(int, java.io.Reader)
*/
public void updateClob(int columnIndex, Reader reader) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateClob(java.lang.String, java.io.Reader)
*/
public void updateClob(String columnLabel, Reader reader)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateClob(int, java.io.Reader, long)
*/
public void updateClob(int columnIndex, Reader reader, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateClob(java.lang.String, java.io.Reader, long)
*/
public void updateClob(String columnLabel, Reader reader, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateNCharacterStream(int, java.io.Reader)
*/
public void updateNCharacterStream(int columnIndex, Reader x)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateNCharacterStream(java.lang.String, java.io.Reader)
*/
public void updateNCharacterStream(String columnLabel, Reader reader)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateNCharacterStream(int, java.io.Reader, long)
*/
public void updateNCharacterStream(int columnIndex, Reader x, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateNCharacterStream(java.lang.String, java.io.Reader, long)
*/
public void updateNCharacterStream(String columnLabel, Reader reader,
long length) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateNClob(int, java.sql.NClob)
*/
public void updateNClob(int columnIndex, NClob clob) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateNClob(java.lang.String, java.sql.NClob)
*/
public void updateNClob(String columnLabel, NClob clob) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateNClob(int, java.io.Reader)
*/
public void updateNClob(int columnIndex, Reader reader) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateNClob(java.lang.String, java.io.Reader)
*/
public void updateNClob(String columnLabel, Reader reader)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateNClob(int, java.io.Reader, long)
*/
public void updateNClob(int columnIndex, Reader reader, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateNClob(java.lang.String, java.io.Reader, long)
*/
public void updateNClob(String columnLabel, Reader reader, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateNString(int, java.lang.String)
*/
public void updateNString(int columnIndex, String string)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateNString(java.lang.String, java.lang.String)
*/
public void updateNString(String columnLabel, String string)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateRowId(int, java.sql.RowId)
*/
public void updateRowId(int columnIndex, RowId x) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateRowId(java.lang.String, java.sql.RowId)
*/
public void updateRowId(String columnLabel, RowId x) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateSQLXML(int, java.sql.SQLXML)
*/
public void updateSQLXML(int columnIndex, SQLXML xmlObject)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.ResultSet#updateSQLXML(java.lang.String, java.sql.SQLXML)
*/
public void updateSQLXML(String columnLabel, SQLXML xmlObject)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#isWrapperFor(java.lang.Class)
*/
public boolean isWrapperFor(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#unwrap(java.lang.Class)
*/
public Object unwrap(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/DateTime.java 0000644 0001750 0001750 00000043603 11316672660 025445 0 ustar martin martin //jTDS JDBC Driver for Microsoft SQL Server and Sybase
//Copyright (C) 2004 The jTDS Project
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.sql.Date;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.GregorianCalendar;
/**
* Encapsulates Sybase date/time values and provides conversions to and from
* Java classes.
*
* @author Mike Hutchinson
* @version $Id: DateTime.java,v 1.4.2.2 2009/08/20 19:44:04 ickzon Exp $
*/
public class DateTime {
/** Per thread instance of Calendar used for conversions. */
private static ThreadLocal calendar = new ThreadLocal() {
protected synchronized Object initialValue() {
return new GregorianCalendar();
}
};
/** Indicates date value not used. */
static final int DATE_NOT_USED = Integer.MIN_VALUE;
/** Indicates time value not used. */
static final int TIME_NOT_USED = Integer.MIN_VALUE;
/** The date component of the server datetime value. */
private int date;
/** The time component of the server datetime value. */
private int time;
/** Unpacked year value. */
private short year;
/** Unpacked month value. */
private short month;
/** Unpacked day value. */
private short day;
/** Unpacked hour value. */
private short hour;
/** Unpacked minute value. */
private short minute;
/** Unpacked second value. */
private short second;
/** Unpacked millisecond value. */
private short millis;
/** Indicates server datetime values have been unpacked. */
private boolean unpacked;
/** Cached value of the datetime as a String. */
private String stringValue;
/** Cached value of the datetime as a java.sql.Timestamp. */
private Timestamp tsValue;
/** Cached value of the datetime as a java.sql.Date. */
private Date dateValue;
/** Cached value of the datetime as a java.sql.Time. */
private Time timeValue;
/**
* Constructs a DateTime object from the two integer components of a
* datetime.
*
* @param date server date field
* @param time server time field
*/
DateTime(int date, int time) {
this.date = date;
this.time = time;
}
/**
* Constructs a DateTime object from the two short components of a
* smalldatetime.
*
* @param date server date field
* @param time server time field
*/
DateTime(short date, short time) {
this.date = (int) date & 0xFFFF;
this.time = (int) time * 60 * 300;
}
/**
* Constructs a DateTime object from a java.sql.Timestamp.
*
* @param ts Timestamp object representing the datetime
* @throws SQLException if the date is out of range
*/
DateTime(Timestamp ts) throws SQLException {
tsValue = ts;
GregorianCalendar cal = (GregorianCalendar)calendar.get();
cal.setTime((java.util.Date) ts);
if (cal.get(Calendar.ERA) != GregorianCalendar.AD) {
cal.set(Calendar.ERA, GregorianCalendar.AD);
throw new SQLException(Messages.get("error.datetime.range.era"), "22007");
}
if (!Driver.JDBC3) {
// Not Running under 1.4 so need to add milliseconds
cal.set(Calendar.MILLISECOND,
((Timestamp)ts).getNanos() / 1000000);
}
this.year = (short)cal.get(Calendar.YEAR);
this.month = (short)(cal.get(Calendar.MONTH) + 1);
this.day = (short)cal.get(Calendar.DAY_OF_MONTH);
this.hour = (short)cal.get(Calendar.HOUR_OF_DAY);
this.minute = (short)cal.get(Calendar.MINUTE);
this.second = (short)cal.get(Calendar.SECOND);
this.millis = (short)cal.get(Calendar.MILLISECOND);
packDate();
packTime();
unpacked = true;
}
/**
* Constructs a DateTime object from a java.sql.Time.
*
* @param t Time object representing the datetime
* @throws SQLException if the time (date) is out of range
*/
DateTime(Time t) throws SQLException {
timeValue = t;
GregorianCalendar cal = (GregorianCalendar)calendar.get();
cal.setTime((java.util.Date) t);
if (cal.get(Calendar.ERA) != GregorianCalendar.AD) {
cal.set(Calendar.ERA, GregorianCalendar.AD);
throw new SQLException(Messages.get("error.datetime.range.era"), "22007");
}
this.date = DATE_NOT_USED;
this.year = 1900;
this.month = 1;
this.day = 1;
this.hour = (short)cal.get(Calendar.HOUR_OF_DAY);
this.minute = (short)cal.get(Calendar.MINUTE);
this.second = (short)cal.get(Calendar.SECOND);
this.millis = (short)cal.get(Calendar.MILLISECOND);
packTime();
this.year = 1970;
this.month = 1;
this.day = 1;
unpacked = true;
}
/**
* Constructs a DateTime object from a java.sql.Date.
*
* @param d Date object representing the datetime
* @throws SQLException if the Date is out of range
*/
DateTime(Date d) throws SQLException {
dateValue = d;
GregorianCalendar cal = (GregorianCalendar)calendar.get();
cal.setTime((java.util.Date) d);
if (cal.get(Calendar.ERA) != GregorianCalendar.AD) {
cal.set(Calendar.ERA, GregorianCalendar.AD);
throw new SQLException(Messages.get("error.datetime.range.era"), "22007");
}
this.year = (short)cal.get(Calendar.YEAR);
this.month = (short)(cal.get(Calendar.MONTH) + 1);
this.day = (short)cal.get(Calendar.DAY_OF_MONTH);
this.hour = 0;
this.minute = 0;
this.second = 0;
this.millis = 0;
packDate();
this.time = TIME_NOT_USED;
unpacked = true;
}
/**
* Retrieves the date component of a datetime value.
*
* @return the datetime date component as an int
*/
int getDate() {
return (date == DATE_NOT_USED) ? 0 : date;
}
/**
* Retrieves the time component of a datetime value.
*
* @return the datetime time component as an int
*/
int getTime() {
return (time == TIME_NOT_USED) ? 0 : time;
}
/**
* Converts a Julian datetime from the Sybase epoch of 1900-01-01 to the
* equivalent unpacked year/month/day etc.
*
* Algorithm from Fliegel, H F and van Flandern, T C (1968).
* Communications of the ACM, Vol 11, No 10 (October, 1968).
*
* SUBROUTINE GDATE (JD, YEAR,MONTH,DAY)
* C
* C---COMPUTES THE GREGORIAN CALENDAR DATE (YEAR,MONTH,DAY)
* C GIVEN THE JULIAN DATE (JD).
* C
* INTEGER JD,YEAR,MONTH,DAY,I,J,K
* C
* L= JD+68569
* N= 4*L/146097
* L= L-(146097*N+3)/4
* I= 4000*(L+1)/1461001
* L= L-1461*I/4+31
* J= 80*L/2447
* K= L-2447*J/80
* L= J/11
* J= J+2-12*L
* I= 100*(N-49)+I+L
* C
* YEAR= I
* MONTH= J
* DAY= K
* C
* RETURN
* END
*
*/
private void unpackDateTime() {
if (this.date == DATE_NOT_USED) {
this.year = 1970;
this.month = 1;
this.day = 1;
} else {
if (date == 0) {
// Optimize common case of 1900-01-01 which is used as
// the default date for datetimes where only the time is set.
this.year = 1900;
this.month = 1;
this.day = 1;
} else {
int l = date + 68569 + 2415021;
int n = 4 * l / 146097;
l = l - (146097 * n + 3) / 4;
int i = 4000 * (l + 1) / 1461001;
l = l - 1461 * i / 4 + 31;
int j = 80 * l / 2447;
int k = l - 2447 * j / 80;
l = j / 11;
j = j + 2 - 12 * l;
i = 100 * (n - 49) + i + l;
this.year = (short)i;
this.month = (short)j;
this.day = (short)k;
}
}
if (time == TIME_NOT_USED) {
this.hour = 0;
this.minute = 0;
this.second = 0;
} else {
int hours = time / 1080000;
time = time - hours * 1080000;
int minutes = time / 18000;
time = time - (minutes * 18000);
int seconds = time / 300;
time = time - seconds * 300;
time = (int) Math.round(time * 1000 / 300f);
this.hour = (short)hours;
this.minute = (short)minutes;
this.second = (short)seconds;
this.millis = (short)time;
}
unpacked = true;
}
/**
* Converts a calendar date into days since 1900 (Sybase epoch).
*
* INTEGER FUNCTION JD (YEAR,MONTH,DAY)
* C
* C---COMPUTES THE JULIAN DATE (JD) GIVEN A GREGORIAN CALENDAR
* C DATE (YEAR,MONTH,DAY).
* C
* INTEGER YEAR,MONTH,DAY,I,J,K
* C
* I= YEAR
* J= MONTH
* K= DAY
* C
* JD= K-32075+1461*(I+4800+(J-14)/12)/4+367*(J-2-(J-14)/12*12)
* 2 /12-3*((I+4900+(J-14)/12)/100)/4
* C
* RETURN
* END
*
*
* @throws java.sql.SQLException if the date is outside the accepted range, 1753-9999
*/
public void packDate() throws SQLException {
if (year < 1753 || year > 9999) {
throw new SQLException(Messages.get("error.datetime.range"), "22003");
}
date = day - 32075 + 1461 * (year + 4800 + (month - 14) / 12) / 4
+ 367 * (month - 2 - (month - 14) / 12 * 12) / 12
- 3 * ((year + 4900 + (month -14) / 12) / 100) / 4 - 2415021;
}
/**
* Converts separate time components into a datetime time value.
*/
public void packTime() {
time = hour * 1080000;
time += minute * 18000;
time += second * 300;
time += Math.round(millis * 300f / 1000);
if (time > 25919999) {
// Time field has overflowed need to increment days
// Sybase does not allow invalid time component
time = 0;
hour = 0;
minute = 0;
second = 0;
millis = 0;
if (date != DATE_NOT_USED) {
GregorianCalendar cal = (GregorianCalendar)calendar.get();
cal.set(Calendar.YEAR, this.year);
cal.set(Calendar.MONTH, this.month - 1);
cal.set(Calendar.DAY_OF_MONTH, this.day);
cal.add(Calendar.DATE, 1);
year = (short)cal.get(Calendar.YEAR);
month = (short)(cal.get(Calendar.MONTH) + 1);
day = (short)cal.get(Calendar.DAY_OF_MONTH);
date++;
}
}
}
/**
* Retrieves the current datetime value as a Timestamp.
*
* @return the current datetime value as a java.sql.Timestamp
*/
public Timestamp toTimestamp() {
if (tsValue == null) {
if (!unpacked) {
unpackDateTime();
}
GregorianCalendar cal = (GregorianCalendar)calendar.get();
cal.set(Calendar.YEAR, this.year);
cal.set(Calendar.MONTH, this.month - 1);
cal.set(Calendar.DAY_OF_MONTH, this.day);
cal.set(Calendar.HOUR_OF_DAY, this.hour);
cal.set(Calendar.MINUTE, this.minute);
cal.set(Calendar.SECOND, this.second);
cal.set(Calendar.MILLISECOND, this.millis);
tsValue = new Timestamp(cal.getTime().getTime());
}
return tsValue;
}
/**
* Retrieves the current datetime value as a Date.
*
* @return the current datetime value as a java.sql.Date
*/
public Date toDate() {
if (dateValue == null) {
if (!unpacked) {
unpackDateTime();
}
GregorianCalendar cal = (GregorianCalendar)calendar.get();
cal.set(Calendar.YEAR, this.year);
cal.set(Calendar.MONTH, this.month - 1);
cal.set(Calendar.DAY_OF_MONTH, this.day);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
dateValue = new Date(cal.getTime().getTime());
}
return dateValue;
}
/**
* Retrieves the current datetime value as a Time.
*
* @return the current datetime value as a java.sql.Time
*/
public Time toTime() {
if (timeValue == null) {
if (!unpacked) {
unpackDateTime();
}
GregorianCalendar cal = (GregorianCalendar)calendar.get();
cal.set(Calendar.YEAR, 1970);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, this.hour);
cal.set(Calendar.MINUTE, this.minute);
cal.set(Calendar.SECOND, this.second);
cal.set(Calendar.MILLISECOND, this.millis);
timeValue = new Time(cal.getTime().getTime());
}
return timeValue;
}
/**
* Retrieves the current datetime value as a Time, Date or Timestamp.
*
* @return the current datetime value as an java.lang.Object
*/
public Object toObject() {
if (date == DATE_NOT_USED) {
return toTime();
}
if (time == TIME_NOT_USED) {
return toDate();
}
return toTimestamp();
}
/**
* Retrieves the current datetime value as a String.
*
* @return the current datetime value as a String
*/
public String toString() {
if (stringValue == null) {
if (!unpacked) {
unpackDateTime();
}
//
// Make local copies to avoid corrupting unpacked
// components.
//
int day = this.day;
int month = this.month;
int year = this.year;
int millis = this.millis;
int second = this.second;
int minute = this.minute;
int hour = this.hour;
char buf[] = new char[23];
int p = 0;
if (date != DATE_NOT_USED) {
p = 10;
buf[--p] = (char)('0' + day % 10);
day /= 10;
buf[--p] = (char)('0' + day % 10);
buf[--p] = '-';
buf[--p] = (char)('0' + month % 10);
month /= 10;
buf[--p] = (char)('0' + month % 10);
buf[--p] = '-';
buf[--p] = (char)('0' + year % 10);
year /= 10;
buf[--p] = (char)('0' + year % 10);
year /= 10;
buf[--p] = (char)('0' + year % 10);
year /= 10;
buf[--p] = (char)('0' + year % 10);
p += 10;
if (time != TIME_NOT_USED) {
buf[p++] = ' ';
}
}
if (time != TIME_NOT_USED) {
p += 12;
buf[--p] = (char)('0' + millis % 10);
millis /= 10;
buf[--p] = (char)('0' + millis % 10);
millis /= 10;
buf[--p] = (char)('0' + millis % 10);
buf[--p] = '.';
buf[--p] = (char)('0' + second % 10);
second /= 10;
buf[--p] = (char)('0' + second % 10);
buf[--p] = ':';
buf[--p] = (char)('0' + minute % 10);
minute /= 10;
buf[--p] = (char)('0' + minute % 10);
buf[--p] = ':';
buf[--p] = (char)('0' + hour % 10);
hour /= 10;
buf[--p] = (char)('0' + hour % 10);
p += 12;
if (buf[p-1] == '0') {
p--;
}
if (buf[p-1] == '0') {
p--;
}
}
stringValue = String.valueOf(buf, 0, p);
}
return stringValue;
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/ConnectionJDBC2.java 0000644 0001750 0001750 00000262571 11316672660 026564 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.lang.ref.WeakReference;
import java.sql.*;
import java.net.UnknownHostException;
import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.HashSet;
import java.util.Random;
import net.sourceforge.jtds.jdbc.cache.*;
import net.sourceforge.jtds.util.*;
/**
* jTDS implementation of the java.sql.Connection interface.
*
*
*
* @author Mike Hutchinson
* @author Alin Sinpalean
* @version $Id: ConnectionJDBC2.java,v 1.119.2.12 2009/12/30 11:37:21 ickzon Exp $
*/
public class ConnectionJDBC2 implements java.sql.Connection {
/**
* SQL query to determine the server charset on Sybase.
*/
private static final String SYBASE_SERVER_CHARSET_QUERY
= "select name from master.dbo.syscharsets where id ="
+ " (select value from master.dbo.sysconfigures where config=131)";
/**
* SQL query to determine the server charset on MS SQL Server 6.5.
*/
private static final String SQL_SERVER_65_CHARSET_QUERY
= "select name from master.dbo.syscharsets where id ="
+ " (select csid from master.dbo.syscharsets, master.dbo.sysconfigures"
+ " where config=1123 and id = value)";
/** Sybase initial connection string. */
private static final String SYBASE_INITIAL_SQL = "SET TRANSACTION ISOLATION LEVEL 1\r\n" +
"SET CHAINED OFF\r\n" +
"SET QUOTED_IDENTIFIER ON\r\n"+
"SET TEXTSIZE 2147483647";
/**
* SQL Server initial connection string. Also contains a
* SELECT @@MAX_PRECISION query to retrieve
* the maximum precision for DECIMAL/NUMERIC data. */
private static final String SQL_SERVER_INITIAL_SQL = "SELECT @@MAX_PRECISION\r\n" +
"SET TRANSACTION ISOLATION LEVEL READ COMMITTED\r\n" +
"SET IMPLICIT_TRANSACTIONS OFF\r\n" +
"SET QUOTED_IDENTIFIER ON\r\n"+
"SET TEXTSIZE 2147483647";
/**
* SQL Server custom transaction isolation level.
*/
public static final int TRANSACTION_SNAPSHOT = 4096;
/*
* Conection attributes
*/
/** The orginal connection URL. */
private final String url;
/** The server host name. */
private String serverName;
/** The server port number. */
private int portNumber;
/** The make of SQL Server (sybase/microsoft). */
private int serverType;
/** The SQL Server instance. */
private String instanceName;
/** The requested database name. */
private String databaseName;
/** The current database name. */
private String currentDatabase;
/** The Windows Domain name. */
private String domainName;
/** The database user ID. */
private String user;
/** The user password. */
private String password;
/** The server character set. */
private String serverCharset;
/** The application name. */
private String appName;
/** The program name. */
private String progName;
/** Workstation ID. */
private String wsid;
/** The server message language. */
private String language;
/** The client MAC Address. */
private String macAddress;
/** The server protocol version. */
private int tdsVersion;
/** The network TCP/IP socket. */
private final SharedSocket socket;
/** The cored TDS protocol object. */
private final TdsCore baseTds;
/** The initial network packet size. */
private int netPacketSize = TdsCore.MIN_PKT_SIZE;
/** User requested packet size. */
private int packetSize;
/** SQL Server 2000 collation. */
private byte collation[];
/** True if user specifies an explicit charset. */
private boolean charsetSpecified;
/** The database product name eg SQL SERVER. */
private String databaseProductName;
/** The product version eg 11.92. */
private String databaseProductVersion;
/** The major version number eg 11. */
private int databaseMajorVersion;
/** The minor version number eg 92. */
private int databaseMinorVersion;
/** True if this connection is closed. */
private boolean closed;
/** True if this connection is read only. */
private boolean readOnly;
/** List of statements associated with this connection. */
private final ArrayList statements = new ArrayList();
/** Default transaction isolation level. */
private int transactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED;
/** Default auto commit state. */
private boolean autoCommit = true;
/** Diagnostc messages for this connection. */
private final SQLDiagnostic messages;
/** Connection's current rowcount limit. */
private int rowCount;
/** Connection's current maximum field size limit. */
private int textSize;
/** Maximum decimal precision. */
private int maxPrecision = TdsData.DEFAULT_PRECISION_38; // Sybase default
/** Stored procedure unique ID number. */
private int spSequenceNo = 1;
/** Cursor unique ID number. */
private int cursorSequenceNo = 1;
/** Procedures in this transaction. */
private final ArrayList procInTran = new ArrayList();
/** Java charset for encoding. */
private CharsetInfo charsetInfo;
/** Method for preparing SQL used in Prepared Statements. */
private int prepareSql;
/** The amount of LOB data to buffer in memory. */
private long lobBuffer;
/** The maximum number of statements to keep open. */
private int maxStatements;
/** Statement cache.*/
private StatementCache statementCache;
/** Send parameters as unicode. */
private boolean useUnicode = true;
/** Use named pipe IPC instead of TCP/IP sockets. */
private boolean namedPipe;
/** Only return the last update count. */
private boolean lastUpdateCount;
/** TCP_NODELAY */
private boolean tcpNoDelay = true;
/** Login timeout value in seconds or 0. */
private int loginTimeout;
/** Sybase capability mask.*/
private int sybaseInfo;
/** True if running distributed transaction. */
private boolean xaTransaction;
/** Current emulated XA State eg start/end/prepare etc. */
private int xaState;
/** Current XA Transaction ID. */
private Object xid;
/** True if driver should emulate distributed transactions. */
private boolean xaEmulation = true;
/** Mutual exclusion lock to control access to connection. */
private final Semaphore mutex = new Semaphore(1);
/** Socket timeout value in seconds or 0. */
private int socketTimeout;
/** True to enable socket keep alive. */
private boolean socketKeepAlive;
/** The process ID to report to a server when connecting. */
private static Integer processId;
/** SSL setting. */
private String ssl;
/** The maximum size of a batch. */
private int batchSize;
/** Use metadata cache for prepared statements. */
private boolean useMetadataCache;
/** Use fast forward cursors for forward only result sets. */
private boolean useCursors;
/** The directory to buffer data to */
private File bufferDir;
/** The global buffer memory limit for all connections (in kilobytes). */
private int bufferMaxMemory;
/** The minimum number of packets per statement to buffer to memory. */
private int bufferMinPackets;
/** Map large types (IMAGE and TEXT/NTEXT) to LOBs by default. */
private boolean useLOBs;
/** A cached TdsCore instance to reuse on new statements. */
private TdsCore cachedTds;
/** The local address to bind to when connecting to a database via TCP/IP. */
private String bindAddress;
/** Force use of jCIFS library on Windows when connecting via named pipes. */
private boolean useJCIFS;
/** When doing NTLM authentication, send NTLMv2 response rather than regular response */
private boolean useNTLMv2 = false;
/** the number of currently open connections */
private static int connections;
/**
* Default constructor.
*
* Used for testing.
*/
private ConnectionJDBC2() {
connections++;
url = null;
socket = null;
baseTds = null;
messages = null;
}
/**
* Create a new database connection.
*
* @param url The connection URL starting jdbc:jtds:.
* @param info The additional connection properties.
* @throws SQLException
*/
ConnectionJDBC2(String url, Properties info)
throws SQLException {
connections++;
this.url = url;
//
// Extract properties into instance variables
//
unpackProperties(info);
this.messages = new SQLDiagnostic(serverType);
//
// Get the instance port, if it is specified.
// Named pipes use instance names differently.
//
if (instanceName.length() > 0 && !namedPipe) {
final MSSqlServerInfo msInfo = new MSSqlServerInfo(serverName);
portNumber = msInfo.getPortForInstance(instanceName);
if (portNumber == -1) {
throw new SQLException(
Messages.get("error.msinfo.badinst", serverName, instanceName),
"08003");
}
}
SharedSocket.setMemoryBudget(bufferMaxMemory * 1024);
SharedSocket.setMinMemPkts(bufferMinPackets);
SQLWarning warn;
Object timer = null;
boolean loginError = false;
try {
if (loginTimeout > 0) {
// Start a login timer
timer = TimerThread.getInstance().setTimer(loginTimeout * 1000,
new TimerThread.TimerListener() {
public void timerExpired() {
if (socket != null) {
socket.forceClose();
}
}
});
}
if (namedPipe) {
// Use named pipe
socket = createNamedPipe(this);
} else {
// Use plain TCP/IP socket
socket = new SharedSocket(this);
}
if (timer != null && TimerThread.getInstance().hasExpired(timer)) {
// If the timer has expired during the connection phase, close
// the socket and throw an exception
socket.forceClose();
throw new IOException("Login timed out");
}
if ( charsetSpecified ) {
loadCharset(serverCharset);
} else {
// Need a default charset to process login packets for TDS 4.2/5.0
// Will discover the actual serverCharset later
loadCharset("iso_1");
serverCharset = ""; // But don't send charset name to server!
}
//
// Create TDS protocol object
//
baseTds = new TdsCore(this, messages);
//
// Negotiate SSL connection if required
//
if (tdsVersion >= Driver.TDS80 && !namedPipe) {
baseTds.negotiateSSL(instanceName, ssl);
}
//
// Now try to login
//
baseTds.login(serverName,
databaseName,
user,
password,
domainName,
serverCharset,
appName,
progName,
wsid,
language,
macAddress,
packetSize);
//
// Save any login warnings so that they will not be overwritten by
// the internal configuration SQL statements e.g. setCatalog() etc.
//
warn = messages.warnings;
// Update the tdsVersion with the value in baseTds. baseTds sets
// the TDS version for the socket and there are no other objects
// with cached TDS versions at this point.
tdsVersion = baseTds.getTdsVersion();
if (tdsVersion < Driver.TDS70 && databaseName.length() > 0) {
// Need to select the default database
setCatalog(databaseName);
}
// If charset is still unknown and the collation is not set either,
// determine the charset by querying (we're using Sybase or SQL Server
// 6.5)
if ((serverCharset == null || serverCharset.length() == 0)
&& collation == null) {
loadCharset(determineServerCharset());
}
// Initial database settings.
// Sets: auto commit mode = true
// transaction isolation = read committed.
if (serverType == Driver.SYBASE) {
baseTds.submitSQL(SYBASE_INITIAL_SQL);
} else {
// Also discover the maximum decimal precision: 28 (default)
// or 38 for MS SQL Server 6.5/7, or 38 for 2000 and later.
Statement stmt = this.createStatement();
ResultSet rs = stmt.executeQuery(SQL_SERVER_INITIAL_SQL);
if (rs.next()) {
maxPrecision = rs.getByte(1);
}
rs.close();
stmt.close();
}
} catch (UnknownHostException e) {
loginError = true;
throw Support.linkException(
new SQLException(Messages.get("error.connection.badhost",
e.getMessage()), "08S03"), e);
} catch (IOException e) {
loginError = true;
if (loginTimeout > 0 && e.getMessage().indexOf("timed out") >= 0) {
throw Support.linkException(
new SQLException(Messages.get("error.connection.timeout"), "HYT01"), e);
}
throw Support.linkException(
new SQLException(Messages.get("error.connection.ioerror",
e.getMessage()), "08S01"), e);
} catch (SQLException e) {
loginError = true;
if (loginTimeout > 0 && e.getMessage().indexOf("socket closed") >= 0) {
throw Support.linkException(
new SQLException(Messages.get("error.connection.timeout"), "HYT01"), e);
}
throw e;
} catch (RuntimeException e) {
loginError = true;
throw e;
}
finally {
// fix for bug [1755448], socket not closed after login error
if (loginError) {
close();
} else if (timer != null) {
// Cancel loginTimer
TimerThread.getInstance().cancelTimer(timer);
}
}
//
// Restore any login warnings so that the user can retrieve them
// by calling Connection.getWarnings()
//
messages.warnings = warn;
}
/**
* Ensure all resources are released.
*/
protected void finalize() throws Throwable {
try {
close();
} catch (Exception e) {
// ignore any error
} finally {
super.finalize();
}
}
/**
* Creates a {@link SharedSocket} object representing a connection to a named
* pipe. If the os.name system property starts with "Windows"
* (case-insensitive) and the useJCIFS parameter is
* false, a {@link SharedLocalNamedPipe} object is created.
* Else a {@link SharedNamedPipe} is created which uses
* jCIFS to provide a pure-Java
* implementation of Windows named pipes.
* loginTimeout seconds to create a
* named pipe if an IOException continues to be thrown stating,
* "All pipe instances are busy". If loginTimeout is set to
* zero (e.g., not set), a default of 20 seconds will be used.
*
* @param connection the connection object
* @return an object representing the named pipe connection
* @throws IOException on error; if an IOException is thrown with
* a message stating "All pipe instances are busy", then the method timed out
* after loginTimeout milliseconds attempting to create a named pipe.
*/
private SharedSocket createNamedPipe(ConnectionJDBC2 connection) throws IOException {
final long loginTimeout = connection.getLoginTimeout();
final long retryTimeout = (loginTimeout > 0 ? loginTimeout : 20) * 1000;
final long startLoginTimeout = System.currentTimeMillis();
final Random random = new Random(startLoginTimeout);
final boolean isWindowsOS = Support.isWindowsOS();
SharedSocket socket = null;
IOException lastIOException = null;
int exceptionCount = 0;
do {
try {
if (isWindowsOS && !connection.getUseJCIFS()) {
socket = new SharedLocalNamedPipe(connection);
}
else {
socket = new SharedNamedPipe(connection);
}
}
catch (IOException ioe) {
exceptionCount++;
lastIOException = ioe;
if (ioe.getMessage().toLowerCase().indexOf("all pipe instances are busy") >= 0) {
// Per a Microsoft knowledgebase article, wait 200 ms to 1 second each time
// we get an "All pipe instances are busy" error.
// http://support.microsoft.com/default.aspx?scid=KB;EN-US;165189
final int randomWait = random.nextInt(800) + 200;
if (Logger.isActive()) {
Logger.println("Retry #" + exceptionCount + " Wait " + randomWait + " ms: " +
ioe.getMessage());
}
try {
Thread.sleep(randomWait);
}
catch (InterruptedException ie) {
// Do nothing; retry again
}
}
else {
throw ioe;
}
}
} while (socket == null && (System.currentTimeMillis() - startLoginTimeout) < retryTimeout);
if (socket == null) {
final IOException ioException = new IOException("Connection timed out to named pipe");
Support.linkException(ioException, lastIOException);
throw ioException;
}
return socket;
}
/**
* Retrive the shared socket.
*
* @return The SharedSocket object.
*/
SharedSocket getSocket() {
return this.socket;
}
/**
* Retrieve the TDS protocol version.
*
* @return The TDS version as an int.
*/
int getTdsVersion() {
return this.tdsVersion;
}
/**
* Retrieves the next unique stored procedure name.
*
*
* Not synchronized because it's only called from the synchronized
* {@link #prepareSQL} method.
*
* @return the next temporary SP name as a String
*/
String getProcName() {
String seq = "000000" + Integer.toHexString(spSequenceNo++).toUpperCase();
return "#jtds" + seq.substring(seq.length() - 6, seq.length());
}
/**
* Retrieves the next unique cursor name.
*
* @return the next cursor name as a String
*/
synchronized String getCursorName() {
String seq = "000000" + Integer.toHexString(cursorSequenceNo++).toUpperCase();
return "_jtds" + seq.substring(seq.length() - 6, seq.length());
}
/**
* Try to convert the SQL statement into a statement prepare.
* baseTds, but the method call also needs to made in a
* synchronized (connection) block together with the execution
* (if the prepared statement is actually executed) to ensure the
* transaction isn't rolled back between this method call and the actual
* execution.
*
* @param pstmt the target prepared statement
* @param sql the SQL statement to prepare
* @param params the parameters
* @param returnKeys indicates whether the statement will return
* generated keys
* @param cursorNeeded indicates whether a cursor prepare is needed
* @return the SQL procedure name as a String or null if the
* SQL cannot be prepared
*/
synchronized String prepareSQL(JtdsPreparedStatement pstmt,
String sql,
ParamInfo[] params,
boolean returnKeys,
boolean cursorNeeded)
throws SQLException {
if (prepareSql == TdsCore.UNPREPARED
|| prepareSql == TdsCore.EXECUTE_SQL) {
return null; // User selected not to use procs
}
if (serverType == Driver.SYBASE) {
if (tdsVersion != Driver.TDS50) {
return null; // No longer support stored procs with 4.2
}
if (returnKeys) {
return null; // Sybase cannot use @@IDENTITY in proc
}
if (cursorNeeded) {
//
// We are going to use the CachedResultSet so there is
// no point in preparing the SQL as it will be discarded
// in favour of a version with "FOR BROWSE" appended.
//
return null;
}
}
//
// Check parameters set and obtain native types
//
for (int i = 0; i < params.length; i++) {
if (!params[i].isSet) {
throw new SQLException(Messages.get("error.prepare.paramnotset",
Integer.toString(i+1)),
"07000");
}
TdsData.getNativeType(this, params[i]);
if (serverType == Driver.SYBASE) {
if ("text".equals(params[i].sqlType)
|| "image".equals(params[i].sqlType)) {
return null; // Sybase does not support text/image params
}
}
}
String key = Support.getStatementKey(sql, params, serverType,
getCatalog(), autoCommit, cursorNeeded);
//
// See if we have already built this one
//
ProcEntry proc = (ProcEntry) statementCache.get(key);
if (proc != null) {
//
// Yes found in cache OK
//
// If already used by the statement, decrement use count
if (pstmt.handles != null && pstmt.handles.contains(proc)) {
proc.release();
}
pstmt.setColMetaData(proc.getColMetaData());
if (serverType == Driver.SYBASE) {
pstmt.setParamMetaData(proc.getParamMetaData());
}
} else {
//
// No, so create the stored procedure now
//
proc = new ProcEntry();
if (serverType == Driver.SQLSERVER) {
proc.setName(
baseTds.microsoftPrepare(
sql, params, cursorNeeded,
pstmt.getResultSetType(),
pstmt.getResultSetConcurrency()));
if (proc.toString() == null) {
proc.setType(ProcEntry.PREP_FAILED);
} else if (prepareSql == TdsCore.TEMPORARY_STORED_PROCEDURES) {
proc.setType(ProcEntry.PROCEDURE);
} else {
proc.setType((cursorNeeded) ? ProcEntry.CURSOR : ProcEntry.PREPARE);
// Meta data may be returned by sp_prepare
proc.setColMetaData(baseTds.getColumns());
pstmt.setColMetaData(proc.getColMetaData());
}
// TODO Find some way of getting parameter meta data for MS
} else {
proc.setName(baseTds.sybasePrepare(sql, params));
if (proc.toString() == null) {
proc.setType(ProcEntry.PREP_FAILED);
} else {
proc.setType(ProcEntry.PROCEDURE);
}
// Sybase gives us lots of useful information about the result set
proc.setColMetaData(baseTds.getColumns());
proc.setParamMetaData(baseTds.getParameters());
pstmt.setColMetaData(proc.getColMetaData());
pstmt.setParamMetaData(proc.getParamMetaData());
}
// OK we have built a proc so add it to the cache.
addCachedProcedure(key, proc);
}
// Add the handle to the prepared statement so that the handles
// can be used to clean up the statement cache properly when the
// prepared statement is closed.
if (pstmt.handles == null) {
pstmt.handles = new HashSet(10);
}
pstmt.handles.add(proc);
// Give the user the name will be null if prepare failed
return proc.toString();
}
/**
* Add a stored procedure to the cache.
* int where 1 == SQLSERVER and
* 2 == SYBASE.
*/
public int getServerType() {
return this.serverType;
}
/**
* Sets the network packet size.
*
* @param size the new packet size
*/
void setNetPacketSize(int size) {
this.netPacketSize = size;
}
/**
* Retrieves the network packet size.
*
* @return the packet size as an int
*/
int getNetPacketSize() {
return this.netPacketSize;
}
/**
* Retrieves the current row count on this connection.
*
* @return the row count as an int
*/
int getRowCount() {
return this.rowCount;
}
/**
* Sets the current row count on this connection.
*
* @param count the new row count
*/
void setRowCount(int count) {
rowCount = count;
}
/**
* Retrieves the current maximum textsize on this connection.
*
* @return the maximum textsize as an int
*/
public int getTextSize() {
return textSize;
}
/**
* Sets the current maximum textsize on this connection.
*
* @param textSize the new maximum textsize
*/
public void setTextSize(int textSize) {
this.textSize = textSize;
}
/**
* Retrieves the status of the lastUpdateCount flag.
*
* @return the lastUpdateCount flag as a boolean
*/
boolean getLastUpdateCount() {
return this.lastUpdateCount;
}
/**
* Retrieves the maximum decimal precision.
*
* @return the precision as an int
*/
int getMaxPrecision() {
return this.maxPrecision;
}
/**
* Retrieves the LOB buffer size.
*
* @return the LOB buffer size as a long
*/
long getLobBuffer() {
return this.lobBuffer;
}
/**
* Retrieves the Prepared SQL method.
*
* @return the Prepared SQL method
*/
int getPrepareSql() {
return this.prepareSql;
}
/**
* Retrieves the batch size to be used internally.
*
* @return the batch size as an int
*/
int getBatchSize() {
return this.batchSize;
}
/**
* Retrieves the boolean indicating whether metadata caching
* is enabled.
*
* @return true if metadata caching is enabled,
* false if caching is disabled
*/
boolean getUseMetadataCache() {
return this.useMetadataCache;
}
/**
* Indicates whether fast forward only cursors should be used for forward
* only result sets.
*
* @return true if fast forward cursors are requested
*/
boolean getUseCursors() {
return this.useCursors;
}
/**
* Indicates whether large types (IMAGE and TEXT/NTEXT) should be mapped by
* default to LOB types or String and byte[]
* respectively.
*
* @return true if the default mapping should be to LOBs,
* false otherwise
*/
boolean getUseLOBs() {
return this.useLOBs;
}
/**
* Indicates whether, when doing Windows authentication to an MS SQL server,
* NTLMv2 should be used. When this is set to "false", LM and NTLM responses
* are sent to the server, which should work fine in most cases. However,
* some servers are configured to require LMv2 and NTLMv2. In these rare
* cases, this property should be set to "true".
*/
boolean getUseNTLMv2() {
return this.useNTLMv2;
}
/**
* Retrieves the application name for this connection.
*
* @return the application name
*/
String getAppName() {
return this.appName;
}
/**
* Retrieves the bind address for this connection.
*
* @return the bind address
*/
String getBindAddress() {
return this.bindAddress;
}
/**
* Returns the directory where data should be buffered to.
*
* @return the directory where data should be buffered to.
*/
File getBufferDir() {
return this.bufferDir;
}
/**
* Retrieves the maximum amount of memory in Kb to buffer for all connections.
*
* @return the maximum amount of memory in Kb to buffer for all connections
*/
int getBufferMaxMemory() {
return this.bufferMaxMemory;
}
/**
* Retrieves the minimum number of packets to buffer per {@link Statement} for this connection.
*
* @return the minimum number of packets to buffer per {@link Statement}
*/
int getBufferMinPackets() {
return this.bufferMinPackets;
}
/**
* Retrieves the database name for this connection.
*
* @return the database name
*/
String getDatabaseName() {
return this.databaseName;
}
/**
* Retrieves the domain name for this connection.
*
* @return the domain name
*/
String getDomainName() {
return this.domainName;
}
/**
* Retrieves the instance name for this connection.
*
* @return the instance name
*/
String getInstanceName() {
return this.instanceName;
}
/**
* Retrieves the login timeout for this connection.
*
* @return the login timeout
*/
int getLoginTimeout() {
return this.loginTimeout;
}
/**
* Retrieves the socket timeout for this connection.
*
* @return the socket timeout
*/
int getSocketTimeout() {
return this.socketTimeout;
}
/**
* Retrieves whether to enable socket keep alive.
*
* @return true if the socket keep alive is enabled
*/
boolean getSocketKeepAlive() {
return this.socketKeepAlive;
}
/**
* Retrieves the process ID to send to a server when a connection is
* established.
*
* @return the process ID
*/
int getProcessId() {
return this.processId.intValue();
}
/**
* Retrieves the MAC (ethernet) address for this connection.
*
* @return the MAC (ethernet) address
*/
String getMacAddress() {
return this.macAddress;
}
/**
* Retrieves the named pipe setting for this connection.
*
* @return the named pipe setting
*/
boolean getNamedPipe() {
return this.namedPipe;
}
/**
* Retrieves the packet size for this connection.
*
* @return the packet size
*/
int getPacketSize() {
return this.packetSize;
}
/**
* Retrieves the password for this connection.
*
* @return the password
*/
String getPassword() {
return this.password;
}
/**
* Retrieves the port number for this connection.
*
* @return the port number
*/
int getPortNumber() {
return this.portNumber;
}
/**
* Retrieves the program name for this connection.
*
* @return the program name
*/
String getProgName() {
return this.progName;
}
/**
* Retrieves the server name for this connection.
*
* @return the server name
*/
String getServerName() {
return this.serverName;
}
/**
* Retrieves the tcpNoDelay setting for this connection.
*
* @return the tcpNoDelay setting
*/
boolean getTcpNoDelay() {
return this.tcpNoDelay;
}
/**
* Retrieves the useJCIFS setting for this connection.
*
* @return the useJCIFS setting
*/
boolean getUseJCIFS() {
return this.useJCIFS;
}
/**
* Retrieves the user for this connection.
*
* @return the user
*/
String getUser() {
return this.user;
}
/**
* Retrieves the workstation ID (WSID) for this connection.
*
* @return the workstation ID (WSID)
*/
String getWsid() {
return this.wsid;
}
/**
* Transfers the properties to the local instance variables.
*
* @param info The connection properties Object.
* @throws SQLException If an invalid property value is found.
*/
protected void unpackProperties(Properties info)
throws SQLException {
serverName = info.getProperty(Messages.get(Driver.SERVERNAME));
portNumber = parseIntegerProperty(info, Driver.PORTNUMBER);
serverType = parseIntegerProperty(info, Driver.SERVERTYPE);
databaseName = info.getProperty(Messages.get(Driver.DATABASENAME));
instanceName = info.getProperty(Messages.get(Driver.INSTANCE));
domainName = info.getProperty(Messages.get(Driver.DOMAIN));
user = info.getProperty(Messages.get(Driver.USER));
password = info.getProperty(Messages.get(Driver.PASSWORD));
macAddress = info.getProperty(Messages.get(Driver.MACADDRESS));
appName = info.getProperty(Messages.get(Driver.APPNAME));
progName = info.getProperty(Messages.get(Driver.PROGNAME));
wsid = info.getProperty(Messages.get(Driver.WSID));
serverCharset = info.getProperty(Messages.get(Driver.CHARSET));
language = info.getProperty(Messages.get(Driver.LANGUAGE));
bindAddress = info.getProperty(Messages.get(Driver.BINDADDRESS));
lastUpdateCount = parseBooleanProperty(info,Driver.LASTUPDATECOUNT);
useUnicode = parseBooleanProperty(info,Driver.SENDSTRINGPARAMETERSASUNICODE);
namedPipe = parseBooleanProperty(info,Driver.NAMEDPIPE);
tcpNoDelay = parseBooleanProperty(info,Driver.TCPNODELAY);
useCursors = (serverType == Driver.SQLSERVER) && parseBooleanProperty(info,Driver.USECURSORS);
useLOBs = parseBooleanProperty(info,Driver.USELOBS);
useMetadataCache = parseBooleanProperty(info,Driver.CACHEMETA);
xaEmulation = parseBooleanProperty(info,Driver.XAEMULATION);
useJCIFS = parseBooleanProperty(info,Driver.USEJCIFS);
charsetSpecified = serverCharset.length() > 0;
useNTLMv2 = parseBooleanProperty(info,Driver.USENTLMV2);
//note:mdb in certain cases (e.g. NTLMv2) the domain name must be
// all upper case for things to work.
if( domainName != null )
domainName = domainName.toUpperCase();
Integer parsedTdsVersion =
DefaultProperties.getTdsVersion(info.getProperty(Messages.get(Driver.TDS)));
if (parsedTdsVersion == null) {
throw new SQLException(Messages.get("error.connection.badprop",
Messages.get(Driver.TDS)), "08001");
}
tdsVersion = parsedTdsVersion.intValue();
packetSize = parseIntegerProperty(info, Driver.PACKETSIZE);
if (packetSize < TdsCore.MIN_PKT_SIZE) {
if (tdsVersion >= Driver.TDS70) {
// Default of 0 means let the server specify packet size
packetSize = (packetSize == 0) ? 0 : TdsCore.DEFAULT_MIN_PKT_SIZE_TDS70;
} else if (tdsVersion == Driver.TDS42) {
// Sensible minimum for older versions of TDS
packetSize = TdsCore.MIN_PKT_SIZE;
} // else for TDS 5 can auto negotiate
}
if (packetSize > TdsCore.MAX_PKT_SIZE) {
packetSize = TdsCore.MAX_PKT_SIZE;
}
packetSize = (packetSize / 512) * 512;
loginTimeout = parseIntegerProperty(info, Driver.LOGINTIMEOUT);
socketTimeout = parseIntegerProperty(info, Driver.SOTIMEOUT);
socketKeepAlive = parseBooleanProperty(info,Driver.SOKEEPALIVE);
String pid = info.getProperty(Messages.get(Driver.PROCESSID));
if ("compute".equals(pid)) {
// only determine a single PID for the VM's (or classloader's) life time
if (processId == null) {
// random number until the real process ID can be determined
processId = new Integer(new Random(System.currentTimeMillis()).nextInt(32768));
}
} else if (pid.length() > 0) {
processId = new Integer(parseIntegerProperty(info, Driver.PROCESSID));
}
lobBuffer = parseLongProperty(info, Driver.LOBBUFFER);
maxStatements = parseIntegerProperty(info, Driver.MAXSTATEMENTS);
statementCache = new ProcedureCache(maxStatements);
prepareSql = parseIntegerProperty(info, Driver.PREPARESQL);
if (prepareSql < 0) {
prepareSql = 0;
} else if (prepareSql > 3) {
prepareSql = 3;
}
// For Sybase use equivalent of sp_executesql.
if (tdsVersion < Driver.TDS70 && prepareSql == TdsCore.PREPARE) {
prepareSql = TdsCore.EXECUTE_SQL;
}
// For SQL 6.5 sp_executesql not available so use stored procedures.
if (tdsVersion < Driver.TDS50 && prepareSql == TdsCore.EXECUTE_SQL) {
prepareSql = TdsCore.TEMPORARY_STORED_PROCEDURES;
}
ssl = info.getProperty(Messages.get(Driver.SSL));
batchSize = parseIntegerProperty(info, Driver.BATCHSIZE);
if (batchSize < 0) {
throw new SQLException(Messages.get("error.connection.badprop",
Messages.get(Driver.BATCHSIZE)), "08001");
}
bufferDir = new File(info.getProperty(Messages.get(Driver.BUFFERDIR)));
if (!bufferDir.isDirectory()) {
if (!bufferDir.mkdirs()) {
throw new SQLException(Messages.get("error.connection.badprop",
Messages.get(Driver.BUFFERDIR)), "08001");
}
}
bufferMaxMemory = parseIntegerProperty(info, Driver.BUFFERMAXMEMORY);
if (bufferMaxMemory < 0) {
throw new SQLException(Messages.get("error.connection.badprop",
Messages.get(Driver.BUFFERMAXMEMORY)), "08001");
}
bufferMinPackets = parseIntegerProperty(info, Driver.BUFFERMINPACKETS);
if (bufferMinPackets < 1) {
throw new SQLException(Messages.get("error.connection.badprop",
Messages.get(Driver.BUFFERMINPACKETS)), "08001");
}
}
/**
* Parse a string property value into an boolean value.
*
* @param info The connection properties object.
* @param key The message key used to retrieve the property name.
* @return The boolean value of the string property value.
* @throws SQLException If the property value can't be parsed.
*/
private static boolean parseBooleanProperty(final Properties info, final String key)
throws SQLException {
final String propertyName = Messages.get(key);
String prop = info.getProperty(propertyName);
if (! (prop == null || "true".equalsIgnoreCase(prop) || "false".equalsIgnoreCase(prop)))
throw new SQLException( Messages.get("error.connection.badprop", propertyName), "08001");
return "true".equalsIgnoreCase(prop);
}
/**
* Parse a string property value into an integer value.
*
* @param info The connection properties object.
* @param key The message key used to retrieve the property name.
* @return The integer value of the string property value.
* @throws SQLException If the property value can't be parsed.
*/
private static int parseIntegerProperty(final Properties info, final String key)
throws SQLException {
final String propertyName = Messages.get(key);
try {
return Integer.parseInt(info.getProperty(propertyName));
} catch (NumberFormatException e) {
throw new SQLException(
Messages.get("error.connection.badprop", propertyName), "08001");
}
}
/**
* Parse a string property value into a long value.
*
* @param info The connection properties object.
* @param key The message key used to retrieve the property name.
* @return The long value of the string property value.
* @throws SQLException If the property value can't be parsed.
*/
private static long parseLongProperty(final Properties info, final String key)
throws SQLException {
final String propertyName = Messages.get(key);
try {
return Long.parseLong(info.getProperty(propertyName));
} catch (NumberFormatException e) {
throw new SQLException(
Messages.get("error.connection.badprop", propertyName), "08001");
}
}
/**
* Retrieve the Java charset to use for encoding.
*
* @return the Charset name as a String
*/
protected String getCharset() {
return charsetInfo.getCharset();
}
/**
* Retrieve the multibyte status of the current character set.
*
* @return boolean true if a multi byte character set
*/
protected boolean isWideChar() {
return charsetInfo.isWideChars();
}
/**
* Retrieve the CharsetInfo instance used by this connection.
*
* @return the default CharsetInfo for this connection
*/
protected CharsetInfo getCharsetInfo() {
return charsetInfo;
}
/**
* Retrieve the sendParametersAsUnicode flag.
*
* @return boolean true if parameters should be sent as unicode.
*/
protected boolean getUseUnicode() {
return this.useUnicode;
}
/**
* Retrieve the Sybase capability data.
*
* @return Capability bit mask as an int.
*/
protected boolean getSybaseInfo(int flag) {
return (this.sybaseInfo & flag) != 0;
}
/**
* Set the Sybase capability data.
*
* @param mask The capability bit mask.
*/
protected void setSybaseInfo(int mask) {
this.sybaseInfo = mask;
}
/**
* Called by the protocol to change the current character set.
*
* @param charset the server character set name
*/
protected void setServerCharset(final String charset) throws SQLException {
// If the user specified a charset, ignore environment changes
if (charsetSpecified) {
Logger.println("Server charset " + charset +
". Ignoring as user requested " + serverCharset + '.');
return;
}
if (!charset.equals(serverCharset)) {
loadCharset(charset);
if (Logger.isActive()) {
Logger.println("Set charset to " + serverCharset + '/'
+ charsetInfo);
}
}
}
/**
* Load the Java charset to match the server character set.
*
* @param charset the server character set
*/
private void loadCharset(String charset) throws SQLException {
// MS SQL Server's iso_1 is Cp1252 not ISO-8859-1!
if (getServerType() == Driver.SQLSERVER
&& charset.equalsIgnoreCase("iso_1")) {
charset = "Cp1252";
}
// Do not default to any charset; if the charset is not found we want
// to know about it
CharsetInfo tmp = CharsetInfo.getCharset(charset);
if (tmp == null) {
throw new SQLException(
Messages.get("error.charset.nomapping", charset), "2C000");
}
loadCharset(tmp, charset);
serverCharset = charset;
}
/**
* Load the Java charset to match the server character set.
*
* @param ci the CharsetInfo to load
*/
private void loadCharset(CharsetInfo ci, String ref) throws SQLException {
try {
"This is a test".getBytes(ci.getCharset());
charsetInfo = ci;
} catch (UnsupportedEncodingException ex) {
throw new SQLException(
Messages.get("error.charset.invalid", ref,
ci.getCharset()),
"2C000");
}
socket.setCharsetInfo(charsetInfo);
}
/**
* Discovers the server charset for server versions that do not send
* ENVCHANGE packets on login ack, by executing a DB
* vendor/version specific query.
* SQLException if used on SQL Server 7.0 or
* 2000; the idea is that the charset should already be determined from
* ENVCHANGE packets for these DB servers.
*
*
* If the sort order is non-zero it determines the character set, otherwise
* the character set is determined by the locale id.
*
* @param collation The new collation.
*/
void setCollation(byte[] collation) throws SQLException {
String strCollation = "0x" + Support.toHex(collation);
// If the user specified a charset, ignore environment changes
if (charsetSpecified) {
Logger.println("Server collation " + strCollation +
". Ignoring as user requested " + serverCharset + '.');
return;
}
CharsetInfo tmp = CharsetInfo.getCharset(collation);
loadCharset(tmp, strCollation);
this.collation = collation;
if (Logger.isActive()) {
Logger.println("Set collation to " + strCollation + '/'
+ charsetInfo);
}
}
/**
* Retrieve the SQL Server 2000 default collation.
*
* @return The collation as a byte[5].
*/
byte[] getCollation() {
return this.collation;
}
/**
* Retrieves whether a specific charset was requested on creation. If this
* is the case, all character data should be encoded/decoded using that
* charset.
*/
boolean isCharsetSpecified() {
return charsetSpecified;
}
/**
* Called by the protcol to change the current database context.
*
* @param newDb The new database selected on the server.
* @param oldDb The old database as known by the server.
* @throws SQLException
*/
protected void setDatabase(final String newDb, final String oldDb)
throws SQLException {
if (currentDatabase != null && !oldDb.equalsIgnoreCase(currentDatabase)) {
throw new SQLException(Messages.get("error.connection.dbmismatch",
oldDb, databaseName),
"HY096");
}
currentDatabase = newDb;
if (Logger.isActive()) {
Logger.println("Changed database from " + oldDb + " to " + newDb);
}
}
/**
* Update the connection instance with information about the server.
*
* @param databaseProductName The server name eg SQL Server.
* @param databaseMajorVersion The major version eg 11
* @param databaseMinorVersion The minor version eg 92
* @param buildNumber The server build number.
*/
protected void setDBServerInfo(String databaseProductName,
int databaseMajorVersion,
int databaseMinorVersion,
int buildNumber) {
this.databaseProductName = databaseProductName;
this.databaseMajorVersion = databaseMajorVersion;
this.databaseMinorVersion = databaseMinorVersion;
if (tdsVersion >= Driver.TDS70) {
StringBuffer buf = new StringBuffer(10);
if (databaseMajorVersion < 10) {
buf.append('0');
}
buf.append(databaseMajorVersion).append('.');
if (databaseMinorVersion < 10) {
buf.append('0');
}
buf.append(databaseMinorVersion).append('.');
buf.append(buildNumber);
while (buf.length() < 10) {
buf.insert(6, '0');
}
this.databaseProductVersion = buf.toString();
} else {
databaseProductVersion =
databaseMajorVersion + "." + databaseMinorVersion;
}
}
/**
* Removes a statement object from the list maintained by the connection
* and cleans up the statement cache if necessary.
* baseTds.
*
* @param statement the statement to remove
*/
synchronized void removeStatement(JtdsStatement statement)
throws SQLException {
// Remove the JtdsStatement from the statement list
synchronized (statements) {
for (int i = 0; i < statements.size(); i++) {
WeakReference wr = (WeakReference) statements.get(i);
if (wr != null) {
Statement stmt = (Statement) wr.get();
// Remove the statement if found but also remove all
// statements that have already been garbage collected
if (stmt == null || stmt == statement) {
statements.set(i, null);
}
}
}
}
if (statement instanceof JtdsPreparedStatement) {
// Clean up the prepared statement cache; getObsoleteHandles will
// decrement the usage count for the set of used handles
Collection handles = statementCache.getObsoleteHandles(
((JtdsPreparedStatement) statement).handles);
if (handles != null) {
if (serverType == Driver.SQLSERVER) {
// SQL Server unprepare
StringBuffer cleanupSql = new StringBuffer(handles.size() * 32);
for (Iterator iterator = handles.iterator(); iterator.hasNext(); ) {
ProcEntry pe = (ProcEntry) iterator.next();
// Could get put back if in a transaction that is
// rolled back
pe.appendDropSQL(cleanupSql);
}
if (cleanupSql.length() > 0) {
baseTds.executeSQL(cleanupSql.toString(), null, null, true, 0,
-1, -1, true);
baseTds.clearResponseQueue();
}
} else {
// Sybase unprepare
for (Iterator iterator = handles.iterator(); iterator.hasNext(); ) {
ProcEntry pe = (ProcEntry)iterator.next();
if (pe.toString() != null) {
// Remove the Sybase light weight proc
baseTds.sybaseUnPrepare(pe.toString());
}
}
}
}
}
}
/**
* Adds a statement object to the list maintained by the connection.
* int
*/
public int getDatabaseMajorVersion() {
return this.databaseMajorVersion;
}
/**
* Retrieves the DBMS minor version.
*
* @return the version as an int
*/
public int getDatabaseMinorVersion() {
return this.databaseMinorVersion;
}
/**
* Retrieves the DBMS product name.
*
* @return the name as a String
*/
String getDatabaseProductName() {
return this.databaseProductName;
}
/**
* Retrieves the DBMS product version.
*
* @return the version as a String
*/
String getDatabaseProductVersion() {
return this.databaseProductVersion;
}
/**
* Retrieves the original connection URL.
*
* @return the connection url as a String
*/
String getURL() {
return this.url;
}
/**
* Retrieves the host and port for this connection.
* String
*/
public String getRmHost() {
return serverName + ':' + portNumber;
}
/**
* Forces the closed status on the statement if an I/O error has occurred.
*/
void setClosed() {
if (!closed) {
closed = true;
// Make sure we release the socket and all data buffered at the socket
// level
try {
socket.close();
} catch (IOException e) {
// Ignore; shouldn't happen anyway
}
}
}
/**
* Invokes the xp_jtdsxa extended stored procedure on the
* server.
* baseTds.
*
* @param args the arguments eg cmd, rmid, flags etc.
* @param data option byte data eg open string xid etc.
* @return optional byte data eg OLE cookie
* @throws SQLException if an error condition occurs
*/
synchronized byte[][] sendXaPacket(int args[], byte[] data)
throws SQLException {
ParamInfo params[] = new ParamInfo[6];
params[0] = new ParamInfo(Types.INTEGER, null, ParamInfo.RETVAL);
params[1] = new ParamInfo(Types.INTEGER, new Integer(args[1]), ParamInfo.INPUT);
params[2] = new ParamInfo(Types.INTEGER, new Integer(args[2]), ParamInfo.INPUT);
params[3] = new ParamInfo(Types.INTEGER, new Integer(args[3]), ParamInfo.INPUT);
params[4] = new ParamInfo(Types.INTEGER, new Integer(args[4]), ParamInfo.INPUT);
params[5] = new ParamInfo(Types.VARBINARY, data, ParamInfo.OUTPUT);
//
// Execute our extended stored procedure (let's hope it is installed!).
//
baseTds.executeSQL(null, "master..xp_jtdsxa", params, false, 0, -1, -1,
true);
//
// Now process results
//
ArrayList xids = new ArrayList();
while (!baseTds.isEndOfResponse()) {
if (baseTds.getMoreResults()) {
// This had better be the results from a xa_recover command
while (baseTds.getNextRow()) {
Object row[] = baseTds.getRowData();
if (row.length == 1 && row[0] instanceof byte[]) {
xids.add(row[0]);
}
}
}
}
messages.checkErrors();
if (params[0].getOutValue() instanceof Integer) {
// Should be return code from XA command
args[0] = ((Integer)params[0].getOutValue()).intValue();
} else {
args[0] = -7; // XAException.XAER_RMFAIL
}
if (xids.size() > 0) {
// List of XIDs from xa_recover
byte list[][] = new byte[xids.size()][];
for (int i = 0; i < xids.size(); i++) {
list[i] = (byte[])xids.get(i);
}
return list;
} else
if (params[5].getOutValue() instanceof byte[]) {
// xa_open the xa connection ID
// xa_start OLE Transaction cookie
byte cookie[][] = new byte[1][];
cookie[0] = (byte[])params[5].getOutValue();
return cookie;
} else {
// All other cases
return null;
}
}
/**
* Enlists the current connection in a distributed transaction.
*
* @param oleTranID the OLE transaction cookie or null to delist
* @throws SQLException if an error condition occurs
*/
synchronized void enlistConnection(byte[] oleTranID)
throws SQLException {
if (oleTranID != null) {
// TODO: Stored procs are no good but maybe prepare will be OK.
this.prepareSql = TdsCore.EXECUTE_SQL;
baseTds.enlistConnection(1, oleTranID);
xaTransaction = true;
} else {
baseTds.enlistConnection(1, null);
xaTransaction = false;
}
}
/**
* Sets the XA transaction ID when running in emulation mode.
*
* @param xid the XA Transaction ID
*/
void setXid(Object xid) {
this.xid = xid;
xaTransaction = xid != null;
}
/**
* Gets the XA transaction ID when running in emulation mode.
*
* @return the transaction ID as an Object
*/
Object getXid() {
return xid;
}
/**
* Sets the XA state variable.
*
* @param value the XA state value
*/
void setXaState(int value) {
this.xaState = value;
}
/**
* Retrieves the XA state variable.
*
* @return the xa state variable as an int
*/
int getXaState() {
return this.xaState;
}
/**
* Retrieves the XA Emulation flag.
* @return True if in XA emulation mode.
*/
boolean isXaEmulation() {
return xaEmulation;
}
/**
* Retrieves the connection mutex and acquires an exclusive lock on the
* network connection.
*
* @return the mutex object as a Semaphore
*/
Semaphore getMutex() {
// Thread.interrupted() will clear the interrupt status
boolean interrupted = Thread.interrupted();
try {
this.mutex.acquire();
} catch (InterruptedException e) {
throw new IllegalStateException("Thread execution interrupted");
}
if (interrupted) {
// Bug [1596743] do not absorb interrupt status
Thread.currentThread().interrupt();
}
return this.mutex;
}
/**
* Releases (either closes or caches) a TdsCore.
*
* @param tds the TdsCore instance to release
* @throws SQLException if an error occurs while closing or cleaning up
* @todo Should probably synchronize on another object
*/
synchronized void releaseTds(TdsCore tds) throws SQLException {
if (cachedTds != null) {
// There's already a cached TdsCore; close this one
tds.close();
} else {
// No cached TdsCore; clean up this one and cache it
tds.clearResponseQueue();
tds.cleanUp();
cachedTds = tds;
}
}
/**
* Retrieves the cached TdsCore or null if
* nothing is cached and resets the cache (sets it to null).
*
* @return the value of {@link #cachedTds}
* @todo Should probably synchronize on another object
*/
synchronized TdsCore getCachedTds() {
TdsCore result = cachedTds;
cachedTds = null;
return result;
}
//
// ------------------- java.sql.Connection interface methods -------------------
//
public int getHoldability() throws SQLException {
checkOpen();
return JtdsResultSet.HOLD_CURSORS_OVER_COMMIT;
}
synchronized public int getTransactionIsolation() throws SQLException {
checkOpen();
return this.transactionIsolation;
}
synchronized public void clearWarnings() throws SQLException {
checkOpen();
messages.clearWarnings();
}
/**
* Releases this Connection object's database and JDBC
* resources immediately instead of waiting for them to be automatically
* released.
* Connection object that is
* already closed is a no-op.
* Connection object is automatically closed
* when it is garbage collected. Certain fatal errors also close a
* Connection object.
* baseTds.
*
* @throws SQLException if a database access error occurs
*/
synchronized public void close() throws SQLException {
if (!closed) {
try {
//
// Close any open statements
//
ArrayList tmpList;
synchronized (statements) {
tmpList = new ArrayList(statements);
statements.clear();
}
for (int i = 0; i < tmpList.size(); i++) {
WeakReference wr = (WeakReference)tmpList.get(i);
if (wr != null) {
Statement stmt = (Statement) wr.get();
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex) {
// Ignore
}
}
}
}
try {
// Tell the server the session is ending, close network connection
if (baseTds != null) {
baseTds.closeConnection();
baseTds.close();
}
// Close cached TdsCore
if (cachedTds != null) {
cachedTds.close();
cachedTds = null;
}
} catch (SQLException ex) {
// Ignore
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
// Ignore
} finally {
closed = true;
if (--connections == 0) {
TimerThread.getInstance().stopTimer();
}
}
}
}
synchronized public void commit() throws SQLException {
checkOpen();
checkLocal("commit");
if (getAutoCommit()) {
throw new SQLException(
Messages.get("error.connection.autocommit", "commit"),
"25000");
}
baseTds.submitSQL("IF @@TRANCOUNT > 0 COMMIT TRAN");
procInTran.clear();
clearSavepoints();
}
synchronized public void rollback() throws SQLException {
checkOpen();
checkLocal("rollback");
if (getAutoCommit()) {
throw new SQLException(
Messages.get("error.connection.autocommit", "rollback"),
"25000");
}
baseTds.submitSQL("IF @@TRANCOUNT > 0 ROLLBACK TRAN");
for (int i = 0; i < procInTran.size(); i++) {
String key = (String) procInTran.get(i);
if (key != null) {
statementCache.remove(key);
}
}
procInTran.clear();
clearSavepoints();
}
synchronized public boolean getAutoCommit() throws SQLException {
checkOpen();
return this.autoCommit;
}
public boolean isClosed() throws SQLException {
return closed;
}
public boolean isReadOnly() throws SQLException {
checkOpen();
return this.readOnly;
}
public void setHoldability(int holdability) throws SQLException {
checkOpen();
switch (holdability) {
case JtdsResultSet.HOLD_CURSORS_OVER_COMMIT:
break;
case JtdsResultSet.CLOSE_CURSORS_AT_COMMIT:
throw new SQLException(
Messages.get("error.generic.optvalue",
"CLOSE_CURSORS_AT_COMMIT",
"setHoldability"),
"HY092");
default:
throw new SQLException(
Messages.get("error.generic.badoption",
Integer.toString(holdability),
"holdability"),
"HY092");
}
}
synchronized public void setTransactionIsolation(int level) throws SQLException {
checkOpen();
if (transactionIsolation == level) {
// No need to submit a request
return;
}
String sql = "SET TRANSACTION ISOLATION LEVEL ";
boolean sybase = serverType == Driver.SYBASE;
switch (level) {
case java.sql.Connection.TRANSACTION_READ_UNCOMMITTED:
sql += (sybase) ? "0" : "READ UNCOMMITTED";
break;
case java.sql.Connection.TRANSACTION_READ_COMMITTED:
sql += (sybase) ? "1" : "READ COMMITTED";
break;
case java.sql.Connection.TRANSACTION_REPEATABLE_READ:
sql += (sybase) ? "2" : "REPEATABLE READ";
break;
case java.sql.Connection.TRANSACTION_SERIALIZABLE:
sql += (sybase) ? "3" : "SERIALIZABLE";
break;
case TRANSACTION_SNAPSHOT:
if (sybase) {
throw new SQLException(
Messages.get("error.generic.optvalue",
"TRANSACTION_SNAPSHOT",
"setTransactionIsolation"),
"HY024");
} else {
sql += "SNAPSHOT";
}
break;
case java.sql.Connection.TRANSACTION_NONE:
throw new SQLException(
Messages.get("error.generic.optvalue",
"TRANSACTION_NONE",
"setTransactionIsolation"),
"HY024");
default:
throw new SQLException(
Messages.get("error.generic.badoption",
Integer.toString(level),
"level"),
"HY092");
}
transactionIsolation = level;
baseTds.submitSQL(sql);
}
synchronized public void setAutoCommit(boolean autoCommit) throws SQLException {
checkOpen();
checkLocal("setAutoCommit");
if (this.autoCommit == autoCommit) {
// If we don't need to change the current auto commit mode, don't
// submit a request and don't commit either. Section 10.1.1 of the
// JDBC 3.0 spec states that the transaction should be committed
// only "if the value of auto-commit is _changed_ in the middle of
// a transaction". This takes precedence over the API docs, which
// states that "if this method is called during a transaction, the
// transaction is committed".
return;
}
StringBuffer sql = new StringBuffer(70);
//
if (!this.autoCommit) {
// If we're in manual commit mode the spec requires that we commit
// the transaction when setAutoCommit() is called
sql.append("IF @@TRANCOUNT > 0 COMMIT TRAN\r\n");
}
if (serverType == Driver.SYBASE) {
if (autoCommit) {
sql.append("SET CHAINED OFF");
} else {
sql.append("SET CHAINED ON");
}
} else {
if (autoCommit) {
sql.append("SET IMPLICIT_TRANSACTIONS OFF");
} else {
sql.append("SET IMPLICIT_TRANSACTIONS ON");
}
}
baseTds.submitSQL(sql.toString());
this.autoCommit = autoCommit;
}
public void setReadOnly(boolean readOnly) throws SQLException {
checkOpen();
this.readOnly = readOnly;
}
synchronized public String getCatalog() throws SQLException {
checkOpen();
return this.currentDatabase;
}
synchronized public void setCatalog(String catalog) throws SQLException {
checkOpen();
if (currentDatabase != null && currentDatabase.equals(catalog)) {
return;
}
int maxlength = tdsVersion >= Driver.TDS70 ? 128 : 30;
if (catalog.length() > maxlength || catalog.length() < 1) {
throw new SQLException(
Messages.get("error.generic.badparam",
catalog,
"catalog"),
"3D000");
}
String sql = tdsVersion >= Driver.TDS70
? ("use [" + catalog + ']') : "use " + catalog;
baseTds.submitSQL(sql);
}
public DatabaseMetaData getMetaData() throws SQLException {
checkOpen();
return new JtdsDatabaseMetaData(this);
}
public SQLWarning getWarnings() throws SQLException {
checkOpen();
return messages.getWarnings();
}
public Savepoint setSavepoint() throws SQLException {
checkOpen();
notImplemented("Connection.setSavepoint()");
return null;
}
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
checkOpen();
notImplemented("Connection.releaseSavepoint(Savepoint)");
}
public void rollback(Savepoint savepoint) throws SQLException {
checkOpen();
notImplemented("Connection.rollback(Savepoint)");
}
public Statement createStatement() throws SQLException {
checkOpen();
return createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_READ_ONLY);
}
synchronized public Statement createStatement(int type, int concurrency)
throws SQLException {
checkOpen();
JtdsStatement stmt = new JtdsStatement(this, type, concurrency);
addStatement(stmt);
return stmt;
}
public Statement createStatement(int type, int concurrency, int holdability)
throws SQLException {
checkOpen();
setHoldability(holdability);
return createStatement(type, concurrency);
}
public Map getTypeMap() throws SQLException {
checkOpen();
return new HashMap();
}
public void setTypeMap(Map map) throws SQLException {
checkOpen();
notImplemented("Connection.setTypeMap(Map)");
}
public String nativeSQL(String sql) throws SQLException {
checkOpen();
if (sql == null || sql.length() == 0) {
throw new SQLException(Messages.get("error.generic.nosql"), "HY000");
}
String[] result = SQLParser.parse(sql, new ArrayList(), this, false);
return result[0];
}
public CallableStatement prepareCall(String sql) throws SQLException {
checkOpen();
return prepareCall(sql,
java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_READ_ONLY);
}
synchronized public CallableStatement prepareCall(String sql, int type,
int concurrency)
throws SQLException {
checkOpen();
if (sql == null || sql.length() == 0) {
throw new SQLException(Messages.get("error.generic.nosql"), "HY000");
}
JtdsCallableStatement stmt = new JtdsCallableStatement(this,
sql,
type,
concurrency);
addStatement(stmt);
return stmt;
}
public CallableStatement prepareCall(
String sql,
int type,
int concurrency,
int holdability)
throws SQLException {
checkOpen();
setHoldability(holdability);
return prepareCall(sql, type, concurrency);
}
public PreparedStatement prepareStatement(String sql)
throws SQLException {
checkOpen();
return prepareStatement(sql,
java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_READ_ONLY);
}
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
throws SQLException {
checkOpen();
if (sql == null || sql.length() == 0) {
throw new SQLException(Messages.get("error.generic.nosql"), "HY000");
}
if (autoGeneratedKeys != JtdsStatement.RETURN_GENERATED_KEYS &&
autoGeneratedKeys != JtdsStatement.NO_GENERATED_KEYS) {
throw new SQLException(
Messages.get("error.generic.badoption",
Integer.toString(autoGeneratedKeys),
"autoGeneratedKeys"),
"HY092");
}
JtdsPreparedStatement stmt = new JtdsPreparedStatement(this,
sql,
java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_READ_ONLY,
autoGeneratedKeys == JtdsStatement.RETURN_GENERATED_KEYS);
addStatement(stmt);
return stmt;
}
synchronized public PreparedStatement prepareStatement(String sql,
int type,
int concurrency)
throws SQLException {
checkOpen();
if (sql == null || sql.length() == 0) {
throw new SQLException(Messages.get("error.generic.nosql"), "HY000");
}
JtdsPreparedStatement stmt = new JtdsPreparedStatement(this,
sql,
type,
concurrency,
false);
addStatement(stmt);
return stmt;
}
public PreparedStatement prepareStatement(
String sql,
int type,
int concurrency,
int holdability)
throws SQLException {
checkOpen();
setHoldability(holdability);
return prepareStatement(sql, type, concurrency);
}
public PreparedStatement prepareStatement(String sql, int[] columnIndexes)
throws SQLException {
if (columnIndexes == null) {
throw new SQLException(
Messages.get("error.generic.nullparam", "prepareStatement"),"HY092");
} else if (columnIndexes.length != 1) {
throw new SQLException(
Messages.get("error.generic.needcolindex", "prepareStatement"),"HY092");
}
return prepareStatement(sql, JtdsStatement.RETURN_GENERATED_KEYS);
}
public Savepoint setSavepoint(String name) throws SQLException {
checkOpen();
notImplemented("Connection.setSavepoint(String)");
return null;
}
public PreparedStatement prepareStatement(String sql, String[] columnNames)
throws SQLException {
if (columnNames == null) {
throw new SQLException(
Messages.get("error.generic.nullparam", "prepareStatement"),"HY092");
} else if (columnNames.length != 1) {
throw new SQLException(
Messages.get("error.generic.needcolname", "prepareStatement"),"HY092");
}
return prepareStatement(sql, JtdsStatement.RETURN_GENERATED_KEYS);
}
/**
* Releases all savepoints. Used internally when committing or rolling back
* a transaction.
*/
void clearSavepoints() {
}
/////// JDBC4 demarcation, do NOT put any JDBC3 code below this line ///////
/* (non-Javadoc)
* @see java.sql.Connection#createArrayOf(java.lang.String, java.lang.Object[])
*/
public Array createArrayOf(String typeName, Object[] elements)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Connection#createBlob()
*/
public Blob createBlob() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Connection#createClob()
*/
public Clob createClob() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Connection#createNClob()
*/
public NClob createNClob() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Connection#createSQLXML()
*/
public SQLXML createSQLXML() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Connection#createStruct(java.lang.String, java.lang.Object[])
*/
public Struct createStruct(String typeName, Object[] attributes)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Connection#getClientInfo()
*/
public Properties getClientInfo() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Connection#getClientInfo(java.lang.String)
*/
public String getClientInfo(String name) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Connection#isValid(int)
*/
public boolean isValid(int timeout) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Connection#setClientInfo(java.util.Properties)
*/
public void setClientInfo(Properties properties)
throws SQLClientInfoException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Connection#setClientInfo(java.lang.String, java.lang.String)
*/
public void setClientInfo(String name, String value)
throws SQLClientInfoException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#isWrapperFor(java.lang.Class)
*/
public boolean isWrapperFor(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#unwrap(java.lang.Class)
*/
public Object unwrap(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/ProcEntry.java 0000644 0001750 0001750 00000011605 11316672660 025673 0 ustar martin martin //jTDS JDBC Driver for Microsoft SQL Server and Sybase
//Copyright (C) 2004 The jTDS Project
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
/**
* Stores information about a cached stored procedure or statement handle.
*
* @version $Id: ProcEntry.java,v 1.1 2005/05/25 09:24:03 alin_sinpalean Exp $
*/
public class ProcEntry {
/** The entry references a stored procedure. */
public static final int PROCEDURE = 1;
/** The entry references a prepared statement handle. */
public static final int PREPARE = 2;
/** The entry references a prepared cursor handle. */
public static final int CURSOR = 3;
/** The entry references a failed prepare. */
public static final int PREP_FAILED = 4;
/** Stored procedure name or statement handle. */
private String name;
/** Column meta data (Sybase only). */
private ColInfo[] colMetaData;
/** Parameter meta data (Sybase only). */
private ParamInfo[] paramMetaData;
/** Type of statement referenced by this entry. */
private int type;
/** Usage count for this statement. */
private int refCount;
/**
* Retrieves the procedure or handle name.
*
* @return the statement or handle name as a String
*/
public final String toString() {
return name;
}
/**
* Sets the procedure name.
*
* @param name the procedure name
*/
public void setName(String name) {
this.name = name;
}
/**
* Sets the prepared statement handle.
*
* @param handle the sp_prepare handle value
*/
public void setHandle(int handle) {
this.name = Integer.toString(handle);
}
/**
* Retrieves the column meta data array.
*
* @return the column meta data as ColInfo[]
*/
public ColInfo[] getColMetaData() {
return this.colMetaData;
}
/**
* Sets the column meta data.
*
* @param colMetaData the column meta data
*/
public void setColMetaData(ColInfo[] colMetaData) {
this.colMetaData = colMetaData;
}
/**
* Retrieves the parameter meta data array.
*
* @return the parameter meta data as a ParamInfo[]
*/
public ParamInfo[] getParamMetaData() {
return this.paramMetaData;
}
/**
* Sets the parameter meta data.
*
* @param paramMetaData the parameter meta data array
*/
public void setParamMetaData(ParamInfo[] paramMetaData) {
this.paramMetaData = paramMetaData;
}
/**
* Sets the statement implementation type.
*
* @param type the type code (one of PROCEDURE,PREPARE,CURSOR)
*/
public void setType(int type) {
this.type = type;
}
/**
* Retrieves the statement implementation type.
*
* @return the statement type as an int
*/
public int getType() {
return this.type;
}
/**
* Retrieves the SQL to drop this statement.
*/
public void appendDropSQL(StringBuffer sql) {
switch (type) {
case PROCEDURE:
sql.append("DROP PROC ").append(name).append('\n');
break;
case PREPARE:
sql.append("EXEC sp_unprepare ").append(name).append('\n');
break;
case CURSOR:
sql.append("EXEC sp_cursorunprepare ").append(name).append('\n');
break;
case PREP_FAILED:
break;
default:
throw new IllegalStateException("Invalid cached statement type " + type);
}
}
/**
* Increments the usage count.
*/
public void addRef() {
refCount++;
}
/**
* Decrements the usage count.
*/
public void release() {
if (refCount > 0) {
refCount--;
}
}
/**
* Retreives the usage count.
*
* @return the usage count as an int
*/
public int getRefCount() {
return refCount;
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/Messages.properties 0000644 0001750 0001750 00000036374 11316672660 027002 0 ustar martin martin prop.appname=APPNAME
prop.batchsize=BATCHSIZE
prop.bindaddress=BINDADDRESS
prop.buffermaxmemory=bufferMaxMemory
prop.bufferminpackets=bufferMinPackets
prop.cachemetadata=CACHEMETADATA
prop.charset=CHARSET
prop.databasename=DATABASENAME
prop.domain=DOMAIN
prop.instance=INSTANCE
prop.language=LANGUAGE
prop.lastupdatecount=LASTUPDATECOUNT
prop.lobbuffer=LOBBUFFER
prop.logfile=LOGFILE
prop.logintimeout=LOGINTIMEOUT
prop.macaddress=MACADDRESS
prop.maxstatements=MAXSTATEMENTS
prop.namedpipe=NAMEDPIPE
prop.packetsize=PACKETSIZE
prop.password=PASSWORD
prop.portnumber=PORTNUMBER
prop.preparesql=PREPARESQL
prop.progname=PROGNAME
prop.servername=SERVERNAME
prop.servertype=SERVERTYPE
prop.sotimeout=SOCKETTIMEOUT
prop.sokeepalive=SOCKETKEEPALIVE
prop.processid=PROCESSID
prop.ssl=SSL
prop.tcpnodelay=TCPNODELAY
prop.tds=TDS
prop.bufferdir=BUFFERDIR
prop.usecursors=USECURSORS
prop.usejcifs=USEJCIFS
prop.uselobs=USELOBS
prop.user=USER
prop.useunicode=SENDSTRINGPARAMETERSASUNICODE
prop.wsid=WSID
prop.xaemulation=XAEMULATION
prop.usentlmv2=USENTLMV2
prop.desc.appname=The application name advertised by the driver.
prop.desc.batchsize=The number of statements to submit at once. Batches are broken up in pieces this large.
prop.desc.bindaddress=The IP address of the local interface that jTDS should bind to when connecting to a database via TCP/IP.
prop.desc.buffermaxmemory=The global buffer memory limit for all connections (in kilobytes).
prop.desc.bufferminpackets=The minimum number of packets per statement to buffer to memory.
prop.desc.cachemetadata=Set to true to enable the caching of column meta data for prepared statements.
prop.desc.charset=Server character set for non-Unicode character values.
prop.desc.databasename=The database name.
prop.desc.domain=The domain used for authentication.
prop.desc.instance=The database server instance.
prop.desc.language=The language for server messages.
prop.desc.lastupdatecount=Return only the last update count on executeUpdate.
prop.desc.lobbuffer=The amount of LOB data to buffer in memory before caching to disk.
prop.desc.logfile=Set the name of a file for the capture of logging information.
prop.desc.logintimeout=The time to wait for a successful login before timing out.
prop.desc.macaddress=Hex-encoded client MAC address.
prop.desc.maxstatements=The maximum number of statements to keep open. This is only a target for the cache.
prop.desc.namedpipe=Use named pipes to connect instead of TCP/IP sockets.
prop.desc.packetsize=The network packet size (a multiple of 512).
prop.desc.password=The database password.
prop.desc.portnumber=The database server port number.
prop.desc.preparesql=Use stored procedures for prepared statements.
prop.desc.progname=The program name advertised by the driver.
prop.desc.servername=The database server hostname.
prop.desc.servertype=The type of database (1 is SQL Server, 2 is Sybase).
prop.desc.sotimeout=The TCP/IP socket timeout value in seconds or 0 for no timeout.
prop.desc.sokeepalive=Use TCP/IP socket keep alive feature.
prop.desc.processid=The process ID reported by the driver.
prop.desc.ssl=Set the SSL level.
prop.desc.tcpnodelay=Enable/disable TCP_NODELAY
prop.desc.tds=The database server protocol.
prop.desc.bufferdir=The directory to buffer data to.
prop.desc.usecursors=Use SQL Server fast forward only result sets for forward only result sets.
prop.desc.usejcifs=Force use of jCIFS library on Windows for connecting via named pipes.
prop.desc.uselobs=Map large types (IMAGE and TEXT/NTEXT) to LOBs vs. String/byte[].
prop.desc.user=The database user.
prop.desc.useunicode=If strings should be sent as unicode values.
prop.desc.wsid=Workstation ID or client host name override. Will be stored in master.dbo.sysprocesses, column hostname.
prop.desc.xaemulation=Set to false to use the Microsoft Distributed Transaction Coordinator.
prop.desc.usentlmv2=Set to true to send LMv2/NTLMv2 responses when using Windows authentication
error.baddatatype=The TDS protocol does not support JDBC datatype {0}.
error.baddbname=The database name ''{0}'' is invalid.
error.badoption=The supplied parameter value ''{0}'' is invalid.
error.bintoolong=Sybase does not support binary parameters > 255 bytes.
error.blob.badpattern=The search pattern cannot be null.
error.blob.badstart=The start position must be >= 1.
error.blob.bytesnull=The bytes value must not be null.
error.blobclob.badlen=The length must be >= 0.
error.blobclob.badoffset=The offset must be >= 0 and less than the array length.
error.blobclob.badpos=The start position must be >= 1.
error.blobclob.badposlen=The start position is beyond the end of the data.
error.blobclob.lentoolong=The value of length exceeds that of the available data.
error.blobclob.readlen=The amount of data read from the stream is not = length.
error.callable.noparam=Parameter ''{0}'' not found in the parameter list.
error.callable.outparamnotset=Output parameters have not yet been processed. Call getMoreResults().
error.callable.notoutput=Parameter ''{0}'' not registered as output parameter. Call registerOutParameter().
error.charset.invalid=Charset {0}/{1} is not supported by the JVM.
error.charset.nomapping=Could not find a Java charset equivalent to DB charset {0}.
error.charset.nocollation=Could not find a Java charset equivalent to collation {0}.
error.chartoolong=Sybase does not support char parameters > 255 bytes.
error.clob.searchnull=The search string must not be null.
error.clob.strnull=The string value myst not be null.
error.connection.badhost=Unknown server host name ''{0}''.
error.connection.badprop=The {0} connection property is invalid.
error.connection.badsavep=savepoint is not valid for this transaction.
error.connection.badxaop=Calls to the {0} method are not allowed in an XA transaction.
error.connection.autocommit={0}() should not be called while in auto-commit mode.
error.connection.dbmismatch=Client {0} / Server {1} old database mismatch.
error.connection.ioerror=Network error IOException: {0}
error.connection.nohost=The serverName property has not been set.
error.connection.savenorollback=Savepoints cannot be rolled back in auto-commit mode.
error.connection.savenoset=Savepoints cannot be set in auto-commit mode.
error.connection.savenullname=Savepoint name cannot be null.
error.connection.servertype=The value of the serverType property is invalid: {0}
error.connection.sso=Single-Sign-On is only supported on Windows. Please specify a user name.
error.connection.timeout=Login timed out.
error.conproxy.noconn="Connection has been returned to pool and this reference is no longer valid.
error.convert.numericoverflow=Numeric overflow in conversion of value {0} to type {1}.
error.convert.badnumber=The value supplied cannot be converted to {0}.
error.convert.badtypeconst=Unable to convert value to {0}.
error.convert.badtypes=Unable to convert between {0} and {1}.
error.cursoropen.fail=Cursor failed to open.
error.datetime.range=Only dates between January 1, 1753 and December 31, 9999 are accepted.
error.datetime.range.era=Only dates in the AD era are accepted.
error.dbmeta.nouser=Unable to determine the user name.
error.driver.badurl=The syntax of the connection URL ''{0}'' is invalid.
error.generic.badoption=Invalid option value ''{0}'' for parameter {1}.
error.generic.badparam=Invalid value ''{0}'' for parameter {1}.
error.generic.badscale=The decimal scale must be >= 0 and <= 28.
error.generic.badtype=Invalid java.sql.Types constant value {0} passed to set or update method.
error.generic.cancelled=Cancel has been invoked on this {0}.
error.generic.closed=Invalid state, the {0} object is closed.
error.generic.encoding=Unexpected encoding exception: {0}
error.generic.ioerror=I/O Error: {0}
error.generic.ioread=I/O Error reading {0}: {1}
error.generic.iowrite=I/O Error writing {0}: {1}
error.generic.needcolindex=The column indexes parameter should be int[1].
error.generic.needcolname=The column names parameter should be String[1].
error.generic.nosql=The SQL statement must not be null or empty.
error.generic.notimp=The {0} method is not implemented.
error.generic.notsup=Use of the {0} method is not supported on this type of statement.
error.generic.nullparam=Null not permitted as parameter of method {0}
error.generic.optltzero=The {0} method requires a parameter value >= 0.
error.generic.optvalue=The {0} option is not currently supported by the {1} method.
error.generic.tdserror=TDS Protocol error: {0}
error.generic.timeout=The query has timed out.
error.generic.truncmbcs=MBCS Parameter truncated.
error.jdbcx.conclosed=The pooled connection is closed.
error.msinfo.badinfo=Unable to get information from SQL Server: {0}.
error.msinfo.badinst=Server {0} has no instance named {1}.
error.msinfo.badport=Could not parse instance port number ''{0}''.
error.nooption=The {0} option is not supported.
error.normalize.lobtoobig=The LOB length is greater than 2,147,483,647.
error.normalize.numtoobig=BigDecimal value has more than {0} digits of precision.
error.notimplemented=Method {0} is not implemented.
error.parsesql.mustbe=Invalid JDBC escape syntax at line position {0} ''{1}'' character expected.
error.parsesql.badesc=Unrecognized SQL escape ''{0}'' at line position {1}.
error.parsesql.missing=Invalid SQL statement or JDBC escape, terminating ''{0}'' not found.
error.parsesql.syntax=Invalid JDBC {0} escape at line position {1}.
error.parsesql.toomanyparams=Prepared or callable statement has more than {0} parameter markers.
error.parsesql.unexpectedparam=Unexpected parameter marker at position {0}.
error.prepare.nooutparam=Output parameter not allowed as argument list prevents use of RPC.
error.prepare.nosql=The prepared statement parameter must contain a valid SQL statement.
error.prepare.paramindex=Invalid parameter index {0}.
error.prepare.paramnotset=Parameter #{0} has not been set.
error.prepare.prepfailed=Preparing the statement failed: {0}
error.resultset.badurl=The URL ''{0}'' is invalid.
error.resultset.colindex=Invalid column index {0}.
error.resultset.colname=Invalid column name {0}.
error.resultset.cursorfail=Cursor operation failed.
error.resultset.delete=Non-null row provided to delete operation.
error.resultset.fwdonly=ResultSet may only be accessed in a forward direction.
error.resultset.insert=Column {0} / {1} is read-only.
error.resultset.insrow=The cursor is on the insert row.
error.resultset.longblob=Blob lengths greater than 2,147,483,647 are not suported.
error.resultset.longclob=Clob lengths greater than 2,147,483,647 are not suported.
error.resultset.noposupdate=Positioned update not supported.
error.resultset.norow=No current row in the ResultSet.
error.resultset.notinsrow=The cursor is not on the insert row.
error.resultset.openfail=Unable to open the specified type of cursor.
error.resultset.readonly=ResultSet is read only.
error.resultset.streamerror=setBinaryStream: IO-Exception occured reading Stream: {0}
error.resultset.streamlen=SetBinaryStream parameterized Length: {0} got length: {1}.
error.resultset.streamlen2=SetBinaryStream parameterized Length: {0} got more than that.
error.resultset.update=Null row provided to insert/update operation.
error.resultset.updatefail=Update row failed. unable to locate row to update in table.
error.resultset.deletefail=Delete row failed. Unable to locate row to delete in table.
error.resultset.insertfail=Insert row failed.
error.savepoint.named=This is a named savepoint.
error.savepoint.unnamed=This is an unnamed savepoint.
error.ssl.encryptionoff=Encryption is not enabled at the server.
error.statement.badbatch=Unable to execute batch of type {0}.
error.statement.badsql=The SQL statement must not contain a procedure call or parameter markers.
error.statement.batchnocount=A statement attempted to return a result set in executeBatch().
error.statement.gtmaxrows=The requested fetch size is greater than the maximum number of rows.
error.statement.needcolindex=One valid column index must be supplied.
error.statement.needcolname=One valid column name must be supplied.
error.statement.nocount=The executeUpdate method must not return a result set.
error.statement.nodata=There are no results to process.
error.statement.noresult=The executeQuery method must return a result set.
error.textoutparam=Output parameters must not have a type of text, ntext or image.
error.tdscore.badlen=Unable to determine the length of text or image field {0}.
error.tdscore.badtext=No table and / or column name is available for this text or image column.
error.tdscore.notextptr=There is no text pointer available for text or image column {0}.
error.update.results=executeUpdate() must not return a result set.
error.xaexception.xaerunknown=The XA resource manager has reported an unknown error.
error.xaexception.xarbrollback=XA_RBROLLBACK: The rollback was caused by an unspecified reason.
error.xaexception.xarbcommfail=XA_RBCOMMFAIL: The rollback was caused by a communication failure.
error.xaexception.xarbdeadlock=XA_RBDEADLOCK: A deadlock was detected.
error.xaexception.xarbintegrity=XA_RBINTEGRITY: A condition that violates the integrity of the resources was detected.
error.xaexception.xarbother=XA_RBOTHER: The resource manager rolled back the transaction branch for an unknown reason.
error.xaexception.xarbproto=XA_RBPROTO: A protocol error occurred in the resource manager.
error.xaexception.xarbtimeout=XA_RBTIMEOUT: A transaction branch took too long.
error.xaexception.xarbtransient=XA_RBTRANSIENT: TM may retry the transaction branch.
error.xaexception.xanomigrate=XA_NOMIGRATE: Transaction must be resumed where suspension occurred.
error.xaexception.xaheurhaz=XA_HEURHAZ: The transaction branch may have been heuristically completed.
error.xaexception.xaheurcom=XA_HEURCOM: The transaction branch has been heuristically committed.
error.xaexception.xaheurrb=XA_HEURRB: The transaction branch has been heuristically rolled back.
error.xaexception.xaheurmix=XA_HEURMIX: The transaction branch has been heuristically committed and rolled back.
error.xaexception.xaretry=XA_RETRY: Function call returned with no effect and may be reissued.
error.xaexception.xardonly=XA_RDONLY: The transaction branch was read-only and has been committed.
error.xaexception.xaerasync=XAER_ASYNC: An asynchronous operation is already outstanding.
error.xaexception.xaerrmerr=XAER_RMERR: A resource manager error occurred in the transaction branch.
error.xaexception.xaernota=XAER_NOTA: The XID does not identify a valid transaction.
error.xaexception.xaerinval=XAER_INVAL: Invalid arguments were given.
error.xaexception.xaerproto=XAER_PROTO: Function invoked in an improper context.
error.xaexception.xaerrmfail=XAER_RMFAIL: The resource manager is unavailable.
error.xaexception.xaerdupid=XAER_DUPID: The XID identifies an existing transaction.
error.xaexception.xaeroutside=XAER_OUTSIDE: The resource manager is doing work outside this transaction.
error.xasupport.badopen=The xa_open call has failed, check that the MSDTC service is available.
error.xasupport.nodist=True distributed transactions are only supported with SQL Server 2000.
error.xasupport.activetran=The connection is still enlisted in a transaction when {0} called.
warning.concurrtype=Don''t know how to handle concurrency type {0}.
warning.cursordowngraded=ResultSet type/concurrency downgraded: {0}
warning.cursortype=Don''t know how to handle cursor type {0}.
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/JtdsStatement.java 0000644 0001750 0001750 00000140267 11316672660 026546 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Types;
import java.util.ArrayList;
import java.util.LinkedList;
/**
* jTDS implementation of the java.sql.Statement interface.
*
* In the event of an IO failure the setClosed() method forces this statement
* and associated result set to close preventing the propogation of errors.
* This class includes a finalize method which increases the chances of the
* statement being closed tidly in a pooled environment where the user has
* forgotten to explicitly close the statement before it goes out of scope.
*
* @see java.sql.Statement
* @see java.sql.Connection#createStatement()
* @see java.sql.ResultSet
*
* @author Mike Hutchinson
* @version $Id: JtdsStatement.java,v 1.64.2.4 2009/12/30 08:45:34 ickzon Exp $
*/
public class JtdsStatement implements java.sql.Statement {
/*
* Constants used for backwards compatibility with JDK 1.3
*/
static final int RETURN_GENERATED_KEYS = 1;
static final int NO_GENERATED_KEYS = 2;
static final int CLOSE_CURRENT_RESULT = 1;
static final int KEEP_CURRENT_RESULT = 2;
static final int CLOSE_ALL_RESULTS = 3;
static final int BOOLEAN = 16;
static final int DATALINK = 70;
static final Integer SUCCESS_NO_INFO = new Integer(-2);
static final Integer EXECUTE_FAILED = new Integer(-3);
static final int DEFAULT_FETCH_SIZE = 100;
/** The connection owning this statement object. */
protected ConnectionJDBC2 connection;
/** The TDS object used for server access. */
protected TdsCore tds;
/** The read query timeout in seconds */
protected int queryTimeout;
/** The current ResultSet. */
protected JtdsResultSet currentResult;
/** The current update count. */
private int updateCount = -1;
/** The fetch direction for result sets. */
protected int fetchDirection = ResultSet.FETCH_FORWARD;
/** The type of result sets created by this statement. */
protected int resultSetType = ResultSet.TYPE_FORWARD_ONLY;
/** The concurrency of result sets created by this statement. */
protected int resultSetConcurrency = ResultSet.CONCUR_READ_ONLY;
/** The fetch size (default 100, only used by cursor
* ResultSets).
*/
protected int fetchSize = DEFAULT_FETCH_SIZE;
/** The cursor name to be used for positioned updates. */
protected String cursorName;
/** True if this statement is closed. */
protected boolean closed;
/** The maximum field size (not used at present). */
protected int maxFieldSize;
/** The maximum number of rows to return (not used at present). */
protected int maxRows;
/** True if SQL statements should be preprocessed. */
protected boolean escapeProcessing = true;
/** SQL Diagnostic exceptions and warnings. */
protected final SQLDiagnostic messages;
/** Batched SQL Statement array. */
protected ArrayList batchValues;
/** Dummy result set for getGeneratedKeys. */
protected JtdsResultSet genKeyResultSet;
/**
* List of queued results (update counts, possibly followed by a
* ResultSet).
*/
protected final LinkedList resultQueue = new LinkedList();
/** List of open result sets. */
protected ArrayList openResultSets;
/** The cached column meta data. */
protected ColInfo[] colMetaData;
/**
* Construct a new Statement object.
*
* @param connection The parent connection.
* @param resultSetType The result set type for example TYPE_FORWARD_ONLY.
* @param resultSetConcurrency The concurrency for example CONCUR_READ_ONLY.
*/
JtdsStatement(ConnectionJDBC2 connection,
int resultSetType,
int resultSetConcurrency) throws SQLException {
//
// This is a good point to do common validation of the result set type
//
if (resultSetType < ResultSet.TYPE_FORWARD_ONLY
|| resultSetType > ResultSet.TYPE_SCROLL_SENSITIVE + 1) {
String method;
if (this instanceof JtdsCallableStatement) {
method = "prepareCall";
} else if (this instanceof JtdsPreparedStatement) {
method = "prepareStatement";
} else {
method = "createStatement";
}
throw new SQLException(
Messages.get("error.generic.badparam",
"resultSetType",
method),
"HY092");
}
//
// Ditto for the result set concurrency
//
if (resultSetConcurrency < ResultSet.CONCUR_READ_ONLY
|| resultSetConcurrency > ResultSet.CONCUR_UPDATABLE + 2) {
String method;
if (this instanceof JtdsCallableStatement) {
method = "prepareCall";
} else if (this instanceof JtdsPreparedStatement) {
method = "prepareStatement";
} else {
method = "createStatement";
}
throw new SQLException(
Messages.get("error.generic.badparam",
"resultSetConcurrency",
method),
"HY092");
}
this.connection = connection;
this.resultSetType = resultSetType;
this.resultSetConcurrency = resultSetConcurrency;
this.tds = connection.getCachedTds();
if (this.tds == null) {
this.messages = new SQLDiagnostic(connection.getServerType());
this.tds = new TdsCore(this.connection, messages);
} else {
this.messages = tds.getMessages();
}
}
/**
* Called when this object goes out of scope to close any
* ResultSet object and this statement.
*/
protected void finalize() throws Throwable {
super.finalize();
try {
close();
} catch (SQLException e) {
// Ignore errors
}
}
/**
* Get the Statement's TDS object.
*
* @return The TDS support as a TdsCore Object.
*/
TdsCore getTds() {
return tds;
}
/**
* Get the statement's warnings list.
*
* @return The warnings list as a SQLDiagnostic.
*/
SQLDiagnostic getMessages() {
return messages;
}
/**
* Check that this statement is still open.
*
* @throws SQLException if statement closed.
*/
protected void checkOpen() throws SQLException {
if (closed || connection == null || connection.isClosed()) {
throw new SQLException(
Messages.get("error.generic.closed", "Statement"), "HY010");
}
}
/**
* Check that the exception is caused by the failure to open a
* cursor and not by a more serious SQL error.
*
* @param e the exception returned by the cursor class
* @throws SQLException if exception is not due to a cursor error
*/
protected void checkCursorException(SQLException e) throws SQLException{
if (connection == null
|| connection.isClosed()
|| "HYT00".equals(e.getSQLState())
|| "HY008".equals(e.getSQLState())) {
// Serious error or timeout so return exception to caller
throw e;
}
if (connection.getServerType() == Driver.SYBASE) {
// Allow retry for Sybase
return;
}
//
// Check cursor specific errors and ranges for SQL Server
//
int error = e.getErrorCode();
if (error >= 16900 && error <= 16999) {
// Errors in this range are all related to the cursor API.
// This is true for all versions of SQL Server.
return;
}
if (error == 6819) {
// A FOR XML clause was found
return;
}
if (error == 8654) {
// A inrow textptr exists
return;
}
if (error == 8162) {
// Formal parameter '%.*ls' was defined as OUTPUT but the actual
// parameter not declared OUTPUT. This happens when trying to
// execute a stored procedure with output parameters via a cursor.
return;
}
//
// More serious error we should rethrow the error and
// not allow the driver to re-execute sql.
//
throw e;
}
/**
* Report that user tried to call a method which has not been implemented.
*
* @param method The method name to report in the error message.
* @throws SQLException
*/
static void notImplemented(String method) throws SQLException {
throw new SQLException(
Messages.get("error.generic.notimp", method), "HYC00");
}
/**
* Close current result set (if any).
*/
void closeCurrentResultSet() throws SQLException {
try {
if (currentResult != null) {
currentResult.close();
}
// } catch (SQLException e) {
// Ignore
} finally {
currentResult = null;
}
}
/**
* Close all result sets.
*/
void closeAllResultSets() throws SQLException {
try {
if (openResultSets != null) {
for (int i = 0; i < openResultSets.size(); i++) {
JtdsResultSet rs = (JtdsResultSet) openResultSets.get(i);
if (rs != null) {
rs.close();
}
}
}
closeCurrentResultSet();
} finally {
openResultSets = null;
}
}
/**
* Add an SQLWarning object to the statment warnings list.
*
* @param w The SQLWarning to add.
*/
void addWarning(SQLWarning w) {
messages.addWarning(w);
}
/**
* Execute the SQL batch on a MS server.
*
* @param size the total size of the batch
* @param executeSize the maximum number of statements to send in one request
* @param counts the returned update counts
* @return chained exceptions linked to a SQLException
* @throws SQLException if a serious error occurs during execution
*/
protected SQLException executeMSBatch(int size, int executeSize, ArrayList counts) throws SQLException {
SQLException sqlEx = null;
for (int i = 0; i < size;) {
Object value = batchValues.get(i);
++i;
// Execute batch now if max size reached or end of batch
boolean executeNow = (i % executeSize == 0) || i == size;
tds.startBatch();
tds.executeSQL((String) value, null, null, false, 0, -1, -1, executeNow);
// If the batch has been sent, process the results
if (executeNow) {
sqlEx = tds.getBatchCounts(counts, sqlEx);
// If a serious error then we stop execution now as count
// is too small.
if (sqlEx != null && counts.size() != i) {
break;
}
}
}
return sqlEx;
}
/**
* Execute the SQL batch on a Sybase server.
*
* Sybase needs to have the SQL concatenated into one TDS language packet. This method will be overriden for
* PreparedStatements.
*
* @param size the total size of the batch
* @param executeSize the maximum number of statements to send in one request
* @param counts the returned update counts
* @return chained exceptions linked to a SQLException
* @throws SQLException if a serious error occurs during execution
*/
protected SQLException executeSybaseBatch(int size, int executeSize, ArrayList counts) throws SQLException {
StringBuffer sql = new StringBuffer(size * 32); // Make buffer reasonable size
SQLException sqlEx = null;
for (int i = 0; i < size;) {
Object value = batchValues.get(i);
++i;
// Execute batch now if max size reached or end of batch
boolean executeNow = (i % executeSize == 0) || i == size;
sql.append((String) value).append(' ');
if (executeNow) {
tds.executeSQL(sql.toString(), null, null, false, 0, -1, -1, true);
sql.setLength(0);
// If the batch has been sent, process the results
sqlEx = tds.getBatchCounts(counts, sqlEx);
// If a serious error or a server error then we stop
// execution now as count is too small.
if (sqlEx != null && counts.size() != i) {
break;
}
}
}
return sqlEx;
}
/**
* Executes SQL to obtain a result set.
*
* @param sql the SQL statement to execute
* @param spName optional stored procedure name
* @param params optional parameters
* @param useCursor whether a cursor should be created for the SQL
* @return the result set generated by the query
*/
protected ResultSet executeSQLQuery(String sql,
String spName,
ParamInfo[] params,
boolean useCursor)
throws SQLException {
String warningMessage = null;
//
// Try to open a cursor result set if required
//
if (useCursor) {
try {
if (connection.getServerType() == Driver.SQLSERVER) {
currentResult =
new MSCursorResultSet(this,
sql,
spName,
params,
resultSetType,
resultSetConcurrency);
return currentResult;
} else {
// Use client side cursor for Sybase
currentResult =
new CachedResultSet(this,
sql,
spName,
params,
resultSetType,
resultSetConcurrency);
return currentResult;
}
} catch (SQLException e) {
checkCursorException(e);
warningMessage = '[' + e.getSQLState() + "] " + e.getMessage();
}
}
//
// Could not open a cursor (or was not requested) so try a direct select
//
if (spName != null
&& connection.getUseMetadataCache()
&& connection.getPrepareSql() == TdsCore.PREPARE
&& colMetaData != null
&& connection.getServerType() == Driver.SQLSERVER) {
// There is cached meta data available for this
// prepared statement
tds.setColumns(colMetaData);
tds.executeSQL(sql, spName, params, true, queryTimeout, maxRows,
maxFieldSize, true);
} else {
tds.executeSQL(sql, spName, params, false, queryTimeout, maxRows,
maxFieldSize, true);
}
// Update warning chain if cursor was downgraded before processing results
if (warningMessage != null) {
addWarning(new SQLWarning(
Messages.get("warning.cursordowngraded", warningMessage), "01000"));
}
// Ignore update counts preceding the result set. All drivers seem to
// do this.
while (!tds.getMoreResults() && !tds.isEndOfResponse());
// check for server side errors
messages.checkErrors();
if (tds.isResultSet()) {
currentResult = new JtdsResultSet(this,
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY,
tds.getColumns());
} else {
throw new SQLException(
Messages.get("error.statement.noresult"), "24000");
}
return currentResult;
}
/**
* Executes any type of SQL.
*
* @param sql the SQL statement to execute
* @param spName optional stored procedure name
* @param params optional parameters
* @param returnKeys whether the statement returns generated keys
* @param update whether the caller is {@link #executeUpdate}
* @param useCursor whether the requested result set type or concurrency
* or connection properties request usage of a cursor
* @return true if the first result is a result set
* @throws SQLException if an error condition occurs
*/
protected boolean executeSQL(String sql,
String spName,
ParamInfo[] params,
boolean returnKeys,
boolean update,
boolean useCursor)
throws SQLException {
String warningMessage = null;
//
// For SQL Server, try to open a cursor result set if required
// (and possible).
//
if (connection.getServerType() == Driver.SQLSERVER && !update && useCursor) {
try {
currentResult = new MSCursorResultSet(this, sql, spName,
params, resultSetType, resultSetConcurrency);
return true;
} catch (SQLException e) {
checkCursorException(e);
warningMessage = '[' + e.getSQLState() + "] " + e.getMessage();
}
}
//
// We are talking to a Sybase server or we could not open a cursor
// or we did not have a SELECT so just execute the SQL normally.
//
tds.executeSQL(sql, spName, params, false, queryTimeout, maxRows,
maxFieldSize, true);
if (warningMessage != null) {
// Update warning chain if cursor was downgraded
addWarning(new SQLWarning(Messages.get(
"warning.cursordowngraded", warningMessage), "01000"));
}
if (processResults(returnKeys, update)) {
Object nextResult = resultQueue.removeFirst();
// Next result is an update count
if (nextResult instanceof Integer) {
updateCount = ((Integer) nextResult).intValue();
return false;
}
// Next result is a ResultSet. Set currentResult and remove it.
currentResult = (JtdsResultSet) nextResult;
return true;
} else {
return false;
}
}
/**
* Queue up update counts into {@link #resultQueue} until the end of the
* response is reached or a ResultSet is encountered. Calling
* processResults while a ResultSet is open will
* not close it, but will consume all remaining rows.
*
* @param returnKeys true if a generated keys
* ResultSet is expected
* @param update true if the method is called from within
* executeUpdate
* @return true if there are any results,
* false otherwise
* @throws SQLException if an error condition occurs
*/
private boolean processResults(boolean returnKeys, boolean update) throws SQLException {
if (!resultQueue.isEmpty()) {
throw new IllegalStateException(
"There should be no queued results.");
}
while (!tds.isEndOfResponse()) {
if (!tds.getMoreResults()) {
if (tds.isUpdateCount()) {
if (update && connection.getLastUpdateCount()) {
resultQueue.clear();
}
resultQueue.addLast(new Integer(tds.getUpdateCount()));
}
} else {
if (returnKeys) {
// This had better be the generated key
// FIXME We could use SELECT @@IDENTITY AS jTDS_SOMETHING and check the column name to make sure
if (tds.getNextRow()) {
genKeyResultSet = new CachedResultSet(this,
tds.getColumns(),
tds.getRowData());
}
} else {
if (update && resultQueue.isEmpty()) {
// Throw exception but queue up any previous ones
SQLException ex = new SQLException(
Messages.get("error.statement.nocount"), "07000");
ex.setNextException(messages.exceptions);
throw ex;
}
resultQueue.add(new JtdsResultSet(
this,
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY,
tds.getColumns()));
break;
}
}
}
// Check for server side errors
getMessages().checkErrors();
return !resultQueue.isEmpty();
}
/**
* Cache as many results as possible (up to the first
* ResultSet). Called by ResultSets when the
* end is reached.
*/
protected void cacheResults() throws SQLException {
// Cache results
processResults(false, false);
}
/**
* Initialize the Statement, by cleaning up all queued and
* unprocessed results. Called by all execute methods.
*
* @throws SQLException if an error occurs
*/
protected void initialize() throws SQLException {
updateCount = -1;
resultQueue.clear();
genKeyResultSet = null;
tds.clearResponseQueue();
// FIXME Should old exceptions found now be thrown instead of lost?
messages.exceptions = null;
messages.clearWarnings();
closeAllResultSets();
}
/**
* Implements the common functionality for plain statement {@link #execute}
* and {#link #executeUpdate}: basic checks, cleaning up of previous
* results, setting up and executing the query and loading the first
* results.
*
* @param sql an SQL INSERT, UPDATE or
* DELETE statement or an SQL statement that
* returns nothing, such as an SQL DDL statement
* @param autoGeneratedKeys a flag indicating whether auto-generated keys
* should be made available for retrieval
* @param update boolean flag indicating whether the caller is
* {@link #executeUpdate} -- in this case an exception is
* thrown if the first result is not an update count and no
* cursor is created (direct execution)
* @return true if the first result is a
* ResultSet, false if it's an update
* count
* @see #execute
* @see #executeUpdate
*/
private boolean executeImpl(String sql, int autoGeneratedKeys, boolean update)
throws SQLException {
initialize();
if (sql == null || sql.length() == 0) {
throw new SQLException(Messages.get("error.generic.nosql"), "HY000");
}
boolean returnKeys;
String sqlWord = "";
if (escapeProcessing) {
String tmp[] = SQLParser.parse(sql, null, connection, false);
if (tmp[1].length() != 0) {
throw new SQLException(
Messages.get("error.statement.badsql"), "07000");
}
sql = tmp[0];
sqlWord = tmp[2];
} else {
// Escape processing turned off so
// see if we can extract "insert" from start of statement
sql = sql.trim();
if (sql.length() > 5) {
sqlWord = sql.substring(0,6).toLowerCase();
}
}
if (autoGeneratedKeys == RETURN_GENERATED_KEYS) {
returnKeys = "insert".equals(sqlWord);
} else if (autoGeneratedKeys == NO_GENERATED_KEYS) {
returnKeys = false;
} else {
throw new SQLException(
Messages.get("error.generic.badoption",
Integer.toString(autoGeneratedKeys),
"autoGeneratedKeys"),
"HY092");
}
if (returnKeys) {
if (connection.getServerType() == Driver.SQLSERVER
&& connection.getDatabaseMajorVersion() >= 8) {
sql += " SELECT SCOPE_IDENTITY() AS ID";
} else {
sql += " SELECT @@IDENTITY AS ID";
}
}
return executeSQL(sql, null, null, returnKeys, update,
!update && useCursor(returnKeys, sqlWord));
}
/**
* Determines whether a cursor should be used based on the requested result
* set type and concurrency, whether a cursor name has been set, the
* useCursors connection property has been set, the first
* word in the SQL query is either SELECT or EXEC/EXECUTE and no generated
* keys are returned.
*
* @param returnKeys indicates whether keys will be returned by the query
* @param sqlWord the first word in the SQL query; can be
* null if the caller is
* {@link #executeQuery}
* @return true if a cursor should be used, false
* if not
*/
protected boolean useCursor(boolean returnKeys, String sqlWord) {
return (resultSetType != ResultSet.TYPE_FORWARD_ONLY
|| resultSetConcurrency != ResultSet.CONCUR_READ_ONLY
|| connection.getUseCursors()
|| cursorName != null)
&& !returnKeys
&& (sqlWord == null || "select".equals(sqlWord) || sqlWord.startsWith("exec"));
}
/**
* Retrieve the default fetch size for this statement.
*
* @return the default fetch size for a new ResultSet
*/
int getDefaultFetchSize() {
return (0 < this.maxRows && this.maxRows < DEFAULT_FETCH_SIZE)
? this.maxRows : DEFAULT_FETCH_SIZE;
}
// ------------------ java.sql.Statement methods ----------------------
public int getFetchDirection() throws SQLException {
checkOpen();
return this.fetchDirection;
}
public int getFetchSize() throws SQLException {
checkOpen();
return this.fetchSize;
}
public int getMaxFieldSize() throws SQLException {
checkOpen();
return this.maxFieldSize;
}
public int getMaxRows() throws SQLException {
checkOpen();
return this.maxRows;
}
public int getQueryTimeout() throws SQLException {
checkOpen();
return this.queryTimeout;
}
public int getResultSetConcurrency() throws SQLException {
checkOpen();
return this.resultSetConcurrency;
}
public int getResultSetHoldability() throws SQLException {
checkOpen();
return JtdsResultSet.HOLD_CURSORS_OVER_COMMIT;
}
public int getResultSetType() throws SQLException {
checkOpen();
return resultSetType;
}
public int getUpdateCount() throws SQLException {
checkOpen();
return updateCount;
}
public void cancel() throws SQLException {
checkOpen();
if (tds != null) {
tds.cancel(false);
}
}
public void clearBatch() throws SQLException {
checkOpen();
if (batchValues != null) {
batchValues.clear();
}
}
public void clearWarnings() throws SQLException {
checkOpen();
messages.clearWarnings();
}
public void close() throws SQLException {
if (!closed) {
SQLException closeEx = null;
try {
closeAllResultSets();
} catch (SQLException ex) {
if (!"HYT00".equals(ex.getSQLState())
&& !"HY008".equals(ex.getSQLState())) {
// Only throw exceptions not caused by cancels or timeouts
closeEx = ex;
}
} finally {
SQLException releaseEx = null;
try {
if (!connection.isClosed()) {
connection.releaseTds(tds);
}
// Check for server side errors
tds.getMessages().checkErrors();
} catch (SQLException ex) {
// Remember any exception thrown
releaseEx = ex;
// Queue up any result set close exceptions
if (closeEx != null) {
releaseEx.setNextException(closeEx);
}
} finally {
// Clean up everything
closed = true;
tds = null;
connection.removeStatement(this);
connection = null;
// Re-throw any caught exception
if (releaseEx != null) {
throw releaseEx;
}
}
}
// Throw any exception caught during result set close
if (closeEx != null) {
throw closeEx;
}
}
}
public boolean getMoreResults() throws SQLException {
checkOpen();
return getMoreResults(CLOSE_ALL_RESULTS);
}
/**
* Execute batch of SQL Statements.
*
* The JDBC3 standard says that the behavior of this method must be
* consistent for any DBMS. As Sybase (and to a lesser extent SQL Server)
* will sometimes continue after a batch execution error, the only way to
* comply with the standard is to always return an array of update counts
* the same size as the batch list. Slots in the array beyond the last
* executed statement are set to EXECUTE_FAILED.
*
* There is a problem with certain statements, returning more update counts
* than there are batch operations. (see bug [])
*
* @return update counts as an int[]
*/
public int[] executeBatch()
throws SQLException, BatchUpdateException {
checkOpen();
initialize();
if (batchValues == null || batchValues.size() == 0) {
return new int[0];
}
int size = batchValues.size();
int executeSize = connection.getBatchSize();
executeSize = (executeSize == 0) ? Integer.MAX_VALUE : executeSize;
SQLException sqlEx;
ArrayList counts = new ArrayList(size);
try {
// Lock the connection, making sure the batch executes atomically. This is especially important in the
// case of prepared statement batches (where we don't want the prepares rolled back before being executed)
// but should also provide some level of sanity in the general case.
synchronized (connection) {
if (connection.getServerType() == Driver.SYBASE
&& connection.getTdsVersion() == Driver.TDS50) {
sqlEx = executeSybaseBatch(size, executeSize, counts);
} else {
sqlEx = executeMSBatch(size, executeSize, counts);
}
}
// Ensure array is the same size as the original statement list
int updateCounts[] = new int[size];
// Copy the update counts into the int array
int results = counts.size();
for (int i = 0; i < results && i < size; i++) {
updateCounts[i] = ((Integer) counts.get(i)).intValue();
}
// Pad any remaining slots with EXECUTE_FAILED
for (int i = results; i < updateCounts.length; i++) {
updateCounts[i] = EXECUTE_FAILED.intValue();
}
// See if we should return an exception
if (sqlEx != null) {
BatchUpdateException batchEx =
new BatchUpdateException(sqlEx.getMessage(),
sqlEx.getSQLState(),
sqlEx.getErrorCode(),
updateCounts);
// Chain any other exceptions
batchEx.setNextException(sqlEx.getNextException());
throw batchEx;
}
return updateCounts;
} catch (BatchUpdateException ex) {
// If it's a BatchUpdateException let it go
throw ex;
} catch (SQLException ex) {
// An SQLException can only occur while sending the batch
// (getBatchCounts() doesn't throw SQLExceptions), so we have to
// end the batch and return the partial results
// FIXME What should we send here to flush out the batch?
// Come to think of it, is there any circumstance under which this
// could actually happen without the connection getting closed?
// No counts will have been returned either as last packet will not
// have been sent.
throw new BatchUpdateException(ex.getMessage(), ex.getSQLState(),
ex.getErrorCode(), new int[0]);
} finally {
clearBatch();
}
}
public void setFetchDirection(int direction) throws SQLException {
checkOpen();
switch (direction) {
case ResultSet.FETCH_UNKNOWN:
case ResultSet.FETCH_REVERSE:
case ResultSet.FETCH_FORWARD:
this.fetchDirection = direction;
break;
default:
throw new SQLException(
Messages.get("error.generic.badoption",
Integer.toString(direction),
"direction"),
"24000");
}
}
public void setFetchSize(int rows) throws SQLException {
checkOpen();
if (rows < 0) {
throw new SQLException(
Messages.get("error.generic.optltzero", "setFetchSize"),
"HY092");
} else if (maxRows > 0 && rows > maxRows) {
throw new SQLException(
Messages.get("error.statement.gtmaxrows"), "HY092");
}
if (rows == 0) {
rows = getDefaultFetchSize();
}
this.fetchSize = rows;
}
public void setMaxFieldSize(int max) throws SQLException {
checkOpen();
if (max < 0) {
throw new SQLException(
Messages.get("error.generic.optltzero", "setMaxFieldSize"),
"HY092");
}
maxFieldSize = max;
}
public void setMaxRows(int max) throws SQLException {
checkOpen();
if (max < 0) {
throw new SQLException(
Messages.get("error.generic.optltzero", "setMaxRows"),
"HY092");
}
if (max > 0 && max < this.fetchSize) {
// Just for consistency with setFetchSize()
this.fetchSize = max;
}
this.maxRows = max;
}
public void setQueryTimeout(int seconds) throws SQLException {
checkOpen();
if (seconds < 0) {
throw new SQLException(
Messages.get("error.generic.optltzero", "setQueryTimeout"),
"HY092");
}
this.queryTimeout = seconds;
}
public boolean getMoreResults(int current) throws SQLException {
checkOpen();
switch (current) {
case CLOSE_ALL_RESULTS:
updateCount = -1;
closeAllResultSets();
break;
case CLOSE_CURRENT_RESULT:
updateCount = -1;
closeCurrentResultSet();
break;
case KEEP_CURRENT_RESULT:
updateCount = -1;
// If there is an open result set it is transferred to
// the list of open result sets. For JtdsResultSet
// result sets we cache the remaining data. For CachedResultSet
// result sets the data is already cached.
if (openResultSets == null) {
openResultSets = new ArrayList();
}
if (currentResult instanceof MSCursorResultSet
|| currentResult instanceof CachedResultSet) {
// NB. Due to restrictions on the way API cursors are
// created, MSCursorResultSet can never be followed by
// any other result sets, update counts or return variables.
openResultSets.add(currentResult);
} else if (currentResult != null) {
currentResult.cacheResultSetRows();
openResultSets.add(currentResult);
}
currentResult = null;
break;
default:
throw new SQLException(
Messages.get("error.generic.badoption",
Integer.toString(current),
"current"),
"HY092");
}
// Check for server side errors
messages.checkErrors();
// Dequeue any results
if (!resultQueue.isEmpty() || processResults(false, false)) {
Object nextResult = resultQueue.removeFirst();
// Next result is an update count
if (nextResult instanceof Integer) {
updateCount = ((Integer) nextResult).intValue();
return false;
}
// Next result is a ResultSet. Set currentResult and remove it.
currentResult = (JtdsResultSet) nextResult;
return true;
} else {
return false;
}
}
public void setEscapeProcessing(boolean enable) throws SQLException {
checkOpen();
this.escapeProcessing = enable;
}
public int executeUpdate(String sql) throws SQLException {
return executeUpdate(sql, NO_GENERATED_KEYS);
}
public void addBatch(String sql) throws SQLException {
checkOpen();
if (sql == null) {
throw new NullPointerException();
}
if (batchValues == null) {
batchValues = new ArrayList();
}
if (escapeProcessing) {
String tmp[] = SQLParser.parse(sql, null, connection, false);
if (tmp[1].length() != 0) {
throw new SQLException(
Messages.get("error.statement.badsql"), "07000");
}
sql = tmp[0];
}
batchValues.add(sql);
}
public void setCursorName(String name) throws SQLException {
checkOpen();
this.cursorName = name;
if (name != null) {
// Reset statement type to JDBC 1 default.
this.resultSetType = ResultSet.TYPE_FORWARD_ONLY;
this.fetchSize = 1; // Needed for positioned updates
}
}
public boolean execute(String sql) throws SQLException {
checkOpen();
return executeImpl(sql, NO_GENERATED_KEYS, false);
}
public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
checkOpen();
executeImpl(sql, autoGeneratedKeys, true);
int res = getUpdateCount();
return res == -1 ? 0 : res;
}
public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
checkOpen();
return executeImpl(sql, autoGeneratedKeys, false);
}
public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
checkOpen();
if (columnIndexes == null) {
throw new SQLException(
Messages.get("error.generic.nullparam", "executeUpdate"),"HY092");
} else if (columnIndexes.length != 1) {
throw new SQLException(
Messages.get("error.generic.needcolindex", "executeUpdate"),"HY092");
}
return executeUpdate(sql, RETURN_GENERATED_KEYS);
}
public boolean execute(String sql, int[] columnIndexes) throws SQLException {
checkOpen();
if (columnIndexes == null) {
throw new SQLException(
Messages.get("error.generic.nullparam", "execute"),"HY092");
} else if (columnIndexes.length != 1) {
throw new SQLException(
Messages.get("error.generic.needcolindex", "execute"),"HY092");
}
return executeImpl(sql, RETURN_GENERATED_KEYS, false);
}
public Connection getConnection() throws SQLException {
checkOpen();
return this.connection;
}
public ResultSet getGeneratedKeys() throws SQLException {
checkOpen();
if (genKeyResultSet == null) {
String colNames[] = {"ID"};
int colTypes[] = {Types.INTEGER};
//
// Return an empty result set
//
CachedResultSet rs = new CachedResultSet(this, colNames, colTypes);
rs.setConcurrency(ResultSet.CONCUR_READ_ONLY);
genKeyResultSet = rs;
}
return genKeyResultSet;
}
public ResultSet getResultSet() throws SQLException {
checkOpen();
//
if (currentResult instanceof MSCursorResultSet ||
currentResult instanceof CachedResultSet) {
return currentResult;
}
//
// See if we are returning a forward read only resultset
//
if (currentResult == null ||
(resultSetType == ResultSet.TYPE_FORWARD_ONLY &&
resultSetConcurrency == ResultSet.CONCUR_READ_ONLY)) {
return currentResult;
}
//
// OK Now create a CachedResultSet based on the existng result set.
//
currentResult = new CachedResultSet(currentResult, true);
return currentResult;
}
public SQLWarning getWarnings() throws SQLException {
checkOpen();
return messages.getWarnings();
}
public int executeUpdate(String sql, String[] columnNames) throws SQLException {
checkOpen();
if (columnNames == null) {
throw new SQLException(
Messages.get("error.generic.nullparam", "executeUpdate"),"HY092");
} else if (columnNames.length != 1) {
throw new SQLException(
Messages.get("error.generic.needcolname", "executeUpdate"),"HY092");
}
return executeUpdate(sql, RETURN_GENERATED_KEYS);
}
public boolean execute(String sql, String[] columnNames) throws SQLException {
checkOpen();
if (columnNames == null) {
throw new SQLException(
Messages.get("error.generic.nullparam", "execute"),"HY092");
} else if (columnNames.length != 1) {
throw new SQLException(
Messages.get("error.generic.needcolname", "execute"),"HY092");
}
return executeImpl(sql, RETURN_GENERATED_KEYS, false);
}
public ResultSet executeQuery(String sql) throws SQLException {
checkOpen();
initialize();
if (sql == null || sql.length() == 0) {
throw new SQLException(Messages.get("error.generic.nosql"), "HY000");
}
if (escapeProcessing) {
String tmp[] = SQLParser.parse(sql, null, connection, false);
if (tmp[1].length() != 0) {
throw new SQLException(
Messages.get("error.statement.badsql"), "07000");
}
sql = tmp[0];
}
return this.executeSQLQuery(sql, null, null, useCursor(false, null));
}
/////// JDBC4 demarcation, do NOT put any JDBC3 code below this line ///////
/* (non-Javadoc)
* @see java.sql.Statement#isClosed()
*/
public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Statement#isPoolable()
*/
public boolean isPoolable() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Statement#setPoolable(boolean)
*/
public void setPoolable(boolean poolable) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#isWrapperFor(java.lang.Class)
*/
public boolean isWrapperFor(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#unwrap(java.lang.Class)
*/
public Object unwrap(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/cache/ 0000755 0001750 0001750 00000000000 11316672660 024143 5 ustar martin martin libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/cache/SimpleLRUCache.java 0000644 0001750 0001750 00000007706 11316672660 027560 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc.cache;
import java.util.HashMap;
import java.util.LinkedList;
/**
* Simple LRU cache for any type of object. Implemented as an extended
* HashMap with a maximum size and an aggregated List
* as LRU queue.
*
* @author Brett Wooldridge
* @version $Id: SimpleLRUCache.java,v 1.1 2005/04/25 11:46:56 alin_sinpalean Exp $
*/
public class SimpleLRUCache extends HashMap {
/** Maximum cache size. */
private final int maxCacheSize;
/** LRU list. */
private final LinkedList list;
/**
* Constructs a new LRU cache instance.
*
* @param maxCacheSize the maximum number of entries in this cache before
* entries are aged off
*/
public SimpleLRUCache(int maxCacheSize) {
super(maxCacheSize);
this.maxCacheSize = Math.max(0, maxCacheSize);
this.list = new LinkedList();
}
/**
* Overrides clear() to also clear the LRU list.
*/
public synchronized void clear() {
super.clear();
list.clear();
}
/**
* Overrides put() so that it also updates the LRU list.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the key
* @return previous value associated with key or null if there
* was no mapping for key; a null return can also
* indicate that the cache previously associated null
* with the specified key
* @see java.util.Map#put(Object, Object)
*/
public synchronized Object put(Object key, Object value) {
if (maxCacheSize == 0) {
return null;
}
// if the key isn't in the cache and the cache is full...
if (!super.containsKey(key) && !list.isEmpty() && list.size() + 1 > maxCacheSize) {
Object deadKey = list.removeLast();
super.remove(deadKey);
}
freshenKey(key);
return super.put(key, value);
}
/**
* Overrides get() so that it also updates the LRU list.
*
* @param key key with which the expected value is associated
* @return the value to which the cache maps the specified key, or
* null if the map contains no mapping for this key
*/
public synchronized Object get(Object key) {
Object value = super.get(key);
if (value != null) {
freshenKey(key);
}
return value;
}
/**
* @see java.util.Map#remove(Object)
*/
public synchronized Object remove(Object key) {
list.remove(key);
return super.remove(key);
}
/**
* Moves the specified value to the top of the LRU list (the bottom of the
* list is where least recently used items live).
*
* @param key key of the value to move to the top of the list
*/
private void freshenKey(Object key) {
list.remove(key);
list.addFirst(key);
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/cache/SQLCacheKey.java 0000644 0001750 0001750 00000004562 11316672660 027051 0 ustar martin martin //jTDS JDBC Driver for Microsoft SQL Server and Sybase
//Copyright (C) 2004 The jTDS Project
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc.cache;
import net.sourceforge.jtds.jdbc.ConnectionJDBC2;
/**
* Cache key for an SQL query, consisting of the query and server type, major
* and minor version.
*
* @author Brett Wooldridge
* @author Alin Sinpalean
* @version $Id: SQLCacheKey.java,v 1.2.2.1 2009/07/29 12:10:42 ickzon Exp $
*/
public class SQLCacheKey {
private final String sql;
private final int serverType;
private final int majorVersion;
private final int minorVersion;
private final int hashCode;
public SQLCacheKey(String sql, ConnectionJDBC2 connection) {
this.sql = sql;
this.serverType = connection.getServerType();
this.majorVersion = connection.getDatabaseMajorVersion();
this.minorVersion = connection.getDatabaseMinorVersion();
this.hashCode = sql.hashCode()
^ (serverType << 24 | majorVersion << 16 | minorVersion);
}
public int hashCode() {
return hashCode;
}
public boolean equals(Object object) {
try {
SQLCacheKey key = (SQLCacheKey) object;
return this.hashCode == key.hashCode
&& this.majorVersion == key.majorVersion
&& this.minorVersion == key.minorVersion
&& this.serverType == key.serverType
&& this.sql.equals(key.sql);
} catch (ClassCastException e) {
return false;
} catch (NullPointerException e) {
return false;
}
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/cache/ProcedureCache.java 0000644 0001750 0001750 00000016144 11316672660 027670 0 ustar martin martin //jTDS JDBC Driver for Microsoft SQL Server and Sybase
//Copyright (C) 2004 The jTDS Project
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc.cache;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import net.sourceforge.jtds.jdbc.ProcEntry;
/**
* LRU cache for procedures and statement handles.
*
* @version $Id: ProcedureCache.java,v 1.5 2005/07/05 16:44:25 alin_sinpalean Exp $
*/
public class ProcedureCache implements StatementCache {
/**
* Encapsulates the cached Object and implements the linked list used to
* implement the LRU logic.
*/
private static class CacheEntry {
String key;
ProcEntry value;
CacheEntry next;
CacheEntry prior;
/**
* Constructs a new cache entry encapsulating the supplied key and
* value.
*
* @param key key used to identify the cache entry
* @param value object being cached
*/
CacheEntry(String key, ProcEntry value) {
this.key = key;
this.value = value;
}
/**
* Unlinks this CacheEntry from the linked list.
*/
void unlink() {
next.prior = prior;
prior.next = next;
}
/**
* Links this CacheEntry into the linked list after the node specified.
*
* @param ce node after which this entry will be linked
*/
void link(CacheEntry ce) {
next = ce.next;
prior = ce;
next.prior = this;
ce.next = this;
}
}
/** The maximum initial HashMap size. */
private static final int MAX_INITIAL_SIZE = 50;
/** The actual cache instance. */
private HashMap cache;
/** Maximum cache size or 0 to disable. */
int cacheSize;
/** Head node of the linked list. */
CacheEntry head;
/** Tail node of the linked list. */
CacheEntry tail;
/** List of redundant cache entries. */
ArrayList free;
/**
* Constructs a new statement cache.
*
* @param cacheSize maximum cache size or 0 to disable caching
*/
public ProcedureCache(int cacheSize) {
this.cacheSize = cacheSize;
cache = new HashMap(Math.min(MAX_INITIAL_SIZE, cacheSize) + 1);
head = new CacheEntry(null, null);
tail = new CacheEntry(null, null);
head.next = tail;
tail.prior = head;
free = new ArrayList();
}
/**
* Retrieves a ProcEntry object from the cache.
*
* If the entry exists it is moved to the front of the linked list to keep
* it alive as long as possible.
*
* @param key the key value identifying the required entry
* @return the keyed entry as an Object or null if the entry
* does not exist
*/
public synchronized Object get(String key) {
CacheEntry ce = (CacheEntry) cache.get(key);
if (ce != null) {
// remove entry from linked list
ce.unlink();
// Relink at Head
ce.link(head);
// Increment usage count
ce.value.addRef();
return ce.value;
}
return null;
}
/**
* Inserts a new entry, identified by a key, into the cache.
*
* If the cache is full then one or more entries are removed and
* transferred to a list for later destruction.
*
* @param key value used to identify the entry
* @param handle proc entry to be inserted into the cache
*/
public synchronized void put(String key, Object handle) {
// Increment usage count
((ProcEntry) handle).addRef();
// Add new entry to cache
CacheEntry ce = new CacheEntry(key, (ProcEntry) handle);
cache.put(key, ce);
ce.link(head);
// See if we need to scavenge some existing entries
scavengeCache();
}
/**
* Removes a redundant entry from the cache.
*
* @param key value that identifies the cache entry
*/
public synchronized void remove(String key) {
CacheEntry ce = (CacheEntry) cache.get(key);
if (ce != null) {
// remove entry from linked list
ce.unlink();
// Remove from HashMap
cache.remove(key);
}
}
/**
* Obtains a list of statement handles or procedures that can now be
* dropped.
*
* @param handles a collection of single use statements that will be
* returned for dropping if the cache is disabled
* @return the collection of redundant statments for dropping
*/
public synchronized Collection getObsoleteHandles(Collection handles) {
if (handles != null) {
// Update the usage count for handles belonging to statements
// that are being closed.
for (Iterator iterator = handles.iterator(); iterator.hasNext();) {
ProcEntry handle = (ProcEntry) iterator.next();
handle.release();
}
}
// Scavenge some existing entries
scavengeCache();
if (free.size() > 0) {
// There are redundant entries to drop
Collection list = free;
free = new ArrayList();
return list;
} else {
// Nothing to do this time
return null;
}
}
/**
* Removes unused entries trying to bring down the cache to the requested
* size. The removed entries are placed in the {@link #free} list.
*
* Note: entries that are in use will not be removed so it is
* possible for the cache to still be larger than {@link #cacheSize} after
* the call finishes.
*/
private void scavengeCache() {
CacheEntry ce = tail.prior;
while (ce != head && cache.size() > cacheSize) {
if (ce.value.getRefCount() == 0) {
// remove entry from linked list
ce.unlink();
// Add to free list for reclaiming
free.add(ce.value);
// Remove from HashMap
cache.remove(ce.key);
}
ce = ce.prior;
}
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/cache/StatementCache.java 0000644 0001750 0001750 00000007556 11316672660 027713 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc.cache;
import java.util.Collection;
/**
* Interface for a statement cache. Abstraction of the caching mechanism by use
* of this interface will allow developers to create custom caching schemes
* that are optimal for their specific applications. Any synchronization
* required by an implementation should utilize the implementing object for the
* lock.
*
*
* The cache can retrieve statement handles using statement keys.
* String generated from the SQL query for which the
* prepared statement was created, the database name and the parameter
* types; this key uniquely identifies a server-side preparation of the
* statement and is used to retrieve the handle of the statement when it
* needs to be executedsp_prepare or
* sp_cursorprepare handle on the serverPreparedStatement can map to multiple handles, depending on
* the types of the parameters it is called with (hence the need to be able
* to map both keys and SQL strings to handles)
*
*
* @author Brian Heineman
* @version $Id: StatementCache.java,v 1.6 2007/07/11 19:57:06 bheineman Exp $
*/
public interface StatementCache {
/**
* Returns a statement handle associated with the specified key or
* null if the key specified does not have an associated
* statement handle.
*
* @param key the statement key whose associated handle is to be returned
* @return statement handle
*/
Object get(String key);
/**
* Places the specified statement handle in the cache for the given key. If
* a key already exists in the cache, the handle will be overwritten.
*
* @param key the statement key to associated with the handle
* @param handle the statement handle
*/
void put(String key, Object handle);
/**
* Removes a statement key and handle from the cache for the specified key.
*
* @param key the statement key whose associated handle is to be removed
* from the cache
*/
void remove(String key);
/**
* Returns a Collection of obsolete statement handles that may
* be released, or null if no statement handles are obsolete.
*
* @param handles the statement handles that are no longer being used
* @return Collection of obsolete statement handles to be
* removed
*/
Collection getObsoleteHandles(Collection handles);
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/ResponseStream.java 0000644 0001750 0001750 00000040212 11316672660 026714 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.io.UnsupportedEncodingException;
import net.sourceforge.jtds.util.*;
/**
* Implements an input stream for the server response.
*
* Implementation note:
*
*
*
* @author Mike Hutchinson.
* @version $Id: ResponseStream.java,v 1.20 2005/10/27 13:22:33 alin_sinpalean Exp $
*/
public class ResponseStream {
/** The shared network socket. */
private final SharedSocket socket;
/** The Input packet buffer. */
private byte[] buffer;
/** The offset of the next byte to read. */
private int bufferPtr;
/** The length of current input packet. */
private int bufferLen;
/** The unique stream id. */
private final int streamId;
/** True if stream is closed. */
private boolean isClosed;
/** A shared byte buffer. */
private final byte[] byteBuffer = new byte[255];
/** A shared char buffer. */
private final char[] charBuffer = new char[255];
/**
* Constructs a RequestStream object.
*
* @param socket the shared socket object to write to
* @param streamId the unique id for this stream (from ResponseStream)
* @param bufferSize the initial buffer size
*/
ResponseStream(SharedSocket socket, int streamId, int bufferSize){
this.streamId = streamId;
this.socket = socket;
this.buffer = new byte[bufferSize];
this.bufferLen = bufferSize;
this.bufferPtr = bufferSize;
}
/**
* Retrieves the unique stream id.
*
* @return the unique stream id as an int
*/
int getStreamId() {
return this.streamId;
}
/**
* Retrieves the next input byte without reading forward.
*
* @return the next byte in the input stream as an int
* @throws IOException if an I/O error occurs
*/
int peek() throws IOException {
int b = read();
bufferPtr--; // Backup one
return b;
}
/**
* Reads the next input byte from the server response stream.
*
* @return the next byte in the input stream as an int
* @throws IOException if an I/O error occurs
*/
int read() throws IOException {
if (bufferPtr >= bufferLen) {
getPacket();
}
return (int) buffer[bufferPtr++] & 0xFF;
}
/**
* Reads a byte array from the server response stream.
*
* @param b the byte array to read into
* @return the number of bytes read as an int
* @throws IOException if an I/O error occurs
*/
int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
/**
* Reads a byte array from the server response stream, specifying a start
* offset and length.
*
* @param b the byte array
* @param off the starting offset in the array
* @param len the number of bytes to read
* @return the number of bytes read as an int
* @throws IOException if an I/O error occurs
*/
int read(byte[] b, int off, int len) throws IOException {
int bytesToRead = len;
while (bytesToRead > 0) {
if (bufferPtr >= bufferLen) {
getPacket();
}
int available = bufferLen - bufferPtr;
int bc = (available > bytesToRead) ? bytesToRead : available;
System.arraycopy(buffer, bufferPtr, b, off, bc);
off += bc;
bytesToRead -= bc;
bufferPtr += bc;
}
return len;
}
/**
* Reads a char array from the server response stream.
*
* @param c the char array
* @return the byte array as a byte[]
* @throws IOException if an I/O error occurs
*/
int read(char[] c) throws IOException {
for (int i = 0; i < c.length; i++) {
if (bufferPtr >= bufferLen) {
getPacket();
}
int b1 = buffer[bufferPtr++] & 0xFF;
if (bufferPtr >= bufferLen) {
getPacket();
}
int b2 = buffer[bufferPtr++] << 8;
c[i] = (char) (b2 | b1);
}
return c.length;
}
/**
* Reads a String object from the server response stream. If
* the TDS protocol version is 4.2 or 5.0 decode the string use the default
* server charset, otherwise use UCS2-LE (Unicode).
*
* @param len the length of the string to read in bytes in the case
* of TDS 4.2/5.0 and in characters for TDS 7.0+
* (UCS2-LE encoded strings)
* @return the result as a String
* @throws IOException if an I/O error occurs
*/
String readString(int len) throws IOException {
if (socket.getTdsVersion() >= Driver.TDS70) {
return readUnicodeString(len);
}
return readNonUnicodeString(len);
}
/**
* Skips a String from the server response stream. If the TDS
* protocol version is 4.2 or 5.0 len is the length in bytes,
* otherwise it's the length in UCS2-LE characters (length in bytes == 2 *
* len).
*
* @param len the length of the string to skip in bytes in the case
* of TDS 4.2/5.0 and in characters for TDS 7.0+
* (UCS2-LE encoded strings)
* @throws IOException if an I/O error occurs
*/
void skipString(int len) throws IOException {
if (len <= 0) {
return;
}
if (socket.getTdsVersion() >= Driver.TDS70) {
skip(len * 2);
} else {
skip(len);
}
}
/**
* Reads a UCS2-LE (Unicode) encoded String object from the server response
* stream.
*
* @param len the length of the string to read in characters
* @return the result as a String
* @throws IOException if an I/O error occurs
*/
String readUnicodeString(int len) throws IOException {
char[] chars = (len > charBuffer.length) ? new char[len] : charBuffer;
for (int i = 0; i < len; i++) {
if (bufferPtr >= bufferLen) {
getPacket();
}
int b1 = buffer[bufferPtr++] & 0xFF;
if (bufferPtr >= bufferLen) {
getPacket();
}
int b2 = buffer[bufferPtr++] << 8;
chars[i] = (char) (b2 | b1);
}
return new String(chars, 0, len);
}
/**
* Reads a non Unicode String from the server response stream,
* creating the String from a translated byte
* array.
*
* @param len the length of the string to read in bytes
* @return the result as a String
* @throws IOException if an I/O error occurs
*/
String readNonUnicodeString(int len) throws IOException {
CharsetInfo info = socket.getCharsetInfo();
return readString(len, info);
}
/**
* Reads a String from the server response stream, translating
* it from a byte array using the specified character set.
*
* @param len the length of the string to read in bytes
* @return the result as a String
* @throws IOException if an I/O error occurs
*/
String readNonUnicodeString(int len, CharsetInfo charsetInfo)
throws IOException {
return readString(len, charsetInfo);
}
/**
* Reads a String from the server response stream, creating
* it from a translated byte array.
*
* @param len the length of the string to read in bytes
* @param info descriptor of the charset to use
* @return the result as a String
* @throws IOException if an I/O error occurs
*/
String readString(int len, CharsetInfo info) throws IOException {
String charsetName = info.getCharset();
byte[] bytes = (len > byteBuffer.length) ? new byte[len] : byteBuffer;
read(bytes, 0, len);
try {
return new String(bytes, 0, len, charsetName);
} catch (UnsupportedEncodingException e) {
return new String(bytes, 0, len);
}
}
/**
* Reads a short value from the server response stream.
*
* @return the result as a short
* @throws IOException if an I/O error occurs
*/
short readShort() throws IOException {
int b1 = read();
return (short) (b1 | (read() << 8));
}
/**
* Reads an int value from the server response stream.
*
* @return the result as a int
* @throws IOException if an I/O error occurs
*/
int readInt() throws IOException {
int b1 = read();
int b2 = read() << 8;
int b3 = read() << 16;
int b4 = read() << 24;
return b4 | b3 | b2 | b1;
}
/**
* Reads a long value from the server response stream.
*
* @return the result as a long
* @throws IOException if an I/O error occurs
*/
long readLong() throws IOException {
long b1 = ((long) read());
long b2 = ((long) read()) << 8;
long b3 = ((long) read()) << 16;
long b4 = ((long) read()) << 24;
long b5 = ((long) read()) << 32;
long b6 = ((long) read()) << 40;
long b7 = ((long) read()) << 48;
long b8 = ((long) read()) << 56;
return b1 | b2 | b3 | b4 | b5 | b6 | b7 | b8;
}
/**
* Reads an unsigned long value from the server response stream.
*
* @return the result as a BigDecimal
* @throws IOException if an I/O error occurs
*/
BigDecimal readUnsignedLong() throws IOException {
int b1 = ((int) read() & 0xFF);
long b2 = ((long) read());
long b3 = ((long) read()) << 8;
long b4 = ((long) read()) << 16;
long b5 = ((long) read()) << 24;
long b6 = ((long) read()) << 32;
long b7 = ((long) read()) << 40;
long b8 = ((long) read()) << 48;
// Convert via String as BigDecimal(long) is actually BigDecimal(double)
// on older versions of java
return new BigDecimal(Long.toString(b2 | b3 | b4 | b5 | b6 | b7 | b8))
.multiply(new BigDecimal(256))
.add(new BigDecimal(b1));
}
/**
* Discards bytes from the server response stream.
*
* @param skip the number of bytes to discard
* @return the number of bytes skipped
*/
int skip(int skip) throws IOException {
int tmp = skip;
while (skip > 0) {
if (bufferPtr >= bufferLen) {
getPacket();
}
int available = bufferLen - bufferPtr;
if (skip > available) {
skip -= available;
bufferPtr = bufferLen;
} else {
bufferPtr += skip;
skip = 0;
}
}
return tmp;
}
/**
* Consumes the rest of the server response, without parsing it.
*
* Note: Use only in extreme cases, packets will not be parsed and
* could leave the connection in an inconsistent state.
*/
void skipToEnd() {
try {
// No more data to read.
bufferPtr = bufferLen;
// Now consume all data until we get an exception.
while (true) {
buffer = socket.getNetPacket(streamId, buffer);
}
} catch (IOException ex) {
// Ignore it. Probably no more packets.
}
}
/**
* Closes this response stream. The stream id is unlinked from the
* underlying shared socket as well.
*/
void close() {
isClosed = true;
socket.closeStream(streamId);
}
/**
* Retrieves the TDS version number.
*
* @return the TDS version as an int
*/
int getTdsVersion() {
return socket.getTdsVersion();
}
/**
* Retrieves the server type.
*
* @return the server type as an int
*/
int getServerType() {
return socket.serverType;
}
/**
* Creates a simple InputStream over the server response.
*
* This method can be used to obtain a stream which can be passed to
* InputStreamReaders to assist in reading multi byte
* character sets.
*
* @param len the number of bytes available in the server response
* @return the InputStream built over the server response
*/
InputStream getInputStream(int len) {
return new TdsInputStream(this, len);
}
/**
* Read the next TDS packet from the network.
*
* @throws IOException if an I/O error occurs
*/
private void getPacket() throws IOException {
while (bufferPtr >= bufferLen) {
if (isClosed) {
throw new IOException("ResponseStream is closed");
}
buffer = socket.getNetPacket(streamId, buffer);
bufferLen = (((int) buffer[2] & 0xFF) << 8) | ((int) buffer[3] & 0xFF);
bufferPtr = TdsCore.PKT_HDR_LEN;
if (Logger.isActive()) {
Logger.logPacket(streamId, true, buffer);
}
}
}
/**
* Simple inner class implementing an InputStream over the
* server response.
*/
private static class TdsInputStream extends InputStream {
/** The underlying ResponseStream. */
ResponseStream tds;
/** The maximum amount of data to make available. */
int maxLen;
/**
* Creates a TdsInputStream instance.
*
* @param tds the underlying ResponseStream
* @param maxLen the maximum amount of data that will be available
*/
public TdsInputStream(ResponseStream tds, int maxLen) {
this.tds = tds;
this.maxLen = maxLen;
}
public int read() throws IOException {
return (maxLen-- > 0)? tds.read(): -1;
}
public int read(byte[] bytes, int offset, int len) throws IOException {
if (maxLen < 1) {
return -1;
} else {
int bc = Math.min(maxLen, len);
if (bc > 0) {
bc = tds.read(bytes, offset, bc);
maxLen -= (bc == -1) ? 0 : bc;
}
return bc;
}
}
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/Charsets.properties 0000644 0001750 0001750 00000012664 11316672660 027003 0 ustar martin martin # The SQL Server iso_1 charset is actually Microsoft's extended version, Cp1252
ISO_1=1|ISO-8859-1
ISO15=1|ISO-8859-15
ISO88592=1|ISO-8859-2
ISO88595=1|ISO-8859-5
ISO88596=1|ISO-8859-6
ISO88597=1|ISO-8859-7
ISO88598=1|ISO-8859-8
ISO88599=1|ISO-8859-9
CP437=1|Cp437
CP850=1|Cp850
CP932=2|MS932
CP936=2|MS936
CP949=2|Cp949
CP950=2|Cp950
CP1250=1|Cp1250
CP1251=1|Cp1251
CP1252=1|Cp1252
CP1253=1|Cp1253
CP1254=1|Cp1254
CP1255=1|Cp1255
CP1256=1|Cp1256
CP1257=1|Cp1257
CP1258=1|Cp1258
ASCII_7=1|US-ASCII
ASCII_8=1|US-ASCII
ROMAN8=1|ISO-8859-1
MAC=1|MacRoman
GREEK8=1|ISO-8859-7
MACGRK2=1|ISO-8859-7
MAC_CYR=1|ISO-8859-5
SJIS=2|Shift_JIS
BIG5=2|Big5
BIG5HK=2|Big5-HKSCS
GB2312=2|MS936
GBK=2|MS936
KOI8=1|KOI8-R
TIS620=1|TIS-620
DECKANJI=3|EUC_JP
EUCCNS=2|x-EUC-CN
EUCJIS=3|EUC-JP
EUCGB=2|x-EUC-CN
EUCKSC=2|EUC-KR
UTF8=4|UTF-8
UNICODE=4|UTF-16
# Also map charset names back to themselves so that they can be used in the URL
# with their Java name, not only the obscure SQL Server denomination.
ISO-8859-1=1|ISO-8859-1
ISO-8859-2=1|ISO-8859-2
ISO-8859-5=1|ISO-8859-5
ISO-8859-6=1|ISO-8859-6
ISO-8859-7=1|ISO-8859-7
ISO-8859-8=1|ISO-8859-8
ISO-8859-9=1|ISO-8859-9
ISO-8859-15=1|ISO-8859-15
US-ASCII=1|US-ASCII
ASCII=1|US-ASCII
SHIFT_JIS=2|Shift_JIS
BIG5-HKSCS=2|Big5-HKSCS
BIG5_HKSCS=2|Big5-HKSCS
KOI8-R=1|KOI8-R
KOI8_R=1|KOI8-R
TIS-620=1|TIS-620
TIS_620=1|TIS-620
EUC-JP=3|EUC_JP
EUC_JP=3|EUC_JP
X-EUC-CN=2|x-EUC-CN
EUC_CN=2|x-EUC-CN
EUC-KR=2|EUC-KR
EUC_KR=2|EUC-KR
UTF-8=4|UTF-8
UTF-16=4|UTF-16
MACROMAN=1|MacRoman
# LCID to charset mappings
LCID_1054=2|MS874
LCID_1041=2|MS932
LCID_66577=2|MS932
LCID_2052=2|MS936
LCID_4100=2|MS936
LCID_133124=2|MS936
LCID_1042=2|MS949
LCID_66578=2|MS949
LCID_1028=2|MS950
LCID_197636=2|MS950
LCID_1029=1|Cp1250
LCID_1038=1|Cp1250
LCID_1045=1|Cp1250
LCID_1048=1|Cp1250
LCID_1050=1|Cp1250
LCID_1051=1|Cp1250
LCID_1052=1|Cp1250
LCID_1060=1|Cp1250
LCID_66574=1|Cp1250
LCID_1026=1|Cp1251
LCID_1049=1|Cp1251
LCID_1058=1|Cp1251
LCID_1059=1|Cp1251
LCID_1071=1|Cp1251
LCID_2074=1|Cp1251
LCID_3098=1|Cp1251
LCID_1027=1|Cp1252
LCID_1030=1|Cp1252
LCID_1031=1|Cp1252
LCID_1033=1|Cp1252
LCID_1034=1|Cp1252
LCID_1035=1|Cp1252
LCID_1036=1|Cp1252
LCID_1039=1|Cp1252
LCID_1040=1|Cp1252
LCID_1043=1|Cp1252
LCID_1044=1|Cp1252
LCID_1046=1|Cp1252
LCID_1053=1|Cp1252
LCID_1057=1|Cp1252
LCID_1069=1|Cp1252
LCID_1080=1|Cp1252
LCID_2055=1|Cp1252
LCID_2057=1|Cp1252
LCID_2058=1|Cp1252
LCID_2060=1|Cp1252
LCID_2064=1|Cp1252
LCID_2067=1|Cp1252
LCID_2068=1|Cp1252
LCID_2070=1|Cp1252
LCID_3097=1|Cp1252
LCID_3081=1|Cp1252
LCID_3082=1|Cp1252
LCID_3084=1|Cp1252
LCID_4103=1|Cp1252
LCID_4105=1|Cp1252
LCID_4106=1|Cp1252
LCID_4108=1|Cp1252
LCID_5127=1|Cp1252
LCID_5129=1|Cp1252
LCID_5130=1|Cp1252
LCID_5132=1|Cp1252
LCID_6153=1|Cp1252
LCID_6154=1|Cp1252
LCID_7178=1|Cp1252
LCID_7717=1|Cp1252
LCID_8201=1|Cp1252
LCID_8202=1|Cp1252
LCID_9225=1|Cp1252
LCID_9226=1|Cp1252
LCID_10250=1|Cp1252
LCID_11274=1|Cp1252
LCID_12298=1|Cp1252
LCID_13322=1|Cp1252
LCID_14346=1|Cp1252
LCID_15370=1|Cp1252
LCID_16394=1|Cp1252
LCID_66567=1|Cp1252
LCID_66615=1|Cp1252
LCID_1032=1|Cp1253
LCID_1055=1|Cp1254
LCID_1037=1|Cp1255
LCID_1025=1|Cp1256
LCID_1056=1|Cp1256
LCID_1065=1|Cp1256
LCID_2049=1|Cp1256
LCID_3073=1|Cp1256
LCID_4097=1|Cp1256
LCID_5121=1|Cp1256
LCID_5145=1|Cp1256
LCID_7169=1|Cp1256
LCID_8193=1|Cp1256
LCID_9217=1|Cp1256
LCID_10241=1|Cp1256
LCID_11265=1|Cp1256
LCID_12289=1|Cp1256
LCID_13313=1|Cp1256
LCID_14337=1|Cp1256
LCID_15361=1|Cp1256
LCID_16385=1|Cp1256
LCID_1061=1|Cp1257
LCID_1062=1|Cp1257
LCID_1063=1|Cp1257
LCID_2087=1|Cp1257
LCID_1066=1|Cp1258
# Sort order to charset mappings
SORT_50=1|Cp1252
SORT_51=1|Cp1252
SORT_52=1|Cp1252
SORT_53=1|Cp1252
SORT_54=1|Cp1252
SORT_71=1|Cp1252
SORT_72=1|Cp1252
SORT_183=1|Cp1252
SORT_184=1|Cp1252
SORT_185=1|Cp1252
SORT_186=1|Cp1252
SORT_210=1|Cp1252
SORT_211=1|Cp1252
SORT_212=1|Cp1252
SORT_213=1|Cp1252
SORT_214=1|Cp1252
SORT_215=1|Cp1252
SORT_216=1|Cp1252
SORT_217=1|Cp1252
SORT_40=1|Cp850
SORT_41=1|Cp850
SORT_42=1|Cp850
SORT_43=1|Cp850
SORT_44=1|Cp850
SORT_49=1|Cp850
SORT_55=1|Cp850
SORT_56=1|Cp850
SORT_57=1|Cp850
SORT_58=1|Cp850
SORT_59=1|Cp850
SORT_60=1|Cp850
SORT_61=1|Cp850
SORT_30=1|Cp437
SORT_31=1|Cp437
SORT_32=1|Cp437
SORT_33=1|Cp437
SORT_34=1|Cp437
SORT_80=1|Cp1250
SORT_81=1|Cp1250
SORT_82=1|Cp1250
SORT_83=1|Cp1250
SORT_84=1|Cp1250
SORT_85=1|Cp1250
SORT_86=1|Cp1250
SORT_87=1|Cp1250
SORT_88=1|Cp1250
SORT_89=1|Cp1250
SORT_90=1|Cp1250
SORT_91=1|Cp1250
SORT_92=1|Cp1250
SORT_93=1|Cp1250
SORT_94=1|Cp1250
SORT_95=1|Cp1250
SORT_96=1|Cp1250
SORT_104=1|Cp1251
SORT_105=1|Cp1251
SORT_106=1|Cp1251
SORT_107=1|Cp1251
SORT_108=1|Cp1251
SORT_112=1|Cp1253
SORT_113=1|Cp1253
SORT_114=1|Cp1253
SORT_120=1|Cp1253
SORT_121=1|Cp1253
SORT_124=1|Cp1253
SORT_128=1|Cp1254
SORT_129=1|Cp1254
SORT_130=1|Cp1254
SORT_136=1|Cp1255
SORT_137=1|Cp1255
SORT_138=1|Cp1255
SORT_144=1|Cp1256
SORT_145=1|Cp1256
SORT_146=1|Cp1256
SORT_152=1|Cp1257
SORT_153=1|Cp1257
SORT_154=1|Cp1257
SORT_155=1|Cp1257
SORT_156=1|Cp1257
SORT_157=1|Cp1257
SORT_158=1|Cp1257
SORT_159=1|Cp1257
SORT_160=1|Cp1257
SORT_194=2|MS949
SORT_195=2|MS949
SORT_201=2|MS949
SORT_196=2|MS950
SORT_197=2|MS950
SORT_202=2|MS950
SORT_198=2|MS936
SORT_199=2|MS936
SORT_203=2|MS936
SORT_204=2|MS874
SORT_205=2|MS874
SORT_206=2|MS874
SORT_192=2|MS932
SORT_193=2|MS932
SORT_200=2|MS932
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/JtdsPreparedStatement.java 0000644 0001750 0001750 00000122356 11316672660 030230 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.*;
import java.util.Calendar;
import java.util.ArrayList;
import java.util.Collection;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.text.NumberFormat;
/**
* jTDS implementation of the java.sql.PreparedStatement interface.
*
*
*
* @author Mike Hutchinson
* @author Brian Heineman
* @version $Id: JtdsPreparedStatement.java,v 1.63.2.6 2009/12/30 11:37:21 ickzon Exp $
*/
public class JtdsPreparedStatement extends JtdsStatement implements PreparedStatement {
/** The SQL statement being prepared. */
protected final String sql;
/** The original SQL statement provided at construction time. */
private final String originalSql;
/** The first SQL keyword in the SQL string.*/
protected String sqlWord;
/** The procedure name for CallableStatements. */
protected String procName;
/** The parameter list for the call. */
protected ParamInfo[] parameters;
/** True to return generated keys. */
private boolean returnKeys;
/** The cached parameter meta data. */
protected ParamInfo[] paramMetaData;
/** Used to format numeric values when scale is specified. */
private final static NumberFormat f = NumberFormat.getInstance();
/** Collection of handles used by this statement */
Collection handles;
/**
* Construct a new preparedStatement object.
*
* @param connection The parent connection.
* @param sql The SQL statement to prepare.
* @param resultSetType The result set type eg SCROLLABLE etc.
* @param concurrency The result set concurrency eg READONLY.
* @param returnKeys True if generated keys should be returned.
* @throws SQLException
*/
JtdsPreparedStatement(ConnectionJDBC2 connection,
String sql,
int resultSetType,
int concurrency,
boolean returnKeys)
throws SQLException {
super(connection, resultSetType, concurrency);
// returned by toString()
originalSql = sql;
// Parse the SQL looking for escapes and parameters
if (this instanceof JtdsCallableStatement) {
sql = normalizeCall(sql);
}
ArrayList params = new ArrayList();
String[] parsedSql = SQLParser.parse(sql, params, connection, false);
if (parsedSql[0].length() == 0) {
throw new SQLException(Messages.get("error.prepare.nosql"), "07000");
}
if (parsedSql[1].length() > 1) {
if (this instanceof JtdsCallableStatement) {
// Procedure call
this.procName = parsedSql[1];
}
}
sqlWord = parsedSql[2];
if (returnKeys && "insert".equals(sqlWord)) {
if (connection.getServerType() == Driver.SQLSERVER
&& connection.getDatabaseMajorVersion() >= 8) {
this.sql = parsedSql[0] + " SELECT SCOPE_IDENTITY() AS ID";
} else {
this.sql = parsedSql[0] + " SELECT @@IDENTITY AS ID";
}
this.returnKeys = true;
} else {
this.sql = parsedSql[0];
this.returnKeys = false;
}
parameters = (ParamInfo[]) params.toArray(new ParamInfo[params.size()]);
}
/**
* Returns the SQL command provided at construction time.
*/
public String toString() {
return originalSql;
}
/**
* This method converts native call syntax into (hopefully) valid JDBC
* escape syntax.
*
* Note: This method is required for backwards compatibility with
* previous versions of jTDS. Strictly speaking only the JDBC syntax needs
* to be recognised, constructions such as "?=#testproc ?,?" are neither
* valid native syntax nor valid escapes. All the substrings and trims
* below are not as bad as they look. The objects created all refer back to
* the original sql string it is just the start and length positions which
* change.
*
* @param sql the SQL statement to process
* @return the SQL, possibly in original form
*/
protected static String normalizeCall(String sql) {
String original = sql;
sql = sql.trim();
if (sql.length() > 0 && sql.charAt(0) == '{') {
return original; // Assume already escaped
}
if (sql.length() > 4 && sql.substring(0, 5).equalsIgnoreCase("exec ")) {
sql = sql.substring(4).trim();
} else if (sql.length() > 7 && sql.substring(0, 8).equalsIgnoreCase("execute ")){
sql = sql.substring(7).trim();
}
if (sql.length() > 1 && sql.charAt(0) == '?') {
sql = sql.substring(1).trim();
if (sql.length() < 1 || sql.charAt(0) != '=') {
return original; // Give up, error will be reported elsewhere
}
sql = sql.substring(1).trim();
// OK now reconstruct as JDBC escaped call
return "{?=call " + sql + '}';
}
return "{call " + sql + '}';
}
/**
* Check that this statement is still open.
*
* @throws SQLException if statement closed.
*/
protected void checkOpen() throws SQLException {
if (closed) {
throw new SQLException(
Messages.get("error.generic.closed", "PreparedStatement"), "HY010");
}
}
/**
* Report that user tried to call a method not supported on this type of statement.
*
* @param method The method name to report in the error message.
* @throws SQLException
*/
protected void notSupported(String method) throws SQLException {
throw new SQLException(
Messages.get("error.generic.notsup", method), "HYC00");
}
/**
* Execute the SQL batch on a MS server.
*
* When running with prepareSQL=1 or 3, the driver will first prepare temporary stored
* procedures or statements for each parameter combination found in the batch. The handles to these pre-preared
* statements will then be used to execute the actual batch statements.
*
* @param size the total size of the batch
* @param executeSize the maximum number of statements to send in one request
* @param counts the returned update counts
* @return chained exceptions linked to a SQLException
* @throws SQLException if a serious error occurs during execution
*/
protected SQLException executeMSBatch(int size, int executeSize, ArrayList counts)
throws SQLException {
if (parameters.length == 0) {
// There are no parameters, each SQL call is the same so execute as a simple batch
return super.executeMSBatch(size, executeSize, counts);
}
SQLException sqlEx = null;
String procHandle[] = null;
// Prepare any statements before executing the batch
if (connection.getPrepareSql() == TdsCore.TEMPORARY_STORED_PROCEDURES ||
connection.getPrepareSql() == TdsCore.PREPARE) {
procHandle = new String[size];
for (int i = 0; i < size; i++) {
// Prepare the statement
procHandle[i] = connection.prepareSQL(this, sql, (ParamInfo[]) batchValues.get(i), false, false);
}
}
for (int i = 0; i < size;) {
Object value = batchValues.get(i);
String proc = (procHandle == null) ? procName : procHandle[i];
++i;
// Execute batch now if max size reached or end of batch
boolean executeNow = (i % executeSize == 0) || i == size;
tds.startBatch();
tds.executeSQL(sql, proc, (ParamInfo[]) value, false, 0, -1, -1, executeNow);
// If the batch has been sent, process the results
if (executeNow) {
sqlEx = tds.getBatchCounts(counts, sqlEx);
// If a serious error then we stop execution now as count
// is too small.
if (sqlEx != null && counts.size() != i) {
break;
}
}
}
return sqlEx;
}
/**
* Execute the SQL batch on a Sybase server.
*
* Sybase needs to have the SQL concatenated into one TDS language packet followed by up to 1000 parameters. This
* method will be overridden for CallableStatements.
*
* @param size the total size of the batch
* @param executeSize the maximum number of statements to send in one request
* @param counts the returned update counts
* @return chained exceptions linked to a SQLException
* @throws SQLException if a serious error occurs during execution
*/
protected SQLException executeSybaseBatch(int size, int executeSize, ArrayList counts) throws SQLException {
if (parameters.length == 0) {
// There are no parameters each SQL call is the same so
// execute as a simple batch
return super.executeSybaseBatch(size, executeSize, counts);
}
// Revise the executeSize down if too many parameters will be required.
// Be conservative the actual maximums are 256 for older servers and 2048.
int maxParams = (connection.getDatabaseMajorVersion() < 12 ||
(connection.getDatabaseMajorVersion() == 12 && connection.getDatabaseMinorVersion() < 50)) ?
200 : 1000;
StringBuffer sqlBuf = new StringBuffer(size * 32);
SQLException sqlEx = null;
if (parameters.length * executeSize > maxParams) {
executeSize = maxParams / parameters.length;
if (executeSize == 0) {
executeSize = 1;
}
}
ArrayList paramList = new ArrayList();
for (int i = 0; i < size;) {
Object value = batchValues.get(i);
++i;
// Execute batch now if max size reached or end of batch
boolean executeNow = (i % executeSize == 0) || i == size;
int offset = sqlBuf.length();
sqlBuf.append(sql).append(' ');
for (int n = 0; n < parameters.length; n++) {
ParamInfo p = ((ParamInfo[]) value)[n];
// Allow for the position of the '?' marker in the buffer
p.markerPos += offset;
paramList.add(p);
}
if (executeNow) {
ParamInfo args[];
args = (ParamInfo[]) paramList.toArray(new ParamInfo[paramList.size()]);
tds.executeSQL(sqlBuf.toString(), null, args, false, 0, -1, -1, true);
sqlBuf.setLength(0);
paramList.clear();
// If the batch has been sent, process the results
sqlEx = tds.getBatchCounts(counts, sqlEx);
// If a serious error or a server error then we stop
// execution now as count is too small.
if (sqlEx != null && counts.size() != i) {
break;
}
}
}
return sqlEx;
}
/**
* Check the supplied index and return the selected parameter.
*
* @param parameterIndex the parameter index 1 to n.
* @return the parameter as a ParamInfo object.
* @throws SQLException if the statement is closed;
* if parameterIndex is less than 0;
* if parameterIndex is greater than the
* number of parameters;
* if checkIfSet was true
* and the parameter was not set
*/
protected ParamInfo getParameter(int parameterIndex) throws SQLException {
checkOpen();
if (parameterIndex < 1 || parameterIndex > parameters.length) {
throw new SQLException(Messages.get("error.prepare.paramindex",
Integer.toString(parameterIndex)),
"07009");
}
return parameters[parameterIndex - 1];
}
/**
* Generic setObject method.
*
* @param parameterIndex Parameter index 1 to n.
* @param x The value to set.
* @param targetSqlType The java.sql.Types constant describing the data.
* @param scale The decimal scale -1 if not set.
*/
public void setObjectBase(int parameterIndex, Object x, int targetSqlType, int scale)
throws SQLException {
checkOpen();
int length = 0;
if (targetSqlType == java.sql.Types.CLOB) {
targetSqlType = java.sql.Types.LONGVARCHAR;
} else if (targetSqlType == java.sql.Types.BLOB) {
targetSqlType = java.sql.Types.LONGVARBINARY;
}
if (x != null) {
x = Support.convert(this, x, targetSqlType, connection.getCharset());
if (scale >= 0) {
if (x instanceof BigDecimal) {
x = ((BigDecimal) x).setScale(scale, BigDecimal.ROUND_HALF_UP);
} else if (x instanceof Number) {
synchronized (f) {
f.setGroupingUsed(false);
f.setMaximumFractionDigits(scale);
x = Support.convert(this, f.format(x), targetSqlType,
connection.getCharset());
}
}
}
if (x instanceof Blob) {
Blob blob = (Blob) x;
length = (int) blob.length();
x = blob.getBinaryStream();
} else if (x instanceof Clob) {
Clob clob = (Clob) x;
length = (int) clob.length();
x = clob.getCharacterStream();
}
}
setParameter(parameterIndex, x, targetSqlType, scale, length);
}
/**
* Update the ParamInfo object for the specified parameter.
*
* @param parameterIndex Parameter index 1 to n.
* @param x The value to set.
* @param targetSqlType The java.sql.Types constant describing the data.
* @param scale The decimal scale -1 if not set.
* @param length The length of the data item.
*/
protected void setParameter(int parameterIndex, Object x, int targetSqlType, int scale, int length)
throws SQLException {
ParamInfo pi = getParameter(parameterIndex);
if ("ERROR".equals(Support.getJdbcTypeName(targetSqlType))) {
throw new SQLException(Messages.get("error.generic.badtype",
Integer.toString(targetSqlType)), "HY092");
}
// Update parameter descriptor
if (targetSqlType == java.sql.Types.DECIMAL
|| targetSqlType == java.sql.Types.NUMERIC) {
pi.precision = connection.getMaxPrecision();
if (x instanceof BigDecimal) {
x = Support.normalizeBigDecimal((BigDecimal) x, pi.precision);
pi.scale = ((BigDecimal) x).scale();
} else {
pi.scale = (scale < 0) ? TdsData.DEFAULT_SCALE : scale;
}
} else {
pi.scale = (scale < 0) ? 0 : scale;
}
if (x instanceof String) {
pi.length = ((String) x).length();
} else if (x instanceof byte[]) {
pi.length = ((byte[]) x).length;
} else {
pi.length = length;
}
if (x instanceof Date) {
x = new DateTime((Date) x);
} else if (x instanceof Time) {
x = new DateTime((Time) x);
} else if (x instanceof Timestamp) {
x = new DateTime((Timestamp) x);
}
pi.value = x;
pi.jdbcType = targetSqlType;
pi.isSet = true;
pi.isUnicode = connection.getUseUnicode();
}
/**
* Update the cached column meta data information.
*
* @param value The Column meta data array.
*/
void setColMetaData(ColInfo[] value) {
this.colMetaData = value;
}
/**
* Update the cached parameter meta data information.
*
* @param value The Column meta data array.
*/
void setParamMetaData(ParamInfo[] value) {
for (int i = 0; i < value.length && i < parameters.length; i++) {
if (!parameters[i].isSet) {
// Only update parameter descriptors if the user
// has not yet set them.
parameters[i].jdbcType = value[i].jdbcType;
parameters[i].isOutput = value[i].isOutput;
parameters[i].precision = value[i].precision;
parameters[i].scale = value[i].scale;
parameters[i].sqlType = value[i].sqlType;
}
}
}
// -------------------- java.sql.PreparedStatement methods follow -----------------
public void close() throws SQLException {
try {
super.close();
} finally {
// Null these fields to reduce memory usage while
// wating for Statement.finalize() to execute.
this.handles = null;
this.parameters = null;
}
}
public int executeUpdate() throws SQLException {
checkOpen();
initialize();
if (procName == null && !(this instanceof JtdsCallableStatement)) {
// Sync on the connection to make sure rollback() isn't called
// between the moment when the statement is prepared and the moment
// when it's executed.
synchronized (connection) {
String spName = connection.prepareSQL(this, sql, parameters, returnKeys, false);
executeSQL(sql, spName, parameters, returnKeys, true, false);
}
} else {
executeSQL(sql, procName, parameters, returnKeys, true, false);
}
int res = getUpdateCount();
return res == -1 ? 0 : res;
}
public void addBatch() throws SQLException {
checkOpen();
if (batchValues == null) {
batchValues = new ArrayList();
}
if (parameters.length == 0) {
// This is likely to be an error. Batch execution
// of a prepared statement with no parameters means
// exactly the same SQL will be executed each time!
batchValues.add(sql);
} else {
batchValues.add(parameters);
ParamInfo tmp[] = new ParamInfo[parameters.length];
for (int i = 0; i < parameters.length; ++i) {
tmp[i] = (ParamInfo) parameters[i].clone();
}
parameters = tmp;
}
}
public void clearParameters() throws SQLException {
checkOpen();
for (int i = 0; i < parameters.length; i++) {
parameters[i].clearInValue();
}
}
public boolean execute() throws SQLException {
checkOpen();
initialize();
boolean useCursor = useCursor(returnKeys, sqlWord);
if (procName == null && !(this instanceof JtdsCallableStatement)) {
// Sync on the connection to make sure rollback() isn't called
// between the moment when the statement is prepared and the moment
// when it's executed.
synchronized (connection) {
String spName = connection.prepareSQL(this, sql, parameters, returnKeys, useCursor);
return executeSQL(sql, spName, parameters, returnKeys, false, useCursor);
}
} else {
return executeSQL(sql, procName, parameters, returnKeys, false, useCursor);
}
}
public void setByte(int parameterIndex, byte x) throws SQLException {
setParameter(parameterIndex, new Integer((int) (x & 0xFF)), java.sql.Types.TINYINT, 0, 0);
}
public void setDouble(int parameterIndex, double x) throws SQLException {
setParameter(parameterIndex, new Double(x), java.sql.Types.DOUBLE, 0, 0);
}
public void setFloat(int parameterIndex, float x) throws SQLException {
setParameter(parameterIndex, new Float(x), java.sql.Types.REAL, 0, 0);
}
public void setInt(int parameterIndex, int x) throws SQLException {
setParameter(parameterIndex, new Integer(x), java.sql.Types.INTEGER, 0, 0);
}
public void setNull(int parameterIndex, int sqlType) throws SQLException {
if (sqlType == java.sql.Types.CLOB) {
sqlType = java.sql.Types.LONGVARCHAR;
} else if (sqlType == java.sql.Types.BLOB) {
sqlType = java.sql.Types.LONGVARBINARY;
}
setParameter(parameterIndex, null, sqlType, -1, 0);
}
public void setLong(int parameterIndex, long x) throws SQLException {
setParameter(parameterIndex, new Long(x), java.sql.Types.BIGINT, 0, 0);
}
public void setShort(int parameterIndex, short x) throws SQLException {
setParameter(parameterIndex, new Integer(x), java.sql.Types.SMALLINT, 0, 0);
}
public void setBoolean(int parameterIndex, boolean x) throws SQLException {
setParameter(parameterIndex, x ? Boolean.TRUE : Boolean.FALSE, BOOLEAN, 0, 0);
}
public void setBytes(int parameterIndex, byte[] x) throws SQLException {
setParameter(parameterIndex, x, java.sql.Types.BINARY, 0, 0);
}
public void setAsciiStream(int parameterIndex, InputStream inputStream, int length)
throws SQLException {
if (inputStream == null || length < 0) {
setParameter(parameterIndex, null, java.sql.Types.LONGVARCHAR, 0, 0);
} else {
try {
setCharacterStream(parameterIndex, new InputStreamReader(inputStream, "US-ASCII"), length);
} catch (UnsupportedEncodingException e) {
// Should never happen!
}
}
}
public void setBinaryStream(int parameterIndex, InputStream x, int length)
throws SQLException {
checkOpen();
if (x == null || length < 0) {
setBytes(parameterIndex, null);
} else {
setParameter(parameterIndex, x, java.sql.Types.LONGVARBINARY, 0, length);
}
}
public void setUnicodeStream(int parameterIndex, InputStream inputStream, int length)
throws SQLException {
checkOpen();
if (inputStream == null || length < 0) {
setString(parameterIndex, null);
} else {
try {
length /= 2;
char[] tmp = new char[length];
int pos = 0;
int b1 = inputStream.read();
int b2 = inputStream.read();
while (b1 >= 0 && b2 >= 0 && pos < length) {
tmp[pos++] = (char) (((b1 << 8) &0xFF00) | (b2 & 0xFF));
b1 = inputStream.read();
b2 = inputStream.read();
}
setString(parameterIndex, new String(tmp, 0, pos));
} catch (java.io.IOException e) {
throw new SQLException(Messages.get("error.generic.ioerror",
e.getMessage()), "HY000");
}
}
}
public void setCharacterStream(int parameterIndex, Reader reader, int length)
throws SQLException {
if (reader == null || length < 0) {
setParameter(parameterIndex, null, java.sql.Types.LONGVARCHAR, 0, 0);
} else {
setParameter(parameterIndex, reader, java.sql.Types.LONGVARCHAR, 0, length);
}
}
public void setObject(int parameterIndex, Object x) throws SQLException {
setObjectBase(parameterIndex, x, Support.getJdbcType(x), -1);
}
public void setObject(int parameterIndex, Object x, int targetSqlType)
throws SQLException {
setObjectBase(parameterIndex, x, targetSqlType, -1);
}
public void setObject(int parameterIndex, Object x, int targetSqlType, int scale)
throws SQLException {
checkOpen();
if (scale < 0 || scale > connection.getMaxPrecision()) {
throw new SQLException(Messages.get("error.generic.badscale"), "HY092");
}
setObjectBase(parameterIndex, x, targetSqlType, scale);
}
public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException {
notImplemented("PreparedStatement.setNull(int, int, String)");
}
public void setString(int parameterIndex, String x) throws SQLException {
setParameter(parameterIndex, x, java.sql.Types.VARCHAR, 0, 0);
}
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException {
setParameter(parameterIndex, x, java.sql.Types.DECIMAL, -1, 0);
}
public void setURL(int parameterIndex, URL url) throws SQLException {
setString(parameterIndex, (url == null)? null: url.toString());
}
public void setArray(int arg0, Array arg1) throws SQLException {
notImplemented("PreparedStatement.setArray");
}
public void setBlob(int parameterIndex, Blob x) throws SQLException {
if (x == null) {
setBytes(parameterIndex, null);
} else {
long length = x.length();
if (length > Integer.MAX_VALUE) {
throw new SQLException(Messages.get("error.resultset.longblob"), "24000");
}
setBinaryStream(parameterIndex, x.getBinaryStream(), (int) x.length());
}
}
public void setClob(int parameterIndex, Clob x) throws SQLException {
if (x == null) {
this.setString(parameterIndex, null);
} else {
long length = x.length();
if (length > Integer.MAX_VALUE) {
throw new SQLException(Messages.get("error.resultset.longclob"), "24000");
}
setCharacterStream(parameterIndex, x.getCharacterStream(), (int) x.length());
}
}
public void setDate(int parameterIndex, Date x) throws SQLException {
setParameter(parameterIndex, x, java.sql.Types.DATE, 0, 0);
}
public ParameterMetaData getParameterMetaData() throws SQLException {
checkOpen();
//
// NB. This is usable only with the JDBC3 version of the interface.
//
if (connection.getServerType() == Driver.SYBASE) {
// Sybase does return the parameter types for prepared sql.
connection.prepareSQL(this, sql, new ParamInfo[0], false, false);
}
try {
Class pmdClass = Class.forName("net.sourceforge.jtds.jdbc.ParameterMetaDataImpl");
Class[] parameterTypes = new Class[] {ParamInfo[].class, ConnectionJDBC2.class};
Object[] arguments = new Object[] {parameters, connection};
Constructor pmdConstructor = pmdClass.getConstructor(parameterTypes);
return (ParameterMetaData) pmdConstructor.newInstance(arguments);
} catch (Exception e) {
notImplemented("PreparedStatement.getParameterMetaData");
}
return null;
}
public void setRef(int parameterIndex, Ref x) throws SQLException {
notImplemented("PreparedStatement.setRef");
}
public ResultSet executeQuery() throws SQLException {
checkOpen();
initialize();
boolean useCursor = useCursor(false, null);
if (procName == null && !(this instanceof JtdsCallableStatement)) {
// Sync on the connection to make sure rollback() isn't called
// between the moment when the statement is prepared and the moment
// when it's executed.
synchronized (connection) {
String spName = connection.prepareSQL(this, sql, parameters, false, useCursor);
return executeSQLQuery(sql, spName, parameters, useCursor);
}
} else {
return executeSQLQuery(sql, procName, parameters, useCursor);
}
}
public ResultSetMetaData getMetaData() throws SQLException {
checkOpen();
if (colMetaData == null) {
if (currentResult != null) {
colMetaData = currentResult.columns;
} else if (connection.getServerType() == Driver.SYBASE) {
// Sybase can provide meta data as a by product of preparing the call.
connection.prepareSQL(this, sql, new ParamInfo[0], false, false);
if (colMetaData == null) {
return null; // Sorry still no go
}
} else {
// For Microsoft set all parameters to null and execute the query.
// SET FMTONLY ON asks the server just to return meta data.
// This only works for select statements
if (!"select".equals(sqlWord)) {
return null;
}
// Copy parameters to avoid corrupting any values already set
// by the user as we need to set a flag and null out the data.
ParamInfo[] params = new ParamInfo[parameters.length];
for (int i = 0; i < params.length; i++) {
params[i] = new ParamInfo(parameters[i].markerPos, false);
params[i].isSet = true;
}
// Substitute nulls into SQL String
StringBuffer testSql = new StringBuffer(sql.length() + 128);
testSql.append("SET FMTONLY ON ");
testSql.append(
Support.substituteParameters(sql, params, connection));
testSql.append(" SET FMTONLY OFF");
try {
tds.submitSQL(testSql.toString());
colMetaData = tds.getColumns();
} catch (SQLException e) {
// Ensure FMTONLY is switched off!
tds.submitSQL("SET FMTONLY OFF");
return null;
}
}
}
return new JtdsResultSetMetaData(colMetaData,
JtdsResultSet.getColumnCount(colMetaData),
connection.getUseLOBs());
}
public void setTime(int parameterIndex, Time x) throws SQLException {
setParameter( parameterIndex, x, java.sql.Types.TIME, 0, 0 );
}
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {
setParameter(parameterIndex, x, java.sql.Types.TIMESTAMP, 0, 0);
}
public void setDate(int parameterIndex, Date x, Calendar cal)
throws SQLException {
if (x != null && cal != null) {
x = new java.sql.Date(Support.timeFromZone(x, cal));
}
setDate(parameterIndex, x);
}
public void setTime(int parameterIndex, Time x, Calendar cal)
throws SQLException {
if (x != null && cal != null) {
x = new Time(Support.timeFromZone(x, cal));
}
setTime(parameterIndex, x);
}
public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal)
throws SQLException {
if (x != null && cal != null) {
x = new java.sql.Timestamp(Support.timeFromZone(x, cal));
}
setTimestamp(parameterIndex, x);
}
public int executeUpdate(String sql) throws SQLException {
notSupported("executeUpdate(String)");
return 0;
}
public void addBatch(String sql) throws SQLException {
notSupported("executeBatch(String)");
}
public boolean execute(String sql) throws SQLException {
notSupported("execute(String)");
return false;
}
public int executeUpdate(String sql, int getKeys) throws SQLException {
notSupported("executeUpdate(String, int)");
return 0;
}
public boolean execute(String arg0, int arg1) throws SQLException {
notSupported("execute(String, int)");
return false;
}
public int executeUpdate(String arg0, int[] arg1) throws SQLException {
notSupported("executeUpdate(String, int[])");
return 0;
}
public boolean execute(String arg0, int[] arg1) throws SQLException {
notSupported("execute(String, int[])");
return false;
}
public int executeUpdate(String arg0, String[] arg1) throws SQLException {
notSupported("executeUpdate(String, String[])");
return 0;
}
public boolean execute(String arg0, String[] arg1) throws SQLException {
notSupported("execute(String, String[])");
return false;
}
public ResultSet executeQuery(String sql) throws SQLException {
notSupported("executeQuery(String)");
return null;
}
/////// JDBC4 demarcation, do NOT put any JDBC3 code below this line ///////
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setAsciiStream(int, java.io.InputStream)
*/
public void setAsciiStream(int parameterIndex, InputStream x)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setAsciiStream(int, java.io.InputStream, long)
*/
public void setAsciiStream(int parameterIndex, InputStream x, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setBinaryStream(int, java.io.InputStream)
*/
public void setBinaryStream(int parameterIndex, InputStream x)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setBinaryStream(int, java.io.InputStream, long)
*/
public void setBinaryStream(int parameterIndex, InputStream x, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setBlob(int, java.io.InputStream)
*/
public void setBlob(int parameterIndex, InputStream inputStream)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setBlob(int, java.io.InputStream, long)
*/
public void setBlob(int parameterIndex, InputStream inputStream, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setCharacterStream(int, java.io.Reader)
*/
public void setCharacterStream(int parameterIndex, Reader reader)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setCharacterStream(int, java.io.Reader, long)
*/
public void setCharacterStream(int parameterIndex, Reader reader,
long length) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setClob(int, java.io.Reader)
*/
public void setClob(int parameterIndex, Reader reader) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setClob(int, java.io.Reader, long)
*/
public void setClob(int parameterIndex, Reader reader, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNCharacterStream(int, java.io.Reader)
*/
public void setNCharacterStream(int parameterIndex, Reader value)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNCharacterStream(int, java.io.Reader, long)
*/
public void setNCharacterStream(int parameterIndex, Reader value,
long length) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNClob(int, java.sql.NClob)
*/
public void setNClob(int parameterIndex, NClob value) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNClob(int, java.io.Reader)
*/
public void setNClob(int parameterIndex, Reader reader) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNClob(int, java.io.Reader, long)
*/
public void setNClob(int parameterIndex, Reader reader, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNString(int, java.lang.String)
*/
public void setNString(int parameterIndex, String value)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setRowId(int, java.sql.RowId)
*/
public void setRowId(int parameterIndex, RowId x) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setSQLXML(int, java.sql.SQLXML)
*/
public void setSQLXML(int parameterIndex, SQLXML xmlObject)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Statement#isClosed()
*/
public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Statement#isPoolable()
*/
public boolean isPoolable() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Statement#setPoolable(boolean)
*/
public void setPoolable(boolean poolable) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#isWrapperFor(java.lang.Class)
*/
public boolean isWrapperFor(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#unwrap(java.lang.Class)
*/
public Object unwrap(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/ProtocolException.java 0000644 0001750 0001750 00000002502 11316672660 027422 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
/**
* Exception class used to report errors in the TDS protocol.
*
* @author Mike Hutchinson
* @version $Id: ProtocolException.java,v 1.3 2005/04/20 16:49:23 alin_sinpalean Exp $
*/
public class ProtocolException extends Exception {
/**
* Construct a ProtocolException with message.
*
* @param message The explanatory message.
*/
public ProtocolException(String message) {
super(message);
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/ColInfo.java 0000644 0001750 0001750 00000005067 11316672660 025304 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
/**
* This class is a descriptor for result set columns.
* Driver.SQLSERVER or
* Driver.SYBASE.
*/
private final int serverType;
SQLException exceptions;
SQLWarning warnings;
void addWarning(SQLWarning w) {
if (warnings == null) {
warnings = w;
} else {
warnings.setNextWarning(w);
}
}
void addException(SQLException e) {
if (exceptions == null) {
exceptions = e;
} else {
exceptions.setNextException(e);
}
}
/**
* Create a dianostic SQLException or SQLWarning.
*
* @param number SQL Server error number.
* @param state SQL Server state code.
* @param serverity SQL Server serverity > 10 = error.
* @param message SQL Server error message text.
* @param server SQL Server name.
* @param procName SQL Server stored procedure name.
* @param line SQL Server error line number in SQL source.
*/
void addDiagnostic(int number,
int state,
int serverity,
String message,
String server,
String procName,
int line) {
if (serverity > 10) {
SQLException e = new SQLException(message,
getStateCode(number, serverType, "S1000"),
number);
//
// See if the driver should return a DataTrunction exception
//
if ((serverType == Driver.SQLSERVER &&
(number == 8152 ||
number == 8115 ||
number == 220)) ||
(serverType == Driver.SYBASE &&
(number == 247 ||
number == 9502))) {
SQLException tmp = e;
e = new DataTruncation(-1, false, false, -1, -1);
// Chain the original exception as this has useful info.
e.setNextException(tmp);
}
addException(e);
} else {
if (number == 0) {
// Output from a TransactSQL print statement.
SQLWarning w = new SQLWarning(message, null, 0);
addWarning(w);
} else {
SQLWarning w = new SQLWarning(message,
getStateCode(number, serverType, "01000"),
number);
addWarning(w);
}
}
}
/**
* Clear the warning chain.
*/
void clearWarnings() {
warnings = null;
}
/**
* Check the exception chain for errors and throw any found
* as an SQLException.
*
* @throws SQLException
*/
void checkErrors() throws SQLException {
if (exceptions != null) {
SQLException tmp = exceptions;
exceptions = null;
throw tmp;
}
}
/**
* Return the warning chain.
*
* @return The warning chain head as a SQLWarning.
*/
SQLWarning getWarnings() {
return warnings;
}
/**
* Create an SQL message for a specific server type.
*
* @param serverType either Driver.SQLSERVER or Driver.SYBASE
*/
SQLDiagnostic(final int serverType) {
this.serverType = serverType;
}
/**
* Map an SQL Server error code to an ANSI SQLSTATE code.
*
* @param number the SQL Server error number
* @param serverType Driver.SQLSERVER or Driver.SYBASE
* @param defState the default state code to return if the mapping fails
* @return the SQLSTATE code as a String
*/
private static String getStateCode(final int number,
final int serverType,
final String defState) {
final HashMap stateTable = (serverType == Driver.SYBASE) ? sybStates : mssqlStates;
final String state = (String) stateTable.get(new Integer(number));
if (state != null) {
return state;
}
return defState;
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/MSSqlServerInfo.java 0000644 0001750 0001750 00000015706 11316672660 026756 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.io.InterruptedIOException;
import java.sql.SQLException;
import java.net.*;
import net.sourceforge.jtds.util.Logger;
/**
* This class communicates with SQL Server 2k to determine what ports its
* instances are listening to. It does this by sending a UDP packet with the
* byte 0x02 in it, and parsing the response.
*
* < 00000000 05 ea 00 53 65 72 76 65 72 4e 61 6d 65 3b 42 52 # ...ServerName;BR
* < 00000010 49 4e 4b 4c 45 59 3b 49 6e 73 74 61 6e 63 65 4e # INKLEY;InstanceN
* < 00000020 61 6d 65 3b 4d 53 53 51 4c 53 45 52 56 45 52 3b # ame;MSSQLSERVER;
* < 00000030 49 73 43 6c 75 73 74 65 72 65 64 3b 4e 6f 3b 56 # IsClustered;No;V
* < 00000040 65 72 73 69 6f 6e 3b 38 2e 30 30 2e 31 39 34 3b # ersion;8.00.194;
* < 00000050 74 63 70 3b 31 34 33 33 3b 6e 70 3b 5c 5c 42 52 # tcp;1433;np;\\BR
* < 00000060 49 4e 4b 4c 45 59 5c 70 69 70 65 5c 73 71 6c 5c # INKLEY\pipe\sql\
* < 00000070 71 75 65 72 79 3b 3b 53 65 72 76 65 72 4e 61 6d # query;;ServerNam
* < 00000080 65 3b 42 52 49 4e 4b 4c 45 59 3b 49 6e 73 74 61 # e;BRINKLEY;Insta
* < 00000090 6e 63 65 4e 61 6d 65 3b 44 4f 47 3b 49 73 43 6c # nceName;DOG;IsCl
* < 000000a0 75 73 74 65 72 65 64 3b 4e 6f 3b 56 65 72 73 69 # ustered;No;Versi
* < 000000b0 6f 6e 3b 38 2e 30 30 2e 31 39 34 3b 74 63 70 3b # on;8.00.194;tcp;
* < 000000c0 33 35 34 36 3b 6e 70 3b 5c 5c 42 52 49 4e 4b 4c # 3546;np;\\BRINKL
* < 000000d0 45 59 5c 70 69 70 65 5c 4d 53 53 51 4c 24 44 4f # EY\pipe\MSSQL$DO
* < 000000e0 47 5c 73 71 6c 5c 71 75 65 72 79 3b 3b # G\sql\query;;
*
*
* @author Matt Brinkley
* @version $Id: MSSqlServerInfo.java,v 1.8.2.1 2009/07/30 10:50:05 ickzon Exp $
*/
public class MSSqlServerInfo {
private int numRetries = 3;
private int timeout = 2000;
private String[] serverInfoStrings;
public MSSqlServerInfo(String host) throws SQLException {
DatagramSocket socket = null;
try {
InetAddress addr = InetAddress.getByName(host);
socket = new DatagramSocket();
byte[] msg = new byte[] {0x02};
DatagramPacket p = new DatagramPacket(msg, msg.length, addr, 1434);
socket.send(p);
byte[] buf = new byte[4096];
p = new DatagramPacket(buf, buf.length);
socket.setSoTimeout(timeout);
for (int i = 0; i < numRetries; i++) {
try {
socket.receive(p);
String infoString = extractString(buf, p.getLength());
serverInfoStrings = split(infoString, ';');
return;
} catch (InterruptedIOException toEx) {
if (Logger.isActive()) {
Logger.logException(toEx);
}
}
}
} catch (Exception e) {
if (Logger.isActive()) {
Logger.logException(e);
}
} finally {
if (socket != null) {
socket.close();
}
}
throw new SQLException(
Messages.get("error.msinfo.badinfo", host), "HY000");
}
/**
* Call getInfo() before calling this method. It parses the info string
* returned from SQL Server and looks for the port for the given named
* instance. If it can't be found, or if getInfo() hadsn't been called,
* it returns -1.
*
* @param instanceName
* @return port the given instance is listening on, or -1 if it can't be
* found.
*/
public int getPortForInstance(String instanceName) throws SQLException {
if (serverInfoStrings == null) {
return -1;
}
// NOTE: default instance is called MSSQLSERVER
if (instanceName == null || instanceName.length() == 0) {
instanceName = "MSSQLSERVER";
}
String curInstance = null;
String curPort = null;
for (int index = 0; index < serverInfoStrings.length; index++) {
if (serverInfoStrings[index].length() == 0) {
curInstance = null;
curPort = null;
} else {
String key = serverInfoStrings[index];
String value = "";
index++;
if (index < serverInfoStrings.length) {
value = serverInfoStrings[index];
}
if ("InstanceName".equals(key)) {
curInstance = value;
}
if ("tcp".equals(key)) {
curPort = value;
}
if (curInstance != null
&& curPort != null
&& curInstance.equalsIgnoreCase(instanceName)) {
try {
return Integer.parseInt(curPort);
} catch (NumberFormatException e) {
throw new SQLException(
Messages.get("error.msinfo.badport", instanceName),
"HY000");
}
}
}
}
// didn't find it...
return -1;
}
private static final String extractString(byte[] buf, int len) {
// the first three bytes are unknown; after that, it should be a narrow string...
final int headerLength = 3;
return new String(buf, headerLength, len - headerLength);
}
public static String[] split(String s, int ch) {
int size = 0;
for (int pos = 0; pos != -1; pos = s.indexOf(ch, pos + 1), size++);
String res[] = new String[size];
int i = 0;
int p1 = 0;
int p2 = s.indexOf(ch);
do {
res[i++] = s.substring(p1, p2 == -1 ? s.length() : p2);
p1 = p2 + 1;
p2 = s.indexOf(ch, p1);
} while (p1 != 0);
return res;
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/ParamInfo.java 0000644 0001750 0001750 00000024020 11316672660 025615 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.sql.SQLException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
/**
* This class is a descriptor for procedure and prepared statement parameters.
*
* @author Mike Hutchinson
* @version $Id: ParamInfo.java,v 1.16 2005/04/25 11:47:01 alin_sinpalean Exp $
*/
class ParamInfo implements Cloneable {
/** Flag as an input parameter. */
final static int INPUT = 0;
/** Flag as an output parameter. */
final static int OUTPUT = 1;
/** Flag as an return value parameter. */
final static int RETVAL = 2;
/** Flag as a unicode parameter. */
final static int UNICODE = 4;
/** Internal TDS data type */
int tdsType;
/** JDBC type constant from java.sql.Types */
int jdbcType;
/** Formal parameter name eg @P1 */
String name;
/** SQL type name eg varchar(10) */
String sqlType;
/** Parameter offset in target SQL statement */
int markerPos = -1;
/** Current parameter value */
Object value;
/** Parameter decimal precision */
int precision = -1;
/** Parameter decimal scale */
int scale = -1;
/** Length of InputStream */
int length = -1;
/** Parameter is an output parameter */
boolean isOutput;
/** Parameter is used as SP return value */
boolean isRetVal;
/** IN parameter has been set */
boolean isSet;
/** Parameter should be sent as unicode */
boolean isUnicode;
/** TDS 8 Collation string. */
byte collation[];
/** Character set descriptor (if different from default) */
CharsetInfo charsetInfo;
/** OUT parameter value is set.*/
boolean isSetOut;
/** OUT Parameter value. */
Object outValue;
/**
* Construct a parameter with parameter marker offset.
*
* @param pos the offset of the ? symbol in the target SQL string
* @param isUnicode true if the parameter is Unicode encoded
*/
ParamInfo(int pos, boolean isUnicode) {
markerPos = pos;
this.isUnicode = isUnicode;
}
/**
* Construct a parameter for statement caching.
*
* @param name the formal name of the parameter
* @param pos the offset of the ? symbol in the parsed SQL string
* @param isRetVal true if the parameter is a return value
* @param isUnicode true if the parameter is Unicode encoded
*/
ParamInfo(String name, int pos, boolean isRetVal, boolean isUnicode) {
this.name = name;
this.markerPos = pos;
this.isRetVal = isRetVal;
this.isUnicode = isUnicode;
}
/**
* Construct an initialised parameter with extra attributes.
*
* @param jdbcType the java.sql.Type constant describing this type
* @param value the initial parameter value
* @param flags the additional attributes eg OUTPUT, RETVAL, UNICODE etc.
*/
ParamInfo(int jdbcType, Object value, int flags)
{
this.jdbcType = jdbcType;
this.value = value;
this.isSet = true;
this.isOutput = ((flags & OUTPUT) > 0) || ((flags & RETVAL) > 0);
this.isRetVal = ((flags & RETVAL)> 0);
this.isUnicode = ((flags & UNICODE) > 0);
if (value instanceof String) {
this.length = ((String)value).length();
} else
if (value instanceof byte[]) {
this.length = ((byte[])value).length;
}
}
/**
* Construct a parameter based on a result set column.
*
* @param ci the column descriptor
* @param name the name for this parameter or null
* @param value the column data value
* @param length the column data length
*/
ParamInfo(ColInfo ci, String name, Object value, int length) {
this.name = name;
this.tdsType = ci.tdsType;
this.scale = ci.scale;
this.precision = ci.precision;
this.jdbcType = ci.jdbcType;
this.sqlType = ci.sqlType;
this.collation = ci.collation;
this.charsetInfo = ci.charsetInfo;
this.isUnicode = TdsData.isUnicode(ci);
this.isSet = true;
this.value = value;
this.length = length;
}
/**
* Get the output parameter value.
*
* @return the OUT value as an Object
* @throws SQLException if the parameter has not been set
*/
Object getOutValue()
throws SQLException {
if (!isSetOut) {
throw new SQLException(
Messages.get("error.callable.outparamnotset"), "HY010");
}
return outValue;
}
/**
* Set the OUT parameter value.
* @param value The data value.
*/
void setOutValue(Object value) {
outValue= value;
isSetOut = true;
}
/**
* Clear the OUT parameter value and status.
*/
void clearOutValue()
{
outValue = null;
isSetOut = false;
}
/**
* Clear the IN parameter value and status.
*/
void clearInValue()
{
value = null;
isSet = false;
}
/**
* Get the string value of the parameter.
*
* @return The data value as a String or null.
*/
String getString(String charset) throws IOException {
if (value == null || value instanceof String) {
return (String) value;
}
if (value instanceof InputStream) {
try {
value = loadFromReader(new InputStreamReader((InputStream) value, charset), length);
length = ((String) value).length();
return (String) value;
} catch (UnsupportedEncodingException e) {
throw new IOException("I/O Error: UnsupportedEncodingException: "+ e.getMessage());
}
}
if (value instanceof Reader) {
value = loadFromReader((Reader)value, length);
return (String)value;
}
return value.toString();
}
/**
* Get the byte array value of the parameter.
*
* @return The data value as a byte[] or null.
*/
byte[] getBytes(String charset) throws IOException {
if (value == null || value instanceof byte[]) {
return (byte[])value;
}
if (value instanceof InputStream) {
value = loadFromStream((InputStream) value, length);
return (byte[]) value;
}
if (value instanceof Reader) {
String tmp = loadFromReader((Reader) value, length);
value = Support.encodeString(charset, tmp);
return (byte[]) value;
}
if (value instanceof String) {
return Support.encodeString(charset, (String) value);
}
return new byte[0];
}
/**
* Load a byte array from an InputStream
*
* @param in The InputStream to read from.
* @param length The length of the stream.
* @return The data as a byte[].
* @throws IOException
*/
private static byte[] loadFromStream(InputStream in, int length)
throws IOException {
byte[] buf = new byte[length];
int pos = 0, res;
while (pos != length && (res = in.read(buf, pos, length - pos)) != -1) {
pos += res;
}
if (pos != length) {
throw new java.io.IOException(
"Data in stream less than specified by length");
}
if (in.read() >= 0) {
throw new java.io.IOException(
"More data in stream than specified by length");
}
return buf;
}
/**
* Create a String from a Reader stream.
*
* @param in The Reader object with the data.
* @param length Number of characters to read.
* @return The data as a String.
* @throws IOException
*/
private static String loadFromReader(Reader in, int length)
throws IOException {
char[] buf = new char[length];
int pos = 0, res;
while (pos != length && (res = in.read(buf, pos, length - pos)) != -1) {
pos += res;
}
if (pos != length) {
throw new java.io.IOException(
"Data in stream less than specified by length");
}
if (in.read() >= 0) {
throw new java.io.IOException(
"More data in stream than specified by length");
}
return new String(buf);
}
/**
* Creates a shallow copy of this ParamInfo instance. Used by
* the PreparedStatement batching implementation to duplicate
* parameters.
*/
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException ex) {
// Will not happen
return null;
}
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/TypeInfo.java 0000644 0001750 0001750 00000023750 11316672660 025507 0 ustar martin martin //jTDS JDBC Driver for Microsoft SQL Server and Sybase
//Copyright (C) 2004 The jTDS Project
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
/**
* Represents an SQL data type as required by getTypeInfo().
* Provides a suitable natural ordering.
*
* This class probably shouldn't be public, but is required to be so by the
* tests.
*
* @author David Eaves
* @version $Id: TypeInfo.java,v 1.5 2005/07/27 11:02:34 alin_sinpalean Exp $
*/
public class TypeInfo implements Comparable {
static final int NUM_COLS = 18;
private final String typeName;
private final int dataType;
private final int precision;
private final String literalPrefix;
private final String literalSuffix;
private final String createParams;
private final short nullable;
private final boolean caseSensitive;
private final short searchable;
private final boolean unsigned;
private final boolean fixedPrecScale;
private final boolean autoIncrement;
private final String localTypeName;
private final short minimumScale;
private final short maximumScale;
private final int sqlDataType;
private final int sqlDatetimeSub;
private final int numPrecRadix;
private final int normalizedType;
private final int distanceFromJdbcType;
public TypeInfo(ResultSet rs, boolean useLOBs) throws SQLException {
typeName = rs.getString(1);
dataType = rs.getInt(2);
precision = rs.getInt(3);
literalPrefix = rs.getString(4);
literalSuffix = rs.getString(5);
createParams = rs.getString(6);
nullable = rs.getShort(7);
caseSensitive = rs.getBoolean(8);
searchable = rs.getShort(9);
unsigned = rs.getBoolean(10);
fixedPrecScale = rs.getBoolean(11);
autoIncrement = rs.getBoolean(12);
localTypeName = rs.getString(13);
if (rs.getMetaData().getColumnCount() >= 18) {
// Some servers provide more information
minimumScale = rs.getShort(14);
maximumScale = rs.getShort(15);
sqlDataType = rs.getInt(16);
sqlDatetimeSub = rs.getInt(17);
numPrecRadix = rs.getInt(18);
} else {
// Must initialize final fields
minimumScale = 0;
maximumScale = 0;
sqlDataType = 0;
sqlDatetimeSub = 0;
numPrecRadix = 0;
}
normalizedType = normalizeDataType(dataType, useLOBs);
distanceFromJdbcType = determineDistanceFromJdbcType();
}
/**
* For testing only. Create an instance with just the properties utilised
* in the compareTo() method (set name, type, and auto
* increment).
*/
public TypeInfo(String typeName, int dataType, boolean autoIncrement) {
this.typeName = typeName;
this.dataType = dataType;
this.autoIncrement = autoIncrement;
this.precision = 0;
this.literalPrefix = null;
this.literalSuffix = null;
this.createParams = null;
this.nullable = 0;
this.caseSensitive = false;
this.searchable = 0;
this.unsigned = false;
this.fixedPrecScale = false;
this.localTypeName = null;
this.minimumScale = 0;
this.maximumScale = 0;
this.sqlDataType = 0;
this.sqlDatetimeSub = 0;
this.numPrecRadix = 0;
normalizedType = normalizeDataType(dataType, true);
distanceFromJdbcType = determineDistanceFromJdbcType();
}
public boolean equals(Object o) {
if (o instanceof TypeInfo) {
return compareTo(o) == 0;
}
return false;
}
public int hashCode() {
return normalizedType * dataType * (autoIncrement ? 7 : 11);
}
public String toString() {
return typeName + " ("
+ (dataType != normalizedType ? dataType + "->" : "")
+ normalizedType + ')';
}
public void update(ResultSet rs) throws SQLException {
rs.updateString(1, typeName);
rs.updateInt(2, normalizedType);
rs.updateInt(3, precision);
rs.updateString(4, literalPrefix);
rs.updateString(5, literalSuffix);
rs.updateString(6, createParams);
rs.updateShort(7, nullable);
rs.updateBoolean(8, caseSensitive);
rs.updateShort(9, searchable);
rs.updateBoolean(10, unsigned);
rs.updateBoolean(11, fixedPrecScale);
rs.updateBoolean(12, autoIncrement);
rs.updateString(13, localTypeName);
if (rs.getMetaData().getColumnCount() >= 18) {
// Some servers provide more information
rs.updateShort(14, minimumScale);
rs.updateShort(15, maximumScale);
rs.updateInt(16, sqlDataType);
rs.updateInt(17, sqlDatetimeSub);
rs.updateInt(18, numPrecRadix);
}
}
/**
* Comparable implementation that orders by dataType, then by how closely
* the data type maps to the corresponding JDBC SQL type.
*
* The data type values for the non-standard SQL Server types tend to have
* negative numbers while the corresponding standard types have positive
* numbers so utilise that in the sorting.
*/
public int compareTo(Object o) {
TypeInfo other = ((TypeInfo) o);
// Order by normalised type, then proximity to standard JDBC type.
return compare(normalizedType, other.normalizedType) * 10 +
compare(distanceFromJdbcType, other.distanceFromJdbcType);
}
private int compare(int i1, int i2) {
return i1 < i2 ? -1 : (i1 == i2 ? 0 : 1);
}
/**
* Determine how close this type is to the corresponding JDBC type. Used in
* sorting to distinguish between types that have the same
* normalizedType value.
*
* @return positive integer indicating how far away the type is from the
* corresponding JDBC type, with zero being the nearest possible
* match and 9 being the least
*/
private int determineDistanceFromJdbcType() {
// TODO: Are these assumptions correct/complete?
switch (dataType) {
// Cases without an un-normalized alternative, so these are the
// best available
case 11: // Sybase DATETIME
case 10: // Sybase TIME
case 9: // Sybase DATE
case 6: // FLOAT
return 0;
case 12: // VARCHAR, SYSNAME and NVARCHAR all together with Sybase
if (typeName.equalsIgnoreCase("varchar")) {
return 0;
}
if (typeName.equalsIgnoreCase("nvarchar")) {
return 1;
}
return 2;
// Special case as the same data type value is used for SYSNAME and
// NVARCHAR (SYSNAME is essentially an alias for NVARCHAR). We
// don't want applications preferring SYSNAME.
case -9: // SYSNAME / NVARCHAR
return typeName.equalsIgnoreCase("sysname") ? 4 : 3;
// Particularly non-standard types
case -11: // UNIQUEIDENTIFIER
return 9;
case -150: // SQL_VARIANT
return 8;
// Default behaviour is to assume that if type has not been
// normalised it is the closest available match, unless it is an
// auto incrementing type
default:
return (dataType == normalizedType && !autoIncrement) ? 0 : 5;
}
}
/**
* Return a {@link java.sql.Types}-defined type for an SQL Server specific data type.
*
* @param serverDataType the data type, as returned by the server
* @param useLOBs whether LOB data types are used for large types
* @return the equivalent data type defined by java.sql.Types
*/
public static int normalizeDataType(int serverDataType, boolean useLOBs) {
switch (serverDataType) {
case 35: // Sybase UNIVARCHAR
return Types.VARCHAR;
case 11: // Sybase DATETIME
return Types.TIMESTAMP;
case 10: // Sybase TIME
return Types.TIME;
case 9: // Sybase DATE
return Types.DATE;
case 6: // FLOAT
return Types.DOUBLE;
case -1: // LONGVARCHAR
return useLOBs ? Types.CLOB : Types.LONGVARCHAR;
case -4: // LONGVARBINARY
return useLOBs ? Types.BLOB : Types.LONGVARBINARY;
case -8: // NCHAR
return Types.CHAR;
case -9: // SYSNAME / NVARCHAR
return Types.VARCHAR;
case -10: // NTEXT
return useLOBs ? Types.CLOB : Types.LONGVARCHAR;
case -11: // UNIQUEIDENTIFIER
return Types.CHAR;
case -150: // SQL_VARIANT
return Types.VARCHAR;
default:
return serverDataType;
}
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/Messages.java 0000644 0001750 0001750 00000013727 11316672660 025524 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.Map;
import java.util.ResourceBundle;
/**
* Support class for Messages.properties.
*
* @author David D. Kilzer
* @author Mike Hutchinson
* @version $Id: Messages.java,v 1.8 2005/04/20 16:49:22 alin_sinpalean Exp $
*/
public final class Messages {
/**
* Default name for resource bundle containing the messages.
*/
private static final String DEFAULT_RESOURCE = "net.sourceforge.jtds.jdbc.Messages";
/**
* Cached resource bundle containing the messages.
* ResourceBundle does caching internally but this caching
* involves a lot of string operations to generate the keys used for
* caching, leading to a lot of StringBuffer reallocation. In
* one run through the complete jTDS test suite there were over 60000
* allocations and reallocations (about one for each get()
* call).
*/
private static ResourceBundle defaultResource;
/**
* Default constructor. Private to prevent instantiation.
*/
private Messages() {
}
/**
* Get runtime message using supplied key.
*
* @param key The key of the message in Messages.properties
* @return The selected message as a String.
*/
public static String get(String key) {
return get(key, null);
}
/**
* Get runtime message using supplied key and substitute parameter
* into message.
*
* @param key The key of the message in Messages.properties
* @param param1 The object to insert into message.
* @return The selected message as a String.
*/
public static String get(String key, Object param1) {
Object args[] = {param1};
return get(key, args);
}
/**
* Get runtime message using supplied key and substitute parameters
* into message.
*
* @param key The key of the message in Messages.properties
* @param param1 The object to insert into message.
* @param param2 The object to insert into message.
* @return The selected message as a String.
*/
static String get(String key, Object param1, Object param2) {
Object args[] = {param1, param2};
return get(key, args);
}
/**
* Get runtime error using supplied key and substitute parameters
* into message.
*
* @param key The key of the error message in Messages.properties
* @param arguments The objects to insert into the message.
* @return The selected error message as a String.
*/
private static String get(String key, Object[] arguments) {
try {
ResourceBundle bundle = loadResourceBundle();
String formatString = bundle.getString(key);
// No need for any formatting if no parameters are specified
if (arguments == null || arguments.length == 0) {
return formatString;
} else {
MessageFormat formatter = new MessageFormat(formatString);
return formatter.format(arguments);
}
} catch (java.util.MissingResourceException mre) {
throw new RuntimeException("No message resource found for message property " + key);
}
}
/**
* Retrieve the list of driver property names and driver property
* descriptions from Messages.properties and populate
* them into {@link Map} objects.
* propertyMap and
* descriptionMap are guaranteed to match up as long
* as the properties defined in Messages.properties
* are well-formed.
*
* @param propertyMap The map of property names to be populated.
* @param descriptionMap The map of property descriptions to be populated.
*/
static void loadDriverProperties(Map propertyMap, Map descriptionMap) {
final ResourceBundle bundle = loadResourceBundle();
final Enumeration keys = bundle.getKeys();
while (keys.hasMoreElements()) {
final String key = (String) keys.nextElement();
final String descriptionPrefix = "prop.desc.";
final String propertyPrefix = "prop.";
if (key.startsWith(descriptionPrefix)) {
descriptionMap.put(key.substring(descriptionPrefix.length()), bundle.getString(key));
}
else if (key.startsWith(propertyPrefix)) {
propertyMap.put(key.substring(propertyPrefix.length()), bundle.getString(key));
}
}
}
/**
* Load the {@link #DEFAULT_RESOURCE} resource bundle.
*
* @return The resource bundle.
*/
private static ResourceBundle loadResourceBundle() {
if (defaultResource == null) {
defaultResource = ResourceBundle.getBundle(DEFAULT_RESOURCE);
}
return defaultResource;
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/NtlmAuth.java 0000644 0001750 0001750 00000032511 11316672660 025501 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import net.sourceforge.jtds.util.MD4Digest;
import net.sourceforge.jtds.util.DESEngine;
import net.sourceforge.jtds.util.MD5Digest;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
/**
* This class calculates the two "responses" to the nonce supplied by the server
* as a part of NTLM authentication.
*
* Much gratitude to the authors of this page, esp. for NTLMv2 info:
* http://davenport.sourceforge.net/ntlm.html
*
* @author Matt Brinkley
* @version $Id: NtlmAuth.java,v 1.7 2006/06/23 18:00:56 matt_brinkley Exp $
*/
public class NtlmAuth {
//-------------------------------------------------------------------------
// LM/NTLM - public interface
//-------------------------------------------------------------------------
public static byte[] answerNtChallenge(String password, byte[] nonce)
throws UnsupportedEncodingException {
return encryptNonce(ntHash(password), nonce);
}
public static byte[] answerLmChallenge(String pwd, byte[] nonce)
throws UnsupportedEncodingException {
byte[] password = convertPassword(pwd);
DESEngine d1 = new DESEngine(true, makeDESkey(password, 0));
DESEngine d2 = new DESEngine(true, makeDESkey(password, 7));
byte[] encrypted = new byte[21];
Arrays.fill(encrypted, (byte)0);
d1.processBlock(nonce, 0, encrypted, 0);
d2.processBlock(nonce, 0, encrypted, 8);
return encryptNonce(encrypted, nonce);
}
//-------------------------------------------------------------------------
// LM/NTLM v2 - public interface
//-------------------------------------------------------------------------
public static byte[] answerNtlmv2Challenge(
String domain, String user, String password, byte[] nonce,
byte[] targetInfo,
byte[] clientNonce)
throws UnsupportedEncodingException {
return answerNtlmv2Challenge(
domain, user, password, nonce, targetInfo, clientNonce,
System.currentTimeMillis());
}
public static byte[] answerNtlmv2Challenge(
String domain, String user, String password, byte[] nonce,
byte[] targetInfo,
byte[] clientNonce,
byte[] timestamp)
throws UnsupportedEncodingException {
byte[] hash = ntv2Hash(domain, user, password);
byte[] blob = createBlob(targetInfo, clientNonce, timestamp);
return lmv2Response(hash,blob,nonce);
}
public static byte[] answerNtlmv2Challenge(
String domain, String user, String password, byte[] nonce,
byte[] targetInfo,
byte[] clientNonce,
long now)
throws UnsupportedEncodingException {
return answerNtlmv2Challenge(
domain, user, password, nonce, targetInfo, clientNonce,
createTimestamp(now));
}
public static byte[] answerLmv2Challenge(
String domain, String user, String password, byte[] nonce, byte[] clientNonce)
throws UnsupportedEncodingException {
byte[] hash = ntv2Hash(domain, user, password);
return lmv2Response(hash, clientNonce, nonce);
}
//-------------------------------------------------------------------------
// LMv2/NTLMv2 impl helpers
//-------------------------------------------------------------------------
private static byte[] ntv2Hash(String domain, String user, String password)
throws UnsupportedEncodingException {
byte[] hash = ntHash(password);
String identity = user.toUpperCase() + domain.toUpperCase();
byte[] identityBytes = identity.getBytes("UnicodeLittleUnmarked");
return hmacMD5(identityBytes, hash);
}
/**
* Creates the LMv2 Response from the given hash, client data, and
* Type 2 challenge.
*
* @param hash The NTLMv2 Hash.
* @param clientData The client data (blob or client challenge).
* @param challenge The server challenge from the Type 2 message.
*
* @return The response (either NTLMv2 or LMv2, depending on the
* client data).
*/
private static byte[] lmv2Response(byte[] hash, byte[] clientData,
byte[] challenge)
{
byte[] data = new byte[challenge.length + clientData.length];
System.arraycopy(challenge, 0, data, 0, challenge.length);
System.arraycopy(clientData, 0, data, challenge.length,
clientData.length);
byte[] mac = hmacMD5(data, hash);
byte[] lmv2Response = new byte[mac.length + clientData.length];
System.arraycopy(mac, 0, lmv2Response, 0, mac.length);
System.arraycopy(clientData, 0, lmv2Response, mac.length, clientData.length);
return lmv2Response;
}
/**
* Calculates the HMAC-MD5 hash of the given data using the specified
* hashing key.
*
* @param data The data for which the hash will be calculated.
* @param key The hashing key.
*
* @return The HMAC-MD5 hash of the given data.
*/
private static byte[] hmacMD5(byte[] data, byte[] key)
{
byte[] ipad = new byte[64];
byte[] opad = new byte[64];
for (int i = 0; i < 64; i++) {
ipad[i] = (byte) 0x36;
opad[i] = (byte) 0x5c;
}
for (int i = key.length - 1; i >= 0; i--) {
ipad[i] ^= key[i];
opad[i] ^= key[i];
}
byte[] content = new byte[data.length + 64];
System.arraycopy(ipad, 0, content, 0, 64);
System.arraycopy(data, 0, content, 64, data.length);
data = md5(content);
content = new byte[data.length + 64];
System.arraycopy(opad, 0, content, 0, 64);
System.arraycopy(data, 0, content, 64, data.length);
return md5(content);
}
private static byte[] md5(byte[] data)
{
MD5Digest md5 = new MD5Digest();
md5.update(data, 0, data.length);
byte[] hash = new byte[16];
md5.doFinal(hash, 0);
return hash;
}
/**
* Implementation of HMAC-MD5 that uses the JDK's crypto API
* We don't use this because of JTDS's support of JDK 1.3.
*/
/*
private static byte[] hmacMD5(byte[] data, byte[] key)
throws NoSuchAlgorithmException, InvalidKeyException
{
SecretKey md5key = new SecretKeySpec( key, "HmacMD5" );
Mac mac = Mac.getInstance(md5key.getAlgorithm());
mac.init(md5key);
return mac.doFinal(data);
}
*/
/**
* Creates a timestamp in the format used in NTLMv2 responses.
* Public so it could be unit tested.
* @param time current time, as returned from System.currentTimeMillis
* @return little-endian byte array of number of tenths of microseconds since
* Jan 1, 1601
*/
public static byte[] createTimestamp(long time)
{
time += 11644473600000l; // milliseconds from January 1, 1601 -> epoch.
time *= 10000; // tenths of a microsecond.
// convert to little-endian byte array.
byte[] timestamp = new byte[8];
for (int i = 0; i < 8; i++) {
timestamp[i] = (byte) time;
time >>>= 8;
}
return timestamp;
}
/**
* Creates the NTLMv2 blob from the given target information block and
* client challenge.
*
* @param targetInformation The target information block from the Type 2
* message.
* @param clientChallenge The random 8-byte client challenge.
*
* @return The blob, used in the calculation of the NTLMv2 Response.
*/
private static byte[] createBlob(byte[] targetInformation,
byte[] clientChallenge,
byte[] timestamp) {
byte[] blobSignature = new byte[] {
(byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00
};
byte[] reserved = new byte[] {
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
};
byte[] unknown1 = new byte[] {
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
};
byte[] unknown2 = new byte[] {
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
};
byte[] blob = new byte[blobSignature.length + reserved.length +
timestamp.length + clientChallenge.length +
unknown1.length + targetInformation.length +
unknown2.length];
int offset = 0;
System.arraycopy(blobSignature, 0, blob, offset, blobSignature.length);
offset += blobSignature.length;
System.arraycopy(reserved, 0, blob, offset, reserved.length);
offset += reserved.length;
System.arraycopy(timestamp, 0, blob, offset, timestamp.length);
offset += timestamp.length;
System.arraycopy(clientChallenge, 0, blob, offset,
clientChallenge.length);
offset += clientChallenge.length;
System.arraycopy(unknown1, 0, blob, offset, unknown1.length);
offset += unknown1.length;
System.arraycopy(targetInformation, 0, blob, offset,
targetInformation.length);
offset += targetInformation.length;
System.arraycopy(unknown2, 0, blob, offset, unknown2.length);
return blob;
}
//-------------------------------------------------------------------------
// LM/NTLM impl helpers
//-------------------------------------------------------------------------
private static byte[] encryptNonce(byte[] key, byte[] nonce) {
byte[] out = new byte[24];
DESEngine d1 = new DESEngine(true, makeDESkey(key, 0));
DESEngine d2 = new DESEngine(true, makeDESkey(key, 7));
DESEngine d3 = new DESEngine(true, makeDESkey(key, 14));
d1.processBlock(nonce, 0, out, 0);
d2.processBlock(nonce, 0, out, 8);
d3.processBlock(nonce, 0, out, 16);
return out;
}
/**
* Creates the md4 hash of the unicode password. This is used as the DES
* key when encrypting the nonce for NTLM challenge-response
*/
private static byte[] ntHash(String password)
throws UnsupportedEncodingException {
byte[] key = new byte[21];
Arrays.fill(key, (byte)0);
byte[] pwd = password.getBytes("UnicodeLittleUnmarked");
// do the md4 hash of the unicode passphrase...
MD4Digest md4 = new MD4Digest();
md4.update(pwd, 0, pwd.length);
md4.doFinal(key, 0);
return key;
}
/**
* Used by answerNtlmChallenge. We need the password converted to caps,
* narrowed and padded/truncated to 14 chars...
*/
private static byte[] convertPassword(String password)
throws UnsupportedEncodingException {
byte[] pwd = password.toUpperCase().getBytes("UTF8");
byte[] rtn = new byte[14];
Arrays.fill(rtn, (byte) 0);
System.arraycopy(
pwd, 0, // src
rtn, 0, // dst
pwd.length > 14 ? 14 : pwd.length); // length
return rtn;
}
/**
* Turns a 7-byte DES key into an 8-byte one by adding parity bits. All
* implementations of DES seem to want an 8-byte key.
*/
private static byte[] makeDESkey(byte[] buf, int off) {
byte[] ret = new byte[8];
ret[0] = (byte) ((buf[off+0] >> 1) & 0xff);
ret[1] = (byte) ((((buf[off+0] & 0x01) << 6) | (((buf[off+1] & 0xff)>>2) & 0xff)) & 0xff);
ret[2] = (byte) ((((buf[off+1] & 0x03) << 5) | (((buf[off+2] & 0xff)>>3) & 0xff)) & 0xff);
ret[3] = (byte) ((((buf[off+2] & 0x07) << 4) | (((buf[off+3] & 0xff)>>4) & 0xff)) & 0xff);
ret[4] = (byte) ((((buf[off+3] & 0x0F) << 3) | (((buf[off+4] & 0xff)>>5) & 0xff)) & 0xff);
ret[5] = (byte) ((((buf[off+4] & 0x1F) << 2) | (((buf[off+5] & 0xff)>>6) & 0xff)) & 0xff);
ret[6] = (byte) ((((buf[off+5] & 0x3F) << 1) | (((buf[off+6] & 0xff)>>7) & 0xff)) & 0xff);
ret[7] = (byte) (buf[off+6] & 0x7F);
for (int i = 0; i < 8; i++) {
ret[i] = (byte) (ret[i] << 1);
}
return ret;
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/RequestStream.java 0000644 0001750 0001750 00000040362 11316672660 026554 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.math.BigInteger;
import net.sourceforge.jtds.util.*;
/**
* Class to implement an output stream for the server request.
*
*
*
* @author Mike Hutchinson.
* @version $Id: RequestStream.java,v 1.18 2005/09/21 21:50:34 ddkilzer Exp $
*/
public class RequestStream {
/** The shared network socket. */
private final SharedSocket socket;
/** The output packet buffer. */
private byte[] buffer;
/** The offset of the next byte to write. */
private int bufferPtr;
/** The request packet type. */
private byte pktType;
/** The unique stream id. */
private final int streamId;
/** True if stream is closed. */
private boolean isClosed;
/** The current output buffer size*/
private int bufferSize;
/** The maximum decimal precision. */
private int maxPrecision;
/**
* Construct a RequestStream object.
*
* @param socket the shared socket object to write to
* @param streamId the unique id for this stream
* @param bufferSize the initial buffer size to use (the current network
* packet size)
* @param maxPrecision the maximum precision for numeric/decimal types
*/
RequestStream(SharedSocket socket, int streamId, int bufferSize, int maxPrecision) {
this.streamId = streamId;
this.socket = socket;
this.bufferSize = bufferSize;
this.buffer = new byte[bufferSize];
this.bufferPtr = TdsCore.PKT_HDR_LEN;
this.maxPrecision = maxPrecision;
}
/**
* Set the output buffer size
*
* @param size The new buffer size (>= {@link TdsCore#MIN_PKT_SIZE} <= {@link TdsCore#MAX_PKT_SIZE}).
*/
void setBufferSize(int size) {
if (size < bufferPtr || size == bufferSize) {
return; // Can't shrink buffer size;
}
if (size < TdsCore.MIN_PKT_SIZE || size > TdsCore.MAX_PKT_SIZE) {
throw new IllegalArgumentException("Invalid buffer size parameter " + size);
}
byte[] tmp = new byte[size];
System.arraycopy(buffer, 0, tmp, 0, bufferPtr);
buffer = tmp;
}
/**
* Retrieve the current output packet size.
*
* @return the packet size as an int.
*/
int getBufferSize() {
return bufferSize;
}
/**
* Retrive the maximum decimal precision.
*
* @return The precision as an int.
*/
int getMaxPrecision() {
return this.maxPrecision;
}
/**
* Returns the maximum number of bytes required to output a decimal
* given the current {@link #maxPrecision}.
*
* @return the maximum number of bytes required to output a decimal.
*/
byte getMaxDecimalBytes() {
return (byte) ((maxPrecision <= TdsData.DEFAULT_PRECISION_28) ? 13 : 17);
}
/**
* Retrieve the unique stream id.
*
* @return the unique stream id as an int.
*/
int getStreamId() {
return this.streamId;
}
/**
* Set the current output packet type.
*
* @param pktType The packet type eg TdsCore.QUERY_PKT.
*/
void setPacketType(byte pktType) {
this.pktType = pktType;
}
/**
* Write a byte to the output stream.
*
* @param b The byte value to write.
* @throws IOException
*/
void write(byte b) throws IOException {
if (bufferPtr == buffer.length) {
putPacket(0);
}
buffer[bufferPtr++] = b;
}
/**
* Write an array of bytes to the output stream.
*
* @param b The byte array to write.
* @throws IOException
*/
void write(byte[] b) throws IOException {
int bytesToWrite = b.length;
int off = 0;
while (bytesToWrite > 0) {
int available = buffer.length - bufferPtr;
if (available == 0) {
putPacket(0);
continue;
}
int bc = (available > bytesToWrite) ? bytesToWrite : available;
System.arraycopy(b, off, buffer, bufferPtr, bc);
off += bc;
bufferPtr += bc;
bytesToWrite -= bc;
}
}
/**
* Write a partial byte buffer to the output stream.
*
* @param b The byte array buffer.
* @param off The offset into the byte array.
* @param len The number of bytes to write.
* @throws IOException
*/
void write(byte[] b, int off, int len) throws IOException {
int limit = (off + len) > b.length? b.length: off + len;
int bytesToWrite = limit - off;
int i = len - bytesToWrite;
while (bytesToWrite > 0) {
int available = buffer.length - bufferPtr;
if (available == 0) {
putPacket(0);
continue;
}
int bc = (available > bytesToWrite)? bytesToWrite: available;
System.arraycopy(b, off, buffer, bufferPtr, bc);
off += bc;
bufferPtr += bc;
bytesToWrite -= bc;
}
for (; i > 0; i--) {
write((byte) 0);
}
}
/**
* Write an int value to the output stream.
*
* @param i The int value to write.
* @throws IOException
*/
void write(int i) throws IOException {
write((byte) i);
write((byte) (i >> 8));
write((byte) (i >> 16));
write((byte) (i >> 24));
}
/**
* Write a short value to the output stream.
*
* @param s The short value to write.
* @throws IOException
*/
void write(short s) throws IOException {
write((byte) s);
write((byte) (s >> 8));
}
/**
* Write a long value to the output stream.
*
* @param l The long value to write.
* @throws IOException
*/
void write(long l) throws IOException {
write((byte) l);
write((byte) (l >> 8));
write((byte) (l >> 16));
write((byte) (l >> 24));
write((byte) (l >> 32));
write((byte) (l >> 40));
write((byte) (l >> 48));
write((byte) (l >> 56));
}
/**
* Write a double value to the output stream.
*
* @param f The double value to write.
* @throws IOException
*/
void write(double f) throws IOException {
long l = Double.doubleToLongBits(f);
write((byte) l);
write((byte) (l >> 8));
write((byte) (l >> 16));
write((byte) (l >> 24));
write((byte) (l >> 32));
write((byte) (l >> 40));
write((byte) (l >> 48));
write((byte) (l >> 56));
}
/**
* Write a float value to the output stream.
*
* @param f The float value to write.
* @throws IOException
*/
void write(float f) throws IOException {
int l = Float.floatToIntBits(f);
write((byte) l);
write((byte) (l >> 8));
write((byte) (l >> 16));
write((byte) (l >> 24));
}
/**
* Write a String object to the output stream.
* If the TDS version is >= 7.0 write a UNICODE string otherwise
* wrote a translated byte stream.
*
* @param s The String to write.
* @throws IOException
*/
void write(String s) throws IOException {
if (socket.getTdsVersion() >= Driver.TDS70) {
int len = s.length();
for (int i = 0; i < len; ++i) {
int c = s.charAt(i);
if (bufferPtr == buffer.length) {
putPacket(0);
}
buffer[bufferPtr++] = (byte) c;
if (bufferPtr == buffer.length) {
putPacket(0);
}
buffer[bufferPtr++] = (byte) (c >> 8);
}
} else {
writeAscii(s);
}
}
/**
* Write a char array object to the output stream.
*
* @param s The char[] to write.
* @throws IOException
*/
void write(char s[], int off, int len) throws IOException {
int i = off;
int limit = (off + len) > s.length ? s.length : off + len;
for ( ; i < limit; i++) {
char c = s[i];
if (bufferPtr == buffer.length) {
putPacket(0);
}
buffer[bufferPtr++] = (byte) c;
if (bufferPtr == buffer.length) {
putPacket(0);
}
buffer[bufferPtr++] = (byte) (c >> 8);
}
}
/**
* Write a String to the output stream as translated bytes.
*
* @param s The String to write.
* @throws IOException
*/
void writeAscii(String s) throws IOException {
String charsetName = socket.getCharset();
if (charsetName != null) {
try {
write(s.getBytes(charsetName));
} catch (UnsupportedEncodingException e) {
write(s.getBytes());
}
} else {
write(s.getBytes());
}
}
/**
* Copy the contents of an InputStream to the server.
*
* @param in The InputStream to read.
* @param length The length of the stream.
* @throws IOException
*/
void writeStreamBytes(InputStream in, int length) throws IOException {
byte buffer[] = new byte[1024];
while (length > 0) {
int res = in.read(buffer);
if (res < 0) {
throw new java.io.IOException(
"Data in stream less than specified by length");
}
write(buffer, 0, res);
length -= res;
}
// XXX Not sure that this is actually an error
if (length < 0 || in.read() >= 0) {
throw new java.io.IOException(
"More data in stream than specified by length");
}
}
/**
* Copy the contents of a Reader stream to the server.
*
* @param in The Reader object with the data.
* @param length The length of the data in characters.
* @throws IOException
*/
void writeReaderChars(Reader in, int length) throws IOException {
char cbuffer[] = new char[512];
byte bbuffer[] = new byte[1024];
while (length > 0) {
int res = in.read(cbuffer);
if (res < 0) {
throw new java.io.IOException(
"Data in stream less than specified by length");
}
for (int i = 0, j = -1; i < res; i++) {
bbuffer[++j] = (byte) cbuffer[i];
bbuffer[++j] = (byte) (cbuffer[i] >> 8);
}
write(bbuffer, 0, res * 2);
length -= res;
}
// XXX Not sure that this is actually an error
if (length < 0 || in.read() >= 0) {
throw new java.io.IOException(
"More data in stream than specified by length");
}
}
/**
* Copy the contents of a Reader stream to the server as bytes.
* int.
*/
int getTdsVersion() {
return socket.getTdsVersion();
}
/**
* Retrieve the Server type.
*
* @return The Server type as an int.
*/
int getServerType() {
return socket.serverType;
}
/**
* Write the TDS packet to the network.
*
* @param last Set to 1 if this is the last packet else 0.
* @throws IOException
*/
private void putPacket(int last) throws IOException {
if (isClosed) {
throw new IOException("RequestStream is closed");
}
buffer[0] = pktType;
buffer[1] = (byte) last; // last segment indicator
buffer[2] = (byte) (bufferPtr >> 8);
buffer[3] = (byte) bufferPtr;
buffer[4] = 0;
buffer[5] = 0;
buffer[6] = (byte) ((socket.getTdsVersion() >= Driver.TDS70) ? 1 : 0);
buffer[7] = 0;
if (Logger.isActive()) {
Logger.logPacket(streamId, false, buffer);
}
buffer = socket.sendNetPacket(streamId, buffer);
bufferPtr = TdsCore.PKT_HDR_LEN;
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/JtdsCallableStatement.java 0000644 0001750 0001750 00000113553 11316672660 030164 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.net.MalformedURLException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Map;
/**
* jTDS implementation of the java.sql.CallableStatement interface.
*
*
*
* @author Mike Hutchinson
* @version $Id: JtdsCallableStatement.java,v 1.23.2.4 2009/12/30 11:37:21 ickzon Exp $
*/
public class JtdsCallableStatement extends JtdsPreparedStatement implements CallableStatement {
/** Last parameter retrieved was null. */
protected boolean paramWasNull;
/**
* Construct a CallableStatement object.
*
* @param connection The connection owning this statement.
* @param sql The SQL statement specifying the procedure to call.
* @param resultSetType The result set type eg FORWARD_ONLY.
* @param concurrency The result set concurrency eg READ_ONLY.
* @throws SQLException
*/
JtdsCallableStatement(ConnectionJDBC2 connection, String sql, int resultSetType, int concurrency)
throws SQLException {
super(connection, sql, resultSetType, concurrency, false);
}
/**
* Find a parameter by name.
*
* @param name The name of the parameter to locate.
* @param set True if function is called from a set / register method.
* @return The parameter index as an int.
* @throws SQLException
*/
int findParameter(String name, boolean set)
throws SQLException {
checkOpen();
for (int i = 0; i < parameters.length; i++){
if (parameters[i].name != null && parameters[i].name.equalsIgnoreCase(name))
return i + 1;
}
if (set && !name.equalsIgnoreCase("@return_status")) {
for (int i = 0; i < parameters.length; i++){
if (parameters[i].name == null) {
parameters[i].name = name;
return i + 1;
}
}
}
throw new SQLException(Messages.get("error.callable.noparam", name), "07000");
}
/**
* Retrieve the value of an output parameter.
*
* @param parameterIndex the ordinal position of the parameter
* @return the parameter value as an Object
* @throws SQLException if the parameter has not been set
*/
protected Object getOutputValue(int parameterIndex)
throws SQLException {
checkOpen();
ParamInfo parameter = getParameter(parameterIndex);
if (!parameter.isOutput) {
throw new SQLException(
Messages.get("error.callable.notoutput",
new Integer(parameterIndex)),
"07000");
}
Object value = parameter.getOutValue();
paramWasNull = (value == null);
return value;
}
/**
* Check that this statement is still open.
*
* @throws SQLException if statement closed.
*/
protected void checkOpen() throws SQLException {
if (closed) {
throw new SQLException(
Messages.get("error.generic.closed", "CallableStatement"), "HY010");
}
}
/**
* Execute the SQL batch on a MS server.
* @param size the total size of the batch.
* @param executeSize the maximum number of statements to send in one request.
* @param counts the returned update counts.
* @return Chained exceptions linked to a SQLException.
* @throws SQLException
*/
protected SQLException executeMSBatch(int size, int executeSize, ArrayList counts)
throws SQLException {
if (parameters.length == 0) {
// No parameters so we can execute as a simple batch
return super.executeMSBatch(size, executeSize, counts);
}
SQLException sqlEx = null;
for (int i = 0; i < size;) {
Object value = batchValues.get(i);
++i;
// Execute batch now if max size reached or end of batch
boolean executeNow = (i % executeSize == 0) || i == size;
tds.startBatch();
tds.executeSQL(sql, procName, (ParamInfo[]) value, false, 0, -1, -1, executeNow);
// If the batch has been sent, process the results
if (executeNow) {
sqlEx = tds.getBatchCounts(counts, sqlEx);
// If a serious error then we stop execution now as count
// is too small.
if (sqlEx != null && counts.size() != i) {
break;
}
}
}
return sqlEx;
}
/**
* Execute the SQL batch on a Sybase server.
*
* For the rare case of CallableStatement batches each statement is executed individually. This ensures that
* problems with the server reading into the middle of a statement are avoided. See bug report [1374518] for more
* details.
*
* @param size the total size of the batch
* @param executeSize the maximum number of statements to send in one request (ignored for this version of the
* method as only one statement will be sent at a time)
* @param counts the returned update counts
* @return chained exceptions linked to a SQLException
* @throws SQLException if a serious error occurs during execution
*/
protected SQLException executeSybaseBatch(int size, int executeSize, ArrayList counts)
throws SQLException
{
if (parameters.length == 0) {
// No parameters so we can execute as a simple batch
return super.executeSybaseBatch(size, executeSize, counts);
}
SQLException sqlEx = null;
for (int i = 0; i < size;) {
Object value = batchValues.get(i);
++i;
tds.executeSQL(sql, procName, (ParamInfo[]) value, false, 0, -1, -1, true);
// If the batch has been sent, process the results
sqlEx = tds.getBatchCounts(counts, sqlEx);
// If a serious error then we stop execution now as count
// is too small.
if (sqlEx != null && counts.size() != i) {
break;
}
}
return sqlEx;
}
// ---------- java.sql.CallableStatement methods follow ----------
public boolean wasNull() throws SQLException {
checkOpen();
return paramWasNull;
}
public byte getByte(int parameterIndex) throws SQLException {
return ((Integer) Support.convert(this, getOutputValue(parameterIndex), java.sql.Types.TINYINT, null)).byteValue();
}
public double getDouble(int parameterIndex) throws SQLException {
return ((Double) Support.convert(this, getOutputValue(parameterIndex), java.sql.Types.DOUBLE, null)).doubleValue();
}
public float getFloat(int parameterIndex) throws SQLException {
return ((Float) Support.convert(this, getOutputValue(parameterIndex), java.sql.Types.REAL, null)).floatValue();
}
public int getInt(int parameterIndex) throws SQLException {
return ((Integer) Support.convert(this, getOutputValue(parameterIndex), java.sql.Types.INTEGER, null)).intValue();
}
public long getLong(int parameterIndex) throws SQLException {
return ((Long) Support.convert(this, getOutputValue(parameterIndex), java.sql.Types.BIGINT, null)).longValue();
}
public short getShort(int parameterIndex) throws SQLException {
return ((Integer) Support.convert(this, getOutputValue(parameterIndex), java.sql.Types.SMALLINT, null)).shortValue();
}
public boolean getBoolean(int parameterIndex) throws SQLException {
return ((Boolean) Support.convert(this, getOutputValue(parameterIndex), BOOLEAN, null)).booleanValue();
}
public byte[] getBytes(int parameterIndex) throws SQLException {
checkOpen();
return ((byte[]) Support.convert(this, getOutputValue(parameterIndex), java.sql.Types.VARBINARY, connection.getCharset()));
}
public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException {
if (sqlType == java.sql.Types.DECIMAL
|| sqlType == java.sql.Types.NUMERIC) {
registerOutParameter(parameterIndex, sqlType, TdsData.DEFAULT_SCALE);
} else {
registerOutParameter(parameterIndex, sqlType, 0);
}
}
public void registerOutParameter(int parameterIndex, int sqlType, int scale)
throws SQLException {
checkOpen();
if (scale < 0 || scale > connection.getMaxPrecision()) {
throw new SQLException(Messages.get("error.generic.badscale"), "HY092");
}
ParamInfo pi = getParameter(parameterIndex);
pi.isOutput = true;
if ("ERROR".equals(Support.getJdbcTypeName(sqlType))) {
throw new SQLException(Messages.get("error.generic.badtype",
Integer.toString(sqlType)), "HY092");
}
if (sqlType == java.sql.Types.CLOB) {
pi.jdbcType = java.sql.Types.LONGVARCHAR;
} else if (sqlType == java.sql.Types.BLOB) {
pi.jdbcType = java.sql.Types.LONGVARBINARY;
} else {
pi.jdbcType = sqlType;
}
pi.scale = scale;
}
public Object getObject(int parameterIndex) throws SQLException {
Object value = getOutputValue(parameterIndex);
// Don't return UniqueIdentifier objects as the user won't know how to
// handle them
if (value instanceof UniqueIdentifier) {
return value.toString();
}
// If the user requested String/byte[] instead of LOBs, do the conversion
if (!connection.getUseLOBs()) {
value = Support.convertLOB(value);
}
return value;
}
public String getString(int parameterIndex) throws SQLException {
checkOpen();
return (String) Support.convert(this, getOutputValue(parameterIndex),
java.sql.Types.VARCHAR, connection.getCharset());
}
public void registerOutParameter(int parameterIndex, int sqlType, String typeName)
throws SQLException {
notImplemented("CallableStatement.registerOutParameter(int, int, String");
}
public byte getByte(String parameterName) throws SQLException {
return getByte(findParameter(parameterName, false));
}
public double getDouble(String parameterName) throws SQLException {
return getDouble(findParameter(parameterName, false));
}
public float getFloat(String parameterName) throws SQLException {
return getFloat(findParameter(parameterName, false));
}
public int getInt(String parameterName) throws SQLException {
return getInt(findParameter(parameterName, false));
}
public long getLong(String parameterName) throws SQLException {
return getLong(findParameter(parameterName, false));
}
public short getShort(String parameterName) throws SQLException {
return getShort(findParameter(parameterName, false));
}
public boolean getBoolean(String parameterName) throws SQLException {
return getBoolean(findParameter(parameterName, false));
}
public byte[] getBytes(String parameterName) throws SQLException {
return getBytes(findParameter(parameterName, false));
}
public void setByte(String parameterName, byte x) throws SQLException {
setByte(findParameter(parameterName, true), x);
}
public void setDouble(String parameterName, double x) throws SQLException {
setDouble(findParameter(parameterName, true), x);
}
public void setFloat(String parameterName, float x) throws SQLException {
setFloat(findParameter(parameterName, true), x);
}
public void registerOutParameter(String parameterName, int sqlType)
throws SQLException {
registerOutParameter(findParameter(parameterName, true), sqlType);
}
public void setInt(String parameterName, int x) throws SQLException {
setInt(findParameter(parameterName, true), x);
}
public void setNull(String parameterName, int sqlType) throws SQLException {
setNull(findParameter(parameterName, true), sqlType);
}
public void registerOutParameter(String parameterName, int sqlType, int scale)
throws SQLException {
registerOutParameter(findParameter(parameterName, true), sqlType, scale);
}
public void setLong(String parameterName, long x) throws SQLException {
setLong(findParameter(parameterName, true), x);
}
public void setShort(String parameterName, short x) throws SQLException {
setShort(findParameter(parameterName, true), x);
}
public void setBoolean(String parameterName, boolean x) throws SQLException {
setBoolean(findParameter(parameterName, true), x);
}
public void setBytes(String parameterName, byte[] x) throws SQLException {
setBytes(findParameter(parameterName, true), x);
}
public BigDecimal getBigDecimal(int parameterIndex) throws SQLException {
return (BigDecimal) Support.convert(this,
getOutputValue(parameterIndex), java.sql.Types.DECIMAL, null);
}
public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException {
BigDecimal bd = (BigDecimal) Support.convert(this,
getOutputValue(parameterIndex), java.sql.Types.DECIMAL, null);
return bd.setScale(scale);
}
public URL getURL(int parameterIndex) throws SQLException {
checkOpen();
String url = (String) Support.convert(this,
getOutputValue(parameterIndex), java.sql.Types.VARCHAR,
connection.getCharset());
try {
return new java.net.URL(url);
} catch (MalformedURLException e) {
throw new SQLException(Messages.get("error.resultset.badurl", url), "22000");
}
}
public Array getArray(int parameterIndex) throws SQLException {
notImplemented("CallableStatement.getArray");
return null;
}
public Blob getBlob(int parameterIndex) throws SQLException {
byte[] value = getBytes(parameterIndex);
if (value == null) {
return null;
}
return new BlobImpl(connection, value);
}
public Clob getClob(int parameterIndex) throws SQLException {
String value = getString(parameterIndex);
if (value == null) {
return null;
}
return new ClobImpl(connection, value);
}
public Date getDate(int parameterIndex) throws SQLException {
return (java.sql.Date) Support.convert(this,
getOutputValue(parameterIndex), java.sql.Types.DATE, null);
}
public Ref getRef(int parameterIndex) throws SQLException {
notImplemented("CallableStatement.getRef");
return null;
}
public Time getTime(int parameterIndex) throws SQLException {
return (Time) Support.convert(this, getOutputValue(parameterIndex), java.sql.Types.TIME, null);
}
public Timestamp getTimestamp(int parameterIndex) throws SQLException {
return (Timestamp) Support.convert(this, getOutputValue(parameterIndex), java.sql.Types.TIMESTAMP, null);
}
public void setAsciiStream(String parameterName, InputStream x, int length)
throws SQLException {
setAsciiStream(findParameter(parameterName, true), x, (int)length);
}
public void setBinaryStream(String parameterName, InputStream x, int length)
throws SQLException {
setBinaryStream(findParameter(parameterName, true), x, length);
}
public void setCharacterStream(String parameterName, Reader reader, int length)
throws SQLException {
setCharacterStream(findParameter(parameterName, true), reader, length);
}
public Object getObject(String parameterName) throws SQLException {
return getObject(findParameter(parameterName, false));
}
public void setObject(String parameterName, Object x) throws SQLException {
setObject(findParameter(parameterName, true), x);
}
public void setObject(String parameterName, Object x, int targetSqlType)
throws SQLException {
setObject(findParameter(parameterName, true), x, targetSqlType);
}
public void setObject(String parameterName, Object x, int targetSqlType, int scale)
throws SQLException {
setObject(findParameter(parameterName, true), x, targetSqlType, scale);
}
public Object getObject(int parameterIndex, Map map) throws SQLException {
notImplemented("CallableStatement.getObject(int, Map)");
return null;
}
public String getString(String parameterName) throws SQLException {
return getString(findParameter(parameterName, false));
}
public void registerOutParameter(String parameterName, int sqlType, String typeName)
throws SQLException {
notImplemented("CallableStatement.registerOutParameter(String, int, String");
}
public void setNull(String parameterName, int sqlType, String typeName)
throws SQLException {
notImplemented("CallableStatement.setNull(String, int, String");
}
public void setString(String parameterName, String x) throws SQLException {
setString(findParameter(parameterName, true), x);
}
public BigDecimal getBigDecimal(String parameterName) throws SQLException {
return getBigDecimal(findParameter(parameterName, false));
}
public void setBigDecimal(String parameterName, BigDecimal x)
throws SQLException {
setBigDecimal(findParameter(parameterName, true), x);
}
public URL getURL(String parameterName) throws SQLException {
return getURL(findParameter(parameterName, false));
}
public void setURL(String parameterName, URL x) throws SQLException {
setObject(findParameter(parameterName, true), x);
}
public Array getArray(String parameterName) throws SQLException {
return getArray(findParameter(parameterName, false));
}
public Blob getBlob(String parameterName) throws SQLException {
return getBlob(findParameter(parameterName, false));
}
public Clob getClob(String parameterName) throws SQLException {
return getClob(findParameter(parameterName, false));
}
public Date getDate(String parameterName) throws SQLException {
return getDate(findParameter(parameterName, false));
}
public void setDate(String parameterName, Date x) throws SQLException {
setDate(findParameter(parameterName, true), x);
}
public Date getDate(int parameterIndex, Calendar cal) throws SQLException {
java.sql.Date date = getDate(parameterIndex);
if (date != null && cal != null) {
date = new java.sql.Date(Support.timeToZone(date, cal));
}
return date;
}
public Ref getRef(String parameterName) throws SQLException {
return getRef(findParameter(parameterName, false));
}
public Time getTime(String parameterName) throws SQLException {
return getTime(findParameter(parameterName, false));
}
public void setTime(String parameterName, Time x) throws SQLException {
setTime(findParameter(parameterName, true), x);
}
public Time getTime(int parameterIndex, Calendar cal) throws SQLException {
java.sql.Time time = getTime(parameterIndex);
if (time != null && cal != null) {
time = new java.sql.Time(Support.timeToZone(time, cal));
}
return time;
}
public Timestamp getTimestamp(String parameterName) throws SQLException {
return getTimestamp(findParameter(parameterName, false));
}
public void setTimestamp(String parameterName, Timestamp x) throws SQLException {
setTimestamp(findParameter(parameterName, true), x);
}
public Timestamp getTimestamp(int parameterIndex, Calendar cal)
throws SQLException {
Timestamp timestamp = getTimestamp(parameterIndex);
if (timestamp != null && cal != null) {
timestamp = new Timestamp(Support.timeToZone(timestamp, cal));
}
return timestamp;
}
public Object getObject(String parameterName, Map map) throws SQLException {
return getObject(findParameter(parameterName, false), map);
}
public Date getDate(String parameterName, Calendar cal) throws SQLException {
return getDate(findParameter(parameterName, false), cal);
}
public Time getTime(String parameterName, Calendar cal) throws SQLException {
return getTime(findParameter(parameterName, false), cal);
}
public Timestamp getTimestamp(String parameterName, Calendar cal)
throws SQLException {
return getTimestamp(findParameter(parameterName, false), cal);
}
public void setDate(String parameterName, Date x, Calendar cal)
throws SQLException {
setDate(findParameter(parameterName, true), x, cal);
}
public void setTime(String parameterName, Time x, Calendar cal)
throws SQLException {
setTime(findParameter(parameterName, true), x, cal);
}
public void setTimestamp(String parameterName, Timestamp x, Calendar cal)
throws SQLException {
setTimestamp(findParameter(parameterName, true), x, cal);
}
/////// JDBC4 demarcation, do NOT put any JDBC3 code below this line ///////
/* (non-Javadoc)
* @see java.sql.CallableStatement#getCharacterStream(int)
*/
public Reader getCharacterStream(int parameterIndex) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getCharacterStream(java.lang.String)
*/
public Reader getCharacterStream(String parameterName) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getNCharacterStream(int)
*/
public Reader getNCharacterStream(int parameterIndex) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getNCharacterStream(java.lang.String)
*/
public Reader getNCharacterStream(String parameterName) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getNClob(int)
*/
public NClob getNClob(int parameterIndex) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getNClob(java.lang.String)
*/
public NClob getNClob(String parameterName) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getNString(int)
*/
public String getNString(int parameterIndex) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getNString(java.lang.String)
*/
public String getNString(String parameterName) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getRowId(int)
*/
public RowId getRowId(int parameterIndex) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getRowId(java.lang.String)
*/
public RowId getRowId(String parameterName) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getSQLXML(int)
*/
public SQLXML getSQLXML(int parameterIndex) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getSQLXML(java.lang.String)
*/
public SQLXML getSQLXML(String parameterName) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setAsciiStream(java.lang.String, java.io.InputStream)
*/
public void setAsciiStream(String parameterName, InputStream x)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setAsciiStream(java.lang.String, java.io.InputStream, long)
*/
public void setAsciiStream(String parameterName, InputStream x, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setBinaryStream(java.lang.String, java.io.InputStream)
*/
public void setBinaryStream(String parameterName, InputStream x)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setBinaryStream(java.lang.String, java.io.InputStream, long)
*/
public void setBinaryStream(String parameterName, InputStream x, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setBlob(java.lang.String, java.sql.Blob)
*/
public void setBlob(String parameterName, Blob x) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setBlob(java.lang.String, java.io.InputStream)
*/
public void setBlob(String parameterName, InputStream inputStream)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setBlob(java.lang.String, java.io.InputStream, long)
*/
public void setBlob(String parameterName, InputStream inputStream,
long length) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setCharacterStream(java.lang.String, java.io.Reader)
*/
public void setCharacterStream(String parameterName, Reader reader)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setCharacterStream(java.lang.String, java.io.Reader, long)
*/
public void setCharacterStream(String parameterName, Reader reader,
long length) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setClob(java.lang.String, java.sql.Clob)
*/
public void setClob(String parameterName, Clob x) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setClob(java.lang.String, java.io.Reader)
*/
public void setClob(String parameterName, Reader reader)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setClob(java.lang.String, java.io.Reader, long)
*/
public void setClob(String parameterName, Reader reader, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setNCharacterStream(java.lang.String, java.io.Reader)
*/
public void setNCharacterStream(String parameterName, Reader value)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setNCharacterStream(java.lang.String, java.io.Reader, long)
*/
public void setNCharacterStream(String parameterName, Reader value,
long length) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setNClob(java.lang.String, java.sql.NClob)
*/
public void setNClob(String parameterName, NClob value) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setNClob(java.lang.String, java.io.Reader)
*/
public void setNClob(String parameterName, Reader reader)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setNClob(java.lang.String, java.io.Reader, long)
*/
public void setNClob(String parameterName, Reader reader, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setNString(java.lang.String, java.lang.String)
*/
public void setNString(String parameterName, String value)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setRowId(java.lang.String, java.sql.RowId)
*/
public void setRowId(String parameterName, RowId x) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setSQLXML(java.lang.String, java.sql.SQLXML)
*/
public void setSQLXML(String parameterName, SQLXML xmlObject)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setAsciiStream(int, java.io.InputStream)
*/
public void setAsciiStream(int parameterIndex, InputStream x)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setBinaryStream(int, java.io.InputStream)
*/
public void setBinaryStream(int parameterIndex, InputStream x)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setBlob(int, java.io.InputStream)
*/
public void setBlob(int parameterIndex, InputStream inputStream)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setBlob(int, java.io.InputStream, long)
*/
public void setBlob(int parameterIndex, InputStream inputStream, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setCharacterStream(int, java.io.Reader)
*/
public void setCharacterStream(int parameterIndex, Reader reader)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setClob(int, java.io.Reader)
*/
public void setClob(int parameterIndex, Reader reader) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setClob(int, java.io.Reader, long)
*/
public void setClob(int parameterIndex, Reader reader, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNCharacterStream(int, java.io.Reader)
*/
public void setNCharacterStream(int parameterIndex, Reader value)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNCharacterStream(int, java.io.Reader, long)
*/
public void setNCharacterStream(int parameterIndex, Reader value,
long length) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNClob(int, java.sql.NClob)
*/
public void setNClob(int parameterIndex, NClob value) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNClob(int, java.io.Reader)
*/
public void setNClob(int parameterIndex, Reader reader) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNClob(int, java.io.Reader, long)
*/
public void setNClob(int parameterIndex, Reader reader, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNString(int, java.lang.String)
*/
public void setNString(int parameterIndex, String value)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setRowId(int, java.sql.RowId)
*/
public void setRowId(int parameterIndex, RowId x) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setSQLXML(int, java.sql.SQLXML)
*/
public void setSQLXML(int parameterIndex, SQLXML xmlObject)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Statement#isClosed()
*/
public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Statement#isPoolable()
*/
public boolean isPoolable() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Statement#setPoolable(boolean)
*/
public void setPoolable(boolean poolable) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#isWrapperFor(java.lang.Class)
*/
public boolean isWrapperFor(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#unwrap(java.lang.Class)
*/
public Object unwrap(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/SharedSocket.java 0000644 0001750 0001750 00000110411 11316672660 026320 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.LinkedList;
import javax.net.SocketFactory;
import net.sourceforge.jtds.ssl.*;
import net.sourceforge.jtds.util.Logger;
/**
* This class mananges the physical connection to the SQL Server and
* serialises its use amongst a number of virtual sockets.
* This allows one physical connection to service a number of concurrent
* statements.
*
*
*
SharedSocket object specifying host name and
* port.
*
* @param connection the connection object
* @throws IOException if socket open fails
*/
SharedSocket(ConnectionJDBC2 connection) throws IOException, UnknownHostException {
this(connection.getBufferDir(), connection.getTdsVersion(), connection.getServerType());
this.host = connection.getServerName();
this.port = connection.getPortNumber();
if (Driver.JDBC3) {
this.socket = createSocketForJDBC3(connection);
} else {
this.socket = new Socket(this.host, this.port);
}
setOut(new DataOutputStream(socket.getOutputStream()));
setIn(new DataInputStream(socket.getInputStream()));
this.socket.setTcpNoDelay(connection.getTcpNoDelay());
this.socket.setSoTimeout(connection.getSocketTimeout() * 1000);
this.socket.setKeepAlive(connection.getSocketKeepAlive());
}
/**
* Creates a {@link Socket} through reflection when {@link Driver#JDBC3}
* is true. Reflection must be used to stay compatible
* with JDK 1.3.
*
* @param connection the connection object
* @return a socket open to the host and port with the given timeout
* @throws IOException if socket open fails
*/
private Socket createSocketForJDBC3(ConnectionJDBC2 connection) throws IOException {
final String host = connection.getServerName();
final int port = connection.getPortNumber();
final int loginTimeout = connection.getLoginTimeout();
final String bindAddress = connection.getBindAddress();
try {
// Create the Socket
Constructor socketConstructor =
Socket.class.getConstructor(new Class[] {});
Socket socket =
(Socket) socketConstructor.newInstance(new Object[] {});
// Create the InetSocketAddress
Constructor constructor = Class.forName("java.net.InetSocketAddress")
.getConstructor(new Class[] {String.class, int.class});
Object address = constructor.newInstance(
new Object[] {host, new Integer(port)});
// Call Socket.bind(SocketAddress) if bindAddress parameter is set
if (bindAddress != null && bindAddress.length() > 0) {
Object localBindAddress = constructor.newInstance(
new Object[]{bindAddress, new Integer(0)});
Method bind = Socket.class.getMethod(
"bind", new Class[]{Class.forName("java.net.SocketAddress")});
bind.invoke(socket, new Object[]{localBindAddress});
}
// Call Socket.connect(InetSocketAddress, int)
Method connect = Socket.class.getMethod("connect", new Class[]
{Class.forName("java.net.SocketAddress"), int.class});
connect.invoke(socket,
new Object[] {address, new Integer(loginTimeout * 1000)});
return socket;
} catch (InvocationTargetException ite) {
// Reflection was OK but invocation of socket.bind() or socket.connect()
// has failed. Try to report the underlying reason
Throwable cause = ite.getTargetException();
if (cause instanceof IOException) {
// OK was an IOException or subclass so just throw it
throw (IOException) cause;
}
// Something else so return invocation exception anyway
// (This should not normally occur)
throw (IOException) Support.linkException(
new IOException("Could not create socket"), cause);
} catch (Exception e) {
// Reflection has failed for some reason e.g. security so
// try to create a socket in the old way.
return new Socket(host, port);
}
}
/**
* Enable TLS encryption by creating a TLS socket over the
* existing TCP/IP network socket.
*
* @param ssl the SSL URL property value
* @throws IOException if an I/O error occurs
*/
void enableEncryption(String ssl) throws IOException {
Logger.println("Enabling TLS encryption");
SocketFactory sf = Driver.JDBC3 ?
SocketFactories.getSocketFactory(ssl, socket)
: SocketFactoriesSUN.getSocketFactory(ssl, socket);
sslSocket = sf.createSocket(getHost(), getPort());
setOut(new DataOutputStream(sslSocket.getOutputStream()));
setIn(new DataInputStream(sslSocket.getInputStream()));
}
/**
* Disable TLS encryption and switch back to raw TCP/IP socket.
*
* @throws IOException if an I/O error occurs
*/
void disableEncryption() throws IOException {
Logger.println("Disabling TLS encryption");
sslSocket.close();
sslSocket = null;
setOut(new DataOutputStream(socket.getOutputStream()));
setIn(new DataInputStream(socket.getInputStream()));
}
/**
* Set the character set descriptor to be used to translate byte arrays to
* or from Strings.
*
* @param charsetInfo the character set descriptor
*/
void setCharsetInfo(CharsetInfo charsetInfo) {
this.charsetInfo = charsetInfo;
}
/**
* Retrieve the character set descriptor used to translate byte arrays to
* or from Strings.
*/
CharsetInfo getCharsetInfo() {
return charsetInfo;
}
/**
* Retrieve the character set name used to translate byte arrays to
* or from Strings.
*
* @return the character set name as a String
*/
String getCharset() {
return charsetInfo.getCharset();
}
/**
* Obtain an instance of a server request stream for this socket.
*
* @param bufferSize the initial buffer size to be used by the
* RequestStream
* @param maxPrecision the maximum precision for numeric/decimal types
* @return the server request stream as a RequestStream
*/
RequestStream getRequestStream(int bufferSize, int maxPrecision) {
synchronized (socketTable) {
int id;
for (id = 0; id < socketTable.size(); id++) {
if (socketTable.get(id) == null) {
break;
}
}
VirtualSocket vsock = new VirtualSocket(id);
if (id >= socketTable.size()) {
socketTable.add(vsock);
} else {
socketTable.set(id, vsock);
}
return new RequestStream(this, id, bufferSize, maxPrecision);
}
}
/**
* Obtain an instance of a server response stream for this socket.
* NB. getRequestStream() must be used first to obtain the RequestStream
* needed as a parameter for this method.
*
* @param requestStream an existing server request stream object obtained
* from this SharedSocket
* @param bufferSize the initial buffer size to be used by the
* RequestStream
* @return the server response stream as a ResponseStream
*/
ResponseStream getResponseStream(RequestStream requestStream, int bufferSize) {
return new ResponseStream(this, requestStream.getStreamId(), bufferSize);
}
/**
* Retrieve the TDS version that is active on the connection
* supported by this socket.
*
* @return the TDS version as an int
*/
int getTdsVersion() {
return tdsVersion;
}
/**
* Set the TDS version field.
*
* @param tdsVersion the TDS version as an int
*/
protected void setTdsVersion(int tdsVersion) {
this.tdsVersion = tdsVersion;
}
/**
* Set the global buffer memory limit for all instances of this driver.
*
* @param memoryBudget the global memory budget
*/
static void setMemoryBudget(int memoryBudget) {
SharedSocket.memoryBudget = memoryBudget;
}
/**
* Get the global buffer memory limit for all instancs of this driver.
*
* @return the memory limit as an int
*/
static int getMemoryBudget() {
return SharedSocket.memoryBudget;
}
/**
* Set the minimum number of packets to cache in memory before
* writing to disk.
*
* @param minMemPkts the minimum number of packets to cache
*/
static void setMinMemPkts(int minMemPkts) {
SharedSocket.minMemPkts = minMemPkts;
}
/**
* Get the minimum number of memory cached packets.
*
* @return minimum memory packets as an int
*/
static int getMinMemPkts() {
return SharedSocket.minMemPkts;
}
/**
* Get the connected status of this socket.
*
* @return true if the underlying socket is connected
*/
boolean isConnected() {
return this.socket != null;
}
/**
* Send a TDS cancel packet to the server.
*
* @param streamId the RequestStream id
* @return boolean true if a cancel is actually
* issued by this method call.
*/
boolean cancel(int streamId) {
//
// Need to synchronize packet send to avoid race conditions on
// responsOwner and cancelPending
//
synchronized (cancelMonitor) {
//
// Only send if response pending for the caller.
// Caller must have aquired connection mutex first.
// NB. This method will not work with local named pipes
// as this thread will be blocked in the write until the
// reading thread has returned from the read.
//
if (responseOwner == streamId && !cancelPending) {
try {
//
// Send a cancel packet.
//
cancelPending = true;
byte[] cancel = new byte[TDS_HDR_LEN];
cancel[0] = TdsCore.CANCEL_PKT;
cancel[1] = 1;
cancel[2] = 0;
cancel[3] = 8;
cancel[4] = 0;
cancel[5] = 0;
cancel[6] = (tdsVersion >= Driver.TDS70) ? (byte) 1 : 0;
cancel[7] = 0;
getOut().write(cancel, 0, TDS_HDR_LEN);
getOut().flush();
if (Logger.isActive()) {
Logger.logPacket(streamId, false, cancel);
}
return true;
} catch (IOException e) {
// Ignore error as network is probably dead anyway
}
}
}
return false;
}
/**
* Close the socket and release all resources.
*
* @throws IOException if the socket close fails
*/
void close() throws IOException {
if (Logger.isActive()) {
Logger.println("TdsSocket: Max buffer memory used = " + (peakMemUsage / 1024) + "KB");
}
synchronized (socketTable) {
// See if any temporary files need deleting
for (int i = 0; i < socketTable.size(); i++) {
VirtualSocket vsock = (VirtualSocket) socketTable.get(i);
if (vsock != null && vsock.diskQueue != null) {
try {
vsock.diskQueue.close();
vsock.queueFile.delete();
} catch (IOException ioe) {
// Ignore errors
}
}
}
try {
if (sslSocket != null) {
sslSocket.close();
sslSocket = null;
}
} finally {
// Close physical socket
if (socket != null) {
socket.close();
}
}
}
}
/**
* Force close the socket causing any pending reads/writes to fail.
*
* Used by the login timer to abort a login attempt.
*/
void forceClose() {
if (socket != null) {
try {
socket.close();
} catch (IOException ioe) {
// Ignore
} finally {
sslSocket = null;
socket = null;
}
}
}
/**
* Deallocate a stream linked to this socket.
*
* @param streamId the ResponseStream id
*/
void closeStream(int streamId) {
synchronized (socketTable) {
VirtualSocket vsock = lookup(streamId);
if (vsock.diskQueue != null) {
try {
vsock.diskQueue.close();
vsock.queueFile.delete();
} catch (IOException ioe) {
// Ignore errors
}
}
socketTable.set(streamId, null);
}
}
/**
* Send a network packet. If output for another virtual socket is
* in progress this packet will be sent later.
*
* @param streamId the originating RequestStream object
* @param buffer the data to send
* @return the same buffer received if emptied or another buffer w/ the
* same size if the incoming buffer is cached (to avoid copying)
* @throws IOException if an I/O error occurs
*/
byte[] sendNetPacket(int streamId, byte buffer[])
throws IOException {
synchronized (socketTable) {
VirtualSocket vsock = lookup(streamId);
while (vsock.inputPkts > 0) {
//
// There is unread data in the input buffers.
// As we are sending another packet we can just discard it now.
//
if (Logger.isActive()) {
Logger.println("TdsSocket: Unread data in input packet queue");
}
dequeueInput(vsock);
}
if (responseOwner != -1) {
//
// Complex case there is another stream's data in the network pipe
// or we had our own incomplete request to discard first
// Read and store other stream's data or flush our own.
//
VirtualSocket other = (VirtualSocket)socketTable.get(responseOwner);
byte[] tmpBuf = null;
boolean ourData = (other.owner == streamId);
do {
// Reuse the buffer if it's our data; we don't need it
tmpBuf = readPacket(ourData ? tmpBuf : null);
if (!ourData) {
// We need to save this input as it belongs to
// Another thread.
enqueueInput(other, tmpBuf);
} // Any of our input is discarded.
} while (tmpBuf[1] == 0); // Read all data to complete TDS packet
}
//
// At this point we know that we are able to send the first
// or subsequent packet of a new request.
//
getOut().write(buffer, 0, getPktLen(buffer));
if (buffer[1] != 0) {
getOut().flush();
// We are the response owner now
responseOwner = streamId;
}
return buffer;
}
}
/**
* Get a network packet. This may be read from the network directly or from
* previously cached buffers.
*
* @param streamId the originating ResponseStream object
* @param buffer the data buffer to receive the object (may be replaced)
* @return the data in a byte[] buffer
* @throws IOException if an I/O error occurs
*/
byte[] getNetPacket(int streamId, byte buffer[]) throws IOException {
synchronized (socketTable) {
VirtualSocket vsock = lookup(streamId);
//
// Return any cached input
//
if (vsock.inputPkts > 0) {
return dequeueInput(vsock);
}
//
// Nothing cached see if we are expecting network data
//
if (responseOwner == -1) {
throw new IOException("Stream " + streamId +
" attempting to read when no request has been sent");
}
//
// OK There should be data, check that it is for this stream
//
if (responseOwner != streamId) {
// Error we are trying to read another thread's request.
throw new IOException("Stream " + streamId +
" is trying to read data that belongs to stream " +
responseOwner);
}
//
// Simple case we are reading our input directly from the server
//
return readPacket(buffer);
}
}
/**
* Save a packet buffer in a memory queue or to a disk queue if the global
* memory limit for the driver has been exceeded.
*
* @param vsock the virtual socket owning this data
* @param buffer the data to queue
*/
private void enqueueInput(VirtualSocket vsock, byte[] buffer)
throws IOException {
//
// Check to see if we should start caching to disk
//
if (globalMemUsage + buffer.length > memoryBudget &&
vsock.pktQueue.size() >= minMemPkts &&
!securityViolation &&
vsock.diskQueue == null) {
// Try to create a disk file for the queue
try {
vsock.queueFile = File.createTempFile("jtds", ".tmp", bufferDir);
// vsock.queueFile.deleteOnExit(); memory leak, see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6664633
vsock.diskQueue = new RandomAccessFile(vsock.queueFile, "rw");
// Write current cache contents to disk and free memory
byte[] tmpBuf;
while (vsock.pktQueue.size() > 0) {
tmpBuf = (byte[]) vsock.pktQueue.removeFirst();
vsock.diskQueue.write(tmpBuf, 0, getPktLen(tmpBuf));
vsock.pktsOnDisk++;
}
} catch (java.lang.SecurityException se) {
// Not allowed to cache to disk so carry on in memory
securityViolation = true;
vsock.queueFile = null;
vsock.diskQueue = null;
}
}
if (vsock.diskQueue != null) {
// Cache file exists so append buffer to it
vsock.diskQueue.write(buffer, 0, getPktLen(buffer));
vsock.pktsOnDisk++;
} else {
// Will cache in memory
vsock.pktQueue.addLast(buffer);
globalMemUsage += buffer.length;
if (globalMemUsage > peakMemUsage) {
peakMemUsage = globalMemUsage;
}
}
vsock.inputPkts++;
}
/**
* Read a cached packet from the in memory queue or from a disk based queue.
*
* @param vsock the virtual socket owning this data
* @return a buffer containing the packet
*/
private byte[] dequeueInput(VirtualSocket vsock)
throws IOException {
byte[] buffer = null;
if (vsock.pktsOnDisk > 0) {
// Data is cached on disk
if (vsock.diskQueue.getFilePointer() == vsock.diskQueue.length()) {
// First read so rewind() file
vsock.diskQueue.seek(0L);
}
vsock.diskQueue.readFully(hdrBuf, 0, TDS_HDR_LEN);
int len = getPktLen(hdrBuf);
buffer = new byte[len];
System.arraycopy(hdrBuf, 0, buffer, 0, TDS_HDR_LEN);
vsock.diskQueue.readFully(buffer, TDS_HDR_LEN, len - TDS_HDR_LEN);
vsock.pktsOnDisk--;
if (vsock.pktsOnDisk < 1) {
// File now empty so close and delete it
try {
vsock.diskQueue.close();
vsock.queueFile.delete();
} finally {
vsock.queueFile = null;
vsock.diskQueue = null;
}
}
} else if (vsock.pktQueue.size() > 0) {
buffer = (byte[]) vsock.pktQueue.removeFirst();
globalMemUsage -= buffer.length;
}
if (buffer != null) {
vsock.inputPkts--;
}
return buffer;
}
/**
* Read a physical TDS packet from the network.
*
* @param buffer a buffer to read the data into (if it fits) or null
* @return either the incoming buffer if it was large enough or a newly
* allocated buffer with the read packet
*/
private byte[] readPacket(byte buffer[])
throws IOException {
//
// Read rest of header
try {
getIn().readFully(hdrBuf);
} catch (EOFException e) {
throw new IOException("DB server closed connection.");
}
byte packetType = hdrBuf[0];
if (packetType != TdsCore.LOGIN_PKT
&& packetType != TdsCore.QUERY_PKT
&& packetType != TdsCore.SYBQUERY_PKT // required to connect IBM/Netcool Omnibus, see patch [1844846]
&& packetType != TdsCore.REPLY_PKT) {
throw new IOException("Unknown packet type 0x" +
Integer.toHexString(packetType & 0xFF));
}
// figure out how many bytes are remaining in this packet.
int len = getPktLen(hdrBuf);
if (len < TDS_HDR_LEN || len > 65536) {
throw new IOException("Invalid network packet length " + len);
}
if (buffer == null || len > buffer.length) {
// Create or expand the buffer as required
buffer = new byte[len];
if (len > maxBufSize) {
maxBufSize = len;
}
}
// Preserve the packet header in the buffer
System.arraycopy(hdrBuf, 0, buffer, 0, TDS_HDR_LEN);
try {
getIn().readFully(buffer, TDS_HDR_LEN, len - TDS_HDR_LEN);
} catch (EOFException e) {
throw new IOException("DB server closed connection.");
}
//
// SQL Server 2000 < SP3 does not set the last packet
// flag in the NT challenge packet.
// If this is the first packet and the length is correct
// force the last packet flag on.
//
if (++packetCount == 1 && serverType == Driver.SQLSERVER
&& "NTLMSSP".equals(new String(buffer, 11, 7))) {
buffer[1] = 1;
}
synchronized (cancelMonitor) {
//
// If a cancel request is outstanding check that the last TDS packet
// is a TDS_DONE with the "cancek ACK" flag set. If it isn't set the
// "more packets" flag; this will ensure that the stream keeps
// processing until the "cancel ACK" is processed.
//
if (cancelPending) {
//
// Move what we assume to be the TDS_DONE packet into doneBuffer
//
if (len >= TDS_DONE_LEN + TDS_HDR_LEN) {
System.arraycopy(buffer, len - TDS_DONE_LEN, doneBuffer, 0,
TDS_DONE_LEN);
} else {
// Packet too short so TDS_DONE record was split over
// two packets. Need to reassemble.
int frag = len - TDS_HDR_LEN;
System.arraycopy(doneBuffer, frag, doneBuffer, 0,
TDS_DONE_LEN - frag);
System.arraycopy(buffer, TDS_HDR_LEN, doneBuffer,
TDS_DONE_LEN - frag, frag);
}
//
// If this is the last packet and there is a cancel pending see
// if the last packet contains a TDS_DONE token with the cancel
// ACK set. If not reset the last packet flag so that the dedicated
// cancel packet is also read and processed.
//
if (buffer[1] == 1) {
if ((doneBuffer[0] & 0xFF) < TDS_DONE_TOKEN) {
throw new IOException("Expecting a TDS_DONE or TDS_DONEPROC.");
}
if ((doneBuffer[1] & TdsCore.DONE_CANCEL) != 0) {
// OK have a cancel ACK packet
cancelPending = false;
} else {
// Must be in next packet so
// force client to read next packet
buffer[1] = 0;
}
}
}
if (buffer[1] != 0) {
// End of response; connection now free
responseOwner = -1;
}
}
return buffer;
}
/**
* Retrieves the virtual socket with the given id.
*
* @param streamId id of the virtual socket to retrieve
*/
private VirtualSocket lookup(int streamId) {
if (streamId < 0 || streamId > socketTable.size()) {
throw new IllegalArgumentException("Invalid parameter stream ID "
+ streamId);
}
VirtualSocket vsock = (VirtualSocket)socketTable.get(streamId);
if (vsock.owner != streamId) {
throw new IllegalStateException("Internal error: bad stream ID "
+ streamId);
}
return vsock;
}
/**
* Convert two bytes (in network byte order) in a byte array into a Java
* short integer.
*
* @param buf array of data
* @return the 16 bit unsigned value as an int
*/
static int getPktLen(byte buf[]) {
int lo = ((int) buf[3] & 0xff);
int hi = (((int) buf[2] & 0xff) << 8);
return hi | lo;
}
/**
* Set the socket timeout.
*
* @param timeout the timeout value in milliseconds
*/
protected void setTimeout(int timeout) throws SocketException {
socket.setSoTimeout(timeout);
}
/**
* Set the socket keep alive.
*
* @param keepAlive true to turn on socket keep alive
*/
protected void setKeepAlive(boolean keepAlive) throws SocketException {
socket.setKeepAlive(keepAlive);
}
/**
* Getter for {@link SharedSocket#in} field.
*
* @return {@link InputStream} used for communication
*/
protected DataInputStream getIn() {
return in;
}
/**
* Setter for {@link SharedSocket#in} field.
*
* @param in the {@link InputStream} to be used for communication
*/
protected void setIn(DataInputStream in) {
this.in = in;
}
/**
* Getter for {@link SharedSocket#out} field.
*
* @return {@link OutputStream} used for communication
*/
protected DataOutputStream getOut() {
return out;
}
/**
* Setter for {@link SharedSocket#out} field.
*
* @param out the {@link OutputStream} to be used for communication
*/
protected void setOut(DataOutputStream out) {
this.out = out;
}
/**
* Get the server host name.
*
* @return the host name as a String
*/
protected String getHost() {
return this.host;
}
/**
* Get the server port number.
*
* @return the host port as an int
*/
protected int getPort() {
return this.port;
}
/**
* Finalize this object by releasing its resources.
*/
protected void finalize() throws Throwable {
close();
super.finalize();
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/ConnectionJDBC3.java 0000644 0001750 0001750 00000022313 11316672660 026551 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.util.*;
import java.sql.*;
/**
* Implements JDBC 3.0 specific functionality. Separated from {@link
* ConnectionJDBC2} in order to allow the same classes to run under both J2SE 1.3
* (ConnectionJDBC2)and 1.4 (ConnectionJDBC3).
*
* @author Alin Sinpalean
* @author Brian Heineman
* @author Mike Hutchinson
* @created March 30, 2004
* @version $Id: ConnectionJDBC3.java,v 1.15.2.2 2009/07/26 17:15:05 ickzon Exp $
*/
public class ConnectionJDBC3 extends ConnectionJDBC2 {
/** The list of savepoints. */
private ArrayList savepoints;
/** Maps each savepoint to a list of tmep procedures created since the savepoint */
private Map savepointProcInTran;
/** Counter for generating unique savepoint identifiers */
private int savepointId;
/**
* Create a new database connection.
*
* @param url The connection URL starting jdbc:jtds:.
* @param props The additional connection properties.
* @throws SQLException
*/
ConnectionJDBC3(String url, Properties props) throws SQLException {
super(url, props);
}
/**
* Add a savepoint to the list maintained by this connection.
*
* @param savepoint The savepoint object to add.
* @throws SQLException
*/
private void setSavepoint(SavepointImpl savepoint) throws SQLException {
Statement statement = null;
try {
statement = createStatement();
statement.execute("IF @@TRANCOUNT=0 BEGIN "
+ "SET IMPLICIT_TRANSACTIONS OFF; " + "BEGIN TRAN; " // Fix for bug []Patch: in SET IMPLICIT_TRANSACTIONS ON
+ "SET IMPLICIT_TRANSACTIONS ON; " + "END " // mode BEGIN TRAN actually starts two transactions!
+ "SAVE TRAN jtds" + savepoint.getId());
} finally {
if (statement != null) {
statement.close();
}
}
synchronized (this) {
if (savepoints == null) {
savepoints = new ArrayList();
}
savepoints.add(savepoint);
}
}
/**
* Releases all savepoints. Used internally when committing or rolling back
* a transaction.
*/
synchronized void clearSavepoints() {
if (savepoints != null) {
savepoints.clear();
}
if (savepointProcInTran != null) {
savepointProcInTran.clear();
}
savepointId = 0;
}
// ------------- Methods implementing java.sql.Connection -----------------
public synchronized void releaseSavepoint(Savepoint savepoint)
throws SQLException {
checkOpen();
if (savepoints == null) {
throw new SQLException(
Messages.get("error.connection.badsavep"), "25000");
}
int index = savepoints.indexOf(savepoint);
if (index == -1) {
throw new SQLException(
Messages.get("error.connection.badsavep"), "25000");
}
Object tmpSavepoint = savepoints.remove(index);
if (savepointProcInTran != null) {
if (index != 0) {
// If this wasn't the outermost savepoint, move all procedures
// to the "wrapping" savepoint's list; when and if that
// savepoint will be rolled back it will clear these procedures
// too
List keys = (List) savepointProcInTran.get(savepoint);
if (keys != null) {
Savepoint wrapping = (Savepoint) savepoints.get(index - 1);
List wrappingKeys =
(List) savepointProcInTran.get(wrapping);
if (wrappingKeys == null) {
wrappingKeys = new ArrayList();
}
wrappingKeys.addAll(keys);
savepointProcInTran.put(wrapping, wrappingKeys);
}
}
// If this was the outermost savepoint, just drop references to
// all procedures; they will be managed by the connection
savepointProcInTran.remove(tmpSavepoint);
}
}
public synchronized void rollback(Savepoint savepoint) throws SQLException {
checkOpen();
checkLocal("rollback");
if (savepoints == null) {
throw new SQLException(
Messages.get("error.connection.badsavep"), "25000");
}
int index = savepoints.indexOf(savepoint);
if (index == -1) {
throw new SQLException(
Messages.get("error.connection.badsavep"), "25000");
} else if (getAutoCommit()) {
throw new SQLException(
Messages.get("error.connection.savenorollback"), "25000");
}
Statement statement = null;
try {
statement = createStatement();
statement.execute("ROLLBACK TRAN jtds" + ((SavepointImpl) savepoint).getId());
} finally {
if (statement != null) {
statement.close();
}
}
int size = savepoints.size();
for (int i = size - 1; i >= index; i--) {
Object tmpSavepoint = savepoints.remove(i);
if (savepointProcInTran == null) {
continue;
}
List keys = (List) savepointProcInTran.get(tmpSavepoint);
if (keys == null) {
continue;
}
for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
removeCachedProcedure(key);
}
}
// recreate savepoint
setSavepoint((SavepointImpl) savepoint);
}
synchronized public Savepoint setSavepoint() throws SQLException {
checkOpen();
checkLocal("setSavepoint");
if (getAutoCommit()) {
throw new SQLException(
Messages.get("error.connection.savenoset"), "25000");
}
SavepointImpl savepoint = new SavepointImpl(getNextSavepointId());
setSavepoint(savepoint);
return savepoint;
}
synchronized public Savepoint setSavepoint(String name) throws SQLException {
checkOpen();
checkLocal("setSavepoint");
if (getAutoCommit()) {
throw new SQLException(
Messages.get("error.connection.savenoset"), "25000");
} else if (name == null) {
throw new SQLException(
Messages.get("error.connection.savenullname", "savepoint"),
"25000");
}
SavepointImpl savepoint = new SavepointImpl(getNextSavepointId(), name);
setSavepoint(savepoint);
return savepoint;
}
/**
* Returns the next savepoint identifier.
*
* @return the next savepoint identifier
*/
private int getNextSavepointId() {
return ++savepointId;
}
/**
* Add a stored procedure to the cache.
*
* @param key The signature of the procedure to cache.
* @param proc The stored procedure descriptor.
*/
void addCachedProcedure(String key, ProcEntry proc) {
super.addCachedProcedure(key, proc);
if (getServerType() == Driver.SQLSERVER
&& proc.getType() == ProcEntry.PROCEDURE) {
// Only need to track SQL Server temp stored procs
addCachedProcedure(key);
}
}
/**
* Add a stored procedure to the savepoint cache.
*
* @param key The signature of the procedure to cache.
*/
synchronized void addCachedProcedure(String key) {
if (savepoints == null || savepoints.size() == 0) {
return;
}
if (savepointProcInTran == null) {
savepointProcInTran = new HashMap();
}
// Retrieve the current savepoint
Object savepoint = savepoints.get(savepoints.size() - 1);
List keys = (List) savepointProcInTran.get(savepoint);
if (keys == null) {
keys = new ArrayList();
}
keys.add(key);
savepointProcInTran.put(savepoint, keys);
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/JtdsDatabaseMetaData.java 0000644 0001750 0001750 00000422131 11316672660 027700 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* jTDS implementation of the java.sql.DatabaseMetaData interface.
*
* Implementation note: *
* This is basically the code from the original jTDS driver. * Main changes relate to the need to support the new ResultSet * implementation. *
* TODO: Many of the system limits need to be revised to more accurately
* reflect the target database constraints. In many cases limits are soft
* and determined by bytes per column for example. Probably more of these
* functions should be altered to return 0 but for now the original jTDS
* values are returned.
*
* @author Craig Spannring
* @author The FreeTDS project
* @author Alin Sinpalean
* created 17 March 2001
* @version $Id: JtdsDatabaseMetaData.java,v 1.37.2.4 2009/12/30 08:45:34 ickzon Exp $
*/
public class JtdsDatabaseMetaData implements java.sql.DatabaseMetaData {
static final int sqlStateXOpen = 1;
// Internal data needed by this implemention.
private final int tdsVersion;
private final int serverType;
private final ConnectionJDBC2 connection;
/**
* Length of a sysname object (table name, catalog name etc.) -- 128 for
* TDS 7.0, 30 for earlier versions.
*/
int sysnameLength = 30;
/**
* Boolean.TRUE if identifiers are case sensitive (the server
* was installed that way). Initially null, set the first time
* any of the methods that check this are called.
*/
Boolean caseSensitive;
public JtdsDatabaseMetaData(ConnectionJDBC2 connection) {
this.connection = connection;
tdsVersion = connection.getTdsVersion();
serverType = connection.getServerType();
if (tdsVersion >= Driver.TDS70) {
sysnameLength = 128;
}
}
//----------------------------------------------------------------------
// First, a variety of minor information about the target database.
/**
* Can all the procedures returned by getProcedures be called by the
* current user?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean allProceduresAreCallable() throws SQLException {
// Sybase - if accessible_sproc = Y in server info (normal case) return true
return true; // per "Programming ODBC for SQLServer" Appendix A
}
/**
* Can all the tables returned by getTable be SELECTed by the
* current user?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean allTablesAreSelectable() throws SQLException {
// Sybase sp_tables may return tables that you are not able to access.
return connection.getServerType() == Driver.SQLSERVER;
}
/**
* Does a data definition statement within a transaction force the
* transaction to commit?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean dataDefinitionCausesTransactionCommit() throws SQLException {
return false;
}
/**
* Is a data definition statement within a transaction ignored?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean dataDefinitionIgnoredInTransactions() throws SQLException {
return false;
}
/**
* Did getMaxRowSize() include LONGVARCHAR and LONGVARBINARY blobs?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean doesMaxRowSizeIncludeBlobs() throws SQLException {
return false;
}
/**
* Get a description of a table's optimal set of columns that
* uniquely identifies a row. They are ordered by SCOPE.
*
*
Each column description has the following columns: *
null means drop catalog name from the selection criteria
* @param schema a schema name; "" retrieves those without a schema
* @param table a table name
* @param scope the scope of interest; use same values as SCOPE
* @param nullable include columns that are nullable?
* @return ResultSet - each row is a column description
* @throws SQLException if a database-access error occurs.
*/
public java.sql.ResultSet getBestRowIdentifier(String catalog,
String schema,
String table,
int scope,
boolean nullable)
throws SQLException {
String colNames[] = {"SCOPE", "COLUMN_NAME",
"DATA_TYPE", "TYPE_NAME",
"COLUMN_SIZE", "BUFFER_LENGTH",
"DECIMAL_DIGITS", "PSEUDO_COLUMN"};
int colTypes[] = {Types.SMALLINT, Types.VARCHAR,
Types.INTEGER, Types.VARCHAR,
Types.INTEGER, Types.INTEGER,
Types.SMALLINT, Types.SMALLINT};
String query = "sp_special_columns ?, ?, ?, ?, ?, ?, ?";
CallableStatement s = connection.prepareCall(syscall(catalog, query));
s.setString(1, table);
s.setString(2, schema);
s.setString(3, catalog);
s.setString(4, "R");
s.setString(5, "T");
s.setString(6, "U");
s.setInt(7, 3); // ODBC version 3
JtdsResultSet rs = (JtdsResultSet)s.executeQuery();
CachedResultSet rsTmp = new CachedResultSet((JtdsStatement)s, colNames, colTypes);
rsTmp.moveToInsertRow();
int colCnt = rs.getMetaData().getColumnCount();
while (rs.next()) {
for (int i = 1; i <= colCnt; i++) {
if (i == 3) {
int type = TypeInfo.normalizeDataType(rs.getInt(i), connection.getUseLOBs());
rsTmp.updateInt(i, type);
} else {
rsTmp.updateObject(i, rs.getObject(i));
}
}
rsTmp.insertRow();
}
rs.close();
// Do not close the statement, rsTmp is also built from it
rsTmp.moveToCurrentRow();
rsTmp.setConcurrency(ResultSet.CONCUR_READ_ONLY);
return rsTmp;
}
/**
* Get the catalog names available in this database. The results are
* ordered by catalog name. * * The catalog column is: *
* * Only privileges matching the column name criteria are returned. They are * ordered by COLUMN_NAME and PRIVILEGE.
* * Each privilige description has the following columns: *
null means drop catalog name from the selection criteria
* @param schema a schema name; "" retrieves those without a schema
* schema
* @param table a table name
* @param columnNamePattern a column name pattern
* @return ResultSet - each row is a column privilege description
* @throws SQLException if a database-access error occurs.
*
* @see #getSearchStringEscape
*/
public java.sql.ResultSet getColumnPrivileges(String catalog,
String schema,
String table,
String columnNamePattern)
throws SQLException {
String query = "sp_column_privileges ?, ?, ?, ?";
CallableStatement s = connection.prepareCall(syscall(catalog, query));
s.setString(1, table);
s.setString(2, schema);
s.setString(3, catalog);
s.setString(4, processEscapes(columnNamePattern));
JtdsResultSet rs = (JtdsResultSet)s.executeQuery();
rs.setColLabel(1, "TABLE_CAT");
rs.setColLabel(2, "TABLE_SCHEM");
upperCaseColumnNames(rs);
return rs;
}
/**
* Get a description of table columns available in a catalog. * * Only column descriptions matching the catalog, schema, table and column * name criteria are returned. They are ordered by TABLE_SCHEM, TABLE_NAME * and ORDINAL_POSITION.
* * Each column description has the following columns: *
null means drop catalog name from the selection criteria
* @param schemaPattern a schema name pattern; "" retrieves those without a schema
* @param tableNamePattern a table name pattern
* @param columnNamePattern a column name pattern
* @return ResultSet - each row is a column description
* @throws SQLException if a database-access error occurs.
*
* @see #getSearchStringEscape
*/
public java.sql.ResultSet getColumns(String catalog,
String schemaPattern,
String tableNamePattern,
String columnNamePattern)
throws SQLException {
String colNames[] = {"TABLE_CAT", "TABLE_SCHEM",
"TABLE_NAME", "COLUMN_NAME",
"DATA_TYPE", "TYPE_NAME",
"COLUMN_SIZE", "BUFFER_LENGTH",
"DECIMAL_DIGITS", "NUM_PREC_RADIX",
"NULLABLE", "REMARKS",
"COLUMN_DEF", "SQL_DATA_TYPE",
"SQL_DATETIME_SUB", "CHAR_OCTET_LENGTH",
"ORDINAL_POSITION", "IS_NULLABLE",
"SCOPE_CATALOG", "SCOPE_SCHEMA",
"SCOPE_TABLE", "SOURCE_DATA_TYPE"};
int colTypes[] = {Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR,
Types.INTEGER, Types.VARCHAR,
Types.INTEGER, Types.INTEGER,
Types.INTEGER, Types.INTEGER,
Types.INTEGER, Types.VARCHAR,
Types.VARCHAR, Types.INTEGER,
Types.INTEGER, Types.INTEGER,
Types.INTEGER, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.SMALLINT};
String query = "sp_columns ?, ?, ?, ?, ?";
CallableStatement s = connection.prepareCall(syscall(catalog, query));
s.setString(1, processEscapes(tableNamePattern));
s.setString(2, processEscapes(schemaPattern));
s.setString(3, catalog);
s.setString(4, processEscapes(columnNamePattern));
s.setInt(5, 3); // ODBC version 3
JtdsResultSet rs = (JtdsResultSet)s.executeQuery();
CachedResultSet rsTmp = new CachedResultSet((JtdsStatement)s, colNames, colTypes);
rsTmp.moveToInsertRow();
int colCnt = rs.getMetaData().getColumnCount();
//
// Neither type of server returns exactly the data required by the JDBC3 standard.
// The result data is copied to a cached result set and modified on the fly.
//
while (rs.next()) {
if (serverType == Driver.SYBASE) {
// Sybase servers (older versions only return 14 columns)
for (int i = 1; i <= 4; i++) {
rsTmp.updateObject(i, rs.getObject(i));
}
rsTmp.updateInt(5, TypeInfo.normalizeDataType(rs.getInt(5), connection.getUseLOBs()));
String typeName = rs.getString(6);
rsTmp.updateString(6, typeName);
for (int i = 8; i <= 12; i++) {
rsTmp.updateObject(i, rs.getObject(i));
}
if (colCnt >= 20) {
// SYBASE 11.92, 12.5
for (int i = 13; i <= 18; i++) {
rsTmp.updateObject(i, rs.getObject(i + 2));
}
} else {
// SYBASE 11.03
rsTmp.updateObject(16, rs.getObject(8));
rsTmp.updateObject(17, rs.getObject(14));
}
if ("image".equals(typeName) || "text".equals(typeName)) {
rsTmp.updateInt(7, Integer.MAX_VALUE);
rsTmp.updateInt(16, Integer.MAX_VALUE);
} else
if ("univarchar".equals(typeName) || "unichar".equals(typeName)) {
rsTmp.updateInt(7, rs.getInt(7) / 2);
rsTmp.updateObject(16, rs.getObject(7));
} else {
rsTmp.updateInt(7, rs.getInt(7));
}
} else {
// MS SQL Server - Mainly OK but we need to fix some data types.
for (int i = 1; i <= colCnt; i++) {
if (i == 5) {
int type = TypeInfo.normalizeDataType(rs.getInt(i), connection.getUseLOBs());
rsTmp.updateInt(i, type);
} else
if (i == 19) {
// This is the SS_DATA_TYPE column and contains the TDS
// data type constant. We can use this to distinguish
// varchar(max) from text on SQL2005.
rsTmp.updateString(6, TdsData.getMSTypeName(rs.getString(6), rs.getInt(19)));
} else {
rsTmp.updateObject(i, rs.getObject(i));
}
}
}
rsTmp.insertRow();
}
rs.close();
rsTmp.moveToCurrentRow();
rsTmp.setConcurrency(ResultSet.CONCUR_READ_ONLY);
return rsTmp;
}
/**
* Get a description of the foreign key columns in the foreign key table
* that reference the primary key columns of the primary key table
* (describe how one table imports another's key). This should normally
* return a single foreign key/primary key pair (most tables only import a
* foreign key from a table once.) They are ordered by FKTABLE_CAT,
* FKTABLE_SCHEM, FKTABLE_NAME, and KEY_SEQ. * * Each foreign key column description has the following columns: *
null means drop catalog name from the selection criteria
* @param primarySchema a schema name pattern; "" retrieves those without a schema
* @param primaryTable the table name that exports the key
* @param foreignCatalog a catalog name; "" retrieves those without a
* null means drop catalog name from the selection criteria
* @param foreignSchema a schema name pattern; "" retrieves those without a schema
* @param foreignTable the table name that imports the key
* @return ResultSet - each row is a foreign key column description
* @throws SQLException if a database-access error occurs.
*
* @see #getImportedKeys
*/
public java.sql.ResultSet getCrossReference(String primaryCatalog,
String primarySchema,
String primaryTable,
String foreignCatalog,
String foreignSchema,
String foreignTable)
throws SQLException {
String colNames[] = {"PKTABLE_CAT", "PKTABLE_SCHEM",
"PKTABLE_NAME", "PKCOLUMN_NAME",
"FKTABLE_CAT", "FKTABLE_SCHEM",
"FKTABLE_NAME", "FKCOLUMN_NAME",
"KEY_SEQ", "UPDATE_RULE",
"DELETE_RULE", "FK_NAME",
"PK_NAME", "DEFERRABILITY"};
int colTypes[] = {Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR,
Types.SMALLINT, Types.SMALLINT,
Types.SMALLINT, Types.VARCHAR,
Types.VARCHAR, Types.SMALLINT};
String query = "sp_fkeys ?, ?, ?, ?, ?, ?";
if (primaryCatalog != null) {
query = syscall(primaryCatalog, query);
} else if (foreignCatalog != null) {
query = syscall(foreignCatalog, query);
} else {
query = syscall(null, query);
}
CallableStatement s = connection.prepareCall(query);
s.setString(1, primaryTable);
s.setString(2, processEscapes(primarySchema));
s.setString(3, primaryCatalog);
s.setString(4, foreignTable);
s.setString(5, processEscapes(foreignSchema));
s.setString(6, foreignCatalog);
JtdsResultSet rs = (JtdsResultSet)s.executeQuery();
int colCnt = rs.getMetaData().getColumnCount();
CachedResultSet rsTmp = new CachedResultSet((JtdsStatement)s, colNames, colTypes);
rsTmp.moveToInsertRow();
while (rs.next()) {
for (int i = 1; i <= colCnt; i++) {
rsTmp.updateObject(i, rs.getObject(i));
}
if (colCnt < 14) {
rsTmp.updateShort(14, (short)DatabaseMetaData.importedKeyNotDeferrable);
}
rsTmp.insertRow();
}
rs.close();
rsTmp.moveToCurrentRow();
rsTmp.setConcurrency(ResultSet.CONCUR_READ_ONLY);
return rsTmp;
}
/**
* Returns the name of this database product.
*
* @return database product name
* @throws SQLException if a database-access error occurs.
*/
public String getDatabaseProductName() throws SQLException {
return connection.getDatabaseProductName();
}
/**
* Returns the version of this database product.
*
* @return database version
* @throws SQLException if a database-access error occurs.
*/
public String getDatabaseProductVersion() throws SQLException {
return connection.getDatabaseProductVersion();
}
//----------------------------------------------------------------------
/**
* Returns the database's default transaction isolation level. The values
* are defined in java.sql.Connection.
*
* @return the default isolation level
* @throws SQLException if a database-access error occurs.
*
* @see Connection
*/
public int getDefaultTransactionIsolation() throws SQLException {
return Connection.TRANSACTION_READ_COMMITTED;
}
/**
* Returns this JDBC driver's major version number.
*
* @return JDBC driver major version
*/
public int getDriverMajorVersion() {
return Driver.MAJOR_VERSION;
}
/**
* Returns this JDBC driver's minor version number.
*
* @return JDBC driver minor version number
*/
public int getDriverMinorVersion() {
return Driver.MINOR_VERSION;
}
/**
* Returns the name of this JDBC driver.
*
* @return JDBC driver name
* @throws SQLException if a database-access error occurs.
*/
public String getDriverName() throws SQLException {
return "jTDS Type 4 JDBC Driver for MS SQL Server and Sybase";
}
/**
* Returns the version of this JDBC driver.
*
* @return JDBC driver version
* @throws SQLException if a database-access error occurs.
*/
public String getDriverVersion() throws SQLException {
return Driver.getVersion();
}
/**
* Get a description of the foreign key columns that reference a table's
* primary key columns (the foreign keys exported by a table). They are
* ordered by FKTABLE_CAT, FKTABLE_SCHEM, FKTABLE_NAME, and KEY_SEQ.
* * Each foreign key column description has the following columns: *
null means drop catalog name from the selection criteria
* @param schema a schema name; "" retrieves those without a schema
* @param table a table name
* @return ResultSet - each row is a foreign key column description
* @throws SQLException if a database-access error occurs.
*
* @see #getImportedKeys
*/
public java.sql.ResultSet getExportedKeys(String catalog,
String schema,
String table)
throws SQLException {
return getCrossReference(catalog, schema, table, null, null, null);
}
/**
* Get all the "extra" characters that can be used in unquoted identifier
* names (those beyond a-z, A-Z, 0-9 and _).
*
* @return the string containing the extra characters
* @throws SQLException if a database-access error occurs.
*/
public String getExtraNameCharacters() throws SQLException {
// MS driver returns "$#@" Sybase JConnect returns "@#$"
return "$#@";
}
/**
* Returns the string used to quote SQL identifiers. This returns a space "
* " if identifier quoting isn't supported. A JDBC-Compliant driver always
* uses a double quote character.
*
* @return the quoting string
* @throws SQLException if a database-access error occurs.
*/
public String getIdentifierQuoteString() throws SQLException {
return "\"";
}
/**
* Get a description of the primary key columns that are referenced by a
* table's foreign key columns (the primary keys imported by a table). They
* are ordered by PKTABLE_CAT, PKTABLE_SCHEM, PKTABLE_NAME, and KEY_SEQ.
* * Each primary key column description has the following columns: *
null means drop catalog name from the selection criteria
* @param schema a schema name; "" retrieves those without a schema
* @param table a table name
* @return ResultSet - each row is a primary key column description
* @throws SQLException if a database-access error occurs.
*
* @see #getExportedKeys
*/
public java.sql.ResultSet getImportedKeys(String catalog,
String schema,
String table)
throws SQLException {
return getCrossReference(null, null, null, catalog, schema, table);
}
/**
* Get a description of a table's indices and statistics. They are ordered
* by NON_UNIQUE, TYPE, INDEX_NAME, and ORDINAL_POSITION. * * Each index column description has the following columns: *
null means drop catalog name from the selection criteria
* @param schema a schema name; "" retrieves those without a schema
* @param table a table name
* @param unique when true, return only indices for unique
* values; when false, return indices regardless of
* whether unique or not
* @param approximate when true, result is allowed to reflect
* approximate or out of data values; when false, results
* are requested to be accurate
* @return ResultSet - each row is an index column description
* @throws SQLException if a database-access error occurs.
*/
public java.sql.ResultSet getIndexInfo(String catalog,
String schema,
String table,
boolean unique,
boolean approximate)
throws SQLException {
String colNames[] = {"TABLE_CAT", "TABLE_SCHEM",
"TABLE_NAME", "NON_UNIQUE",
"INDEX_QUALIFIER", "INDEX_NAME",
"TYPE", "ORDINAL_POSITION",
"COLUMN_NAME", "ASC_OR_DESC",
"CARDINALITY", "PAGES",
"FILTER_CONDITION"};
int colTypes[] = {Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.BIT,
Types.VARCHAR, Types.VARCHAR,
Types.SMALLINT, Types.SMALLINT,
Types.VARCHAR, Types.VARCHAR,
Types.INTEGER, Types.INTEGER,
Types.VARCHAR};
String query = "sp_statistics ?, ?, ?, ?, ?, ?";
CallableStatement s = connection.prepareCall(syscall(catalog, query));
s.setString(1, table);
s.setString(2, schema);
s.setString(3, catalog);
s.setString(4, "%");
s.setString(5, unique ? "Y" : "N");
s.setString(6, approximate ? "Q" : "E");
JtdsResultSet rs = (JtdsResultSet) s.executeQuery();
int colCnt = rs.getMetaData().getColumnCount();
CachedResultSet rsTmp = new CachedResultSet((JtdsStatement)s, colNames, colTypes);
rsTmp.moveToInsertRow();
while (rs.next()) {
for (int i = 1; i <= colCnt; i++) {
rsTmp.updateObject(i, rs.getObject(i));
}
rsTmp.insertRow();
}
rs.close();
rsTmp.moveToCurrentRow();
rsTmp.setConcurrency(ResultSet.CONCUR_READ_ONLY);
return rsTmp;
}
//----------------------------------------------------------------------
// The following group of methods exposes various limitations
// based on the target database with the current driver.
// Unless otherwise specified, a result of zero means there is no
// limit, or the limit is not known.
/**
* How many hex characters can you have in an inline binary literal?
*
* @return max literal length
* @throws SQLException if a database-access error occurs.
*/
public int getMaxBinaryLiteralLength() throws SQLException {
// Sybase jConnect says 255
// Actual value is 16384 for Sybase 12.5
// MS JDBC says 0
// Probable maximum size for MS is 65,536 * network packet size
return 131072;
// per "Programming ODBC for SQLServer" Appendix A
}
/**
* What's the maximum length of a catalog name?
*
* @return max name length in bytes
* @throws SQLException if a database-access error occurs.
*/
public int getMaxCatalogNameLength() throws SQLException {
return sysnameLength;
}
/**
* What's the max length for a character literal?
*
* @return max literal length
* @throws SQLException if a database-access error occurs.
*/
public int getMaxCharLiteralLength() throws SQLException {
// Sybase jConnect says 255
// Actual value is 16384 for Sybase 12.5
// MS JDBC says 0
// Probable maximum size for MS is 65,536 * network packet size
return 131072;
// per "Programming ODBC for SQLServer" Appendix A
}
/**
* What's the limit on column name length?
*
* @return max literal length
* @throws SQLException if a database-access error occurs.
*/
public int getMaxColumnNameLength() throws SQLException {
// per "Programming ODBC for SQLServer" Appendix A
return sysnameLength;
}
/**
* What's the maximum number of columns in a "GROUP BY" clause?
*
* @return max number of columns
* @throws SQLException if a database-access error occurs.
*/
public int getMaxColumnsInGroupBy() throws SQLException {
// Sybase jConnect says 16
// MS JDBC says 16
// per "Programming ODBC for SQLServer" Appendix A
// Actual MS value is 8060 / average bytes per column
return (tdsVersion >= Driver.TDS70) ? 0 : 16;
}
/**
* What's the maximum number of columns allowed in an index?
*
* @return max columns
* @throws SQLException if a database-access error occurs.
*/
public int getMaxColumnsInIndex() throws SQLException {
// per SQL Server Books Online "Administrator's Companion",
// Part 1, Chapter 1.
// Sybase 12.5 is 31
return 16;
}
/**
* What's the maximum number of columns in an "ORDER BY" clause?
*
* @return max columns
* @throws SQLException if a database-access error occurs.
*/
public int getMaxColumnsInOrderBy() throws SQLException {
// per "Programming ODBC for SQLServer" Appendix A
// Sybase 12.5 is 31
// Actual MS value is 8060 / average bytes per column
return (tdsVersion >= Driver.TDS70) ? 0 : 16;
}
/**
* What's the maximum number of columns in a "SELECT" list?
*
* @return max columns
* @throws SQLException if a database-access error occurs.
*/
public int getMaxColumnsInSelect() throws SQLException {
// Sybase jConnect says 0
// per "Programming ODBC for SQLServer" Appendix A
return 4096;
}
/**
* What's the maximum number of columns in a table?
*
* @return max columns
* @throws SQLException if a database-access error occurs.
*/
public int getMaxColumnsInTable() throws SQLException {
// Sybase jConnect says 250
// per "Programming ODBC for SQLServer" Appendix A
// MS 2000 should be 4096
// Sybase 12.5 is now 1024
return (tdsVersion >= Driver.TDS70) ? 1024 : 250;
}
/**
* How many active connections can we have at a time to this database?
*
* @return max connections
* @throws SQLException if a database-access error occurs.
*/
public int getMaxConnections() throws SQLException {
// Sybase - could query syscurconfigs to get actual value
// which in practice will be a lot less than 32767!
// per SQL Server Books Online "Administrator's Companion",
// Part 1, Chapter 1.
return 32767;
}
/**
* What's the maximum cursor name length?
*
* @return max cursor name length in bytes
* @throws SQLException if a database-access error occurs.
*/
public int getMaxCursorNameLength() throws SQLException {
// per "Programming ODBC for SQLServer" Appendix A
return sysnameLength;
}
/**
* What's the maximum length of an index (in bytes)?
*
* @return max index length in bytes
* @throws SQLException if a database-access error occurs.
*/
public int getMaxIndexLength() throws SQLException {
// Sybase JConnect says 255
// Actual Sybase 12.5 is 600 - 5300 depending on page size
// per "Programming ODBC for SQLServer" Appendix A
return (tdsVersion >= Driver.TDS70) ? 900 : 255;
}
/**
* What's the maximum length of a procedure name?
*
* @return max name length in bytes
* @throws SQLException if a database-access error occurs.
*/
public int getMaxProcedureNameLength() throws SQLException {
// per "Programming ODBC for SQLServer" Appendix A
return sysnameLength;
}
/**
* What's the maximum length of a single row?
*
* @return max row size in bytes
* @throws SQLException if a database-access error occurs.
*/
public int getMaxRowSize() throws SQLException {
// Sybase jConnect says 1962 but this can be more with wide tables.
// per SQL Server Books Online "Administrator's Companion",
// Part 1, Chapter 1.
return (tdsVersion >= Driver.TDS70) ? 8060 : 1962;
}
/**
* What's the maximum length allowed for a schema name?
*
* @return max name length in bytes
* @throws SQLException if a database-access error occurs.
*/
public int getMaxSchemaNameLength() throws SQLException {
return sysnameLength;
}
/**
* What's the maximum length of a SQL statement?
*
* @return max length in bytes
* @throws SQLException if a database-access error occurs.
*/
public int getMaxStatementLength() throws SQLException {
// I think this should return 0 (no limit)
// actual limit for SQL 7/2000 is 65536 * packet size!
// Sybase JConnect says 0
// MS JDBC says 0
// per "Programming ODBC for SQLServer" Appendix A
return 0;
}
/**
* How many active statements can we have open at one time to this
* database?
*
* @return the maximum
* @throws SQLException if a database-access error occurs.
*/
public int getMaxStatements() throws SQLException {
return 0;
}
/**
* What's the maximum length of a table name?
*
* @return max name length in bytes
* @throws SQLException if a database-access error occurs.
*/
public int getMaxTableNameLength() throws SQLException {
// per "Programming ODBC for SQLServer" Appendix A
return sysnameLength;
}
/**
* What's the maximum number of tables in a SELECT?
*
* @return the maximum
* @throws SQLException if a database-access error occurs.
*/
public int getMaxTablesInSelect() throws SQLException {
// Sybase JConnect says 256
// MS JDBC says 32!
// Actual Sybase 12.5 is 50
// per "Programming ODBC for SQLServer" Appendix A
return (tdsVersion > Driver.TDS50) ? 256 : 16;
}
/**
* What's the maximum length of a user name?
*
* @return max name length in bytes
* @throws SQLException if a database-access error occurs.
*/
public int getMaxUserNameLength() throws SQLException {
return sysnameLength;
}
/**
* Get a comma separated list of math functions.
*
* @return the list
* @throws SQLException if a database-access error occurs.
*/
public String getNumericFunctions() throws SQLException {
// I don't think either Sybase or SQL have a truncate maths function
// so I have removed it from the list.
// Also all other drivers return this list in lower case. Should we?
return "abs,acos,asin,atan,atan2,ceiling,cos,cot,degrees,exp,floor,log,"
+ "log10,mod,pi,power,radians,rand,round,sign,sin,sqrt,tan";
}
/**
* Get a description of a table's primary key columns. They are ordered by
* COLUMN_NAME. * * Each primary key column description has the following columns: *
null means drop catalog name from the selection criteria
* @param schema a schema name; "" retrieves those without a schema
* @param table a table name
* @return ResultSet - each row is a primary key column description
* @throws SQLException if a database-access error occurs.
*/
public java.sql.ResultSet getPrimaryKeys(String catalog,
String schema,
String table)
throws SQLException {
String colNames[] = {"TABLE_CAT", "TABLE_SCHEM",
"TABLE_NAME", "COLUMN_NAME",
"KEY_SEQ", "PK_NAME"};
int colTypes[] = {Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR,
Types.SMALLINT, Types.VARCHAR};
String query = "sp_pkeys ?, ?, ?";
CallableStatement s = connection.prepareCall(syscall(catalog, query));
s.setString(1, table);
s.setString(2, schema);
s.setString(3, catalog);
JtdsResultSet rs = (JtdsResultSet)s.executeQuery();
CachedResultSet rsTmp = new CachedResultSet((JtdsStatement)s, colNames, colTypes);
rsTmp.moveToInsertRow();
int colCnt = rs.getMetaData().getColumnCount();
while (rs.next()) {
for (int i = 1; i <= colCnt; i++) {
rsTmp.updateObject(i, rs.getObject(i));
}
rsTmp.insertRow();
}
rs.close();
rsTmp.moveToCurrentRow();
rsTmp.setConcurrency(ResultSet.CONCUR_READ_ONLY);
return rsTmp;
}
/**
* Get a description of a catalog's stored procedure parameters and result
* columns. * * Only descriptions matching the schema, procedure and parameter name * criteria are returned. They are ordered by PROCEDURE_SCHEM and * PROCEDURE_NAME. Within this, the return value, if any, is first. Next * are the parameter descriptions in call order. The column descriptions * follow in column number order.
* * Each row in the ResultSet is a parameter description or column * description with the following fields: *
*
* Note: Some databases may not return the column descriptions for a
* procedure. Additional columns beyond REMARKS can be defined by the
* database.
*
* @param catalog a catalog name; "" retrieves those without a
* null means drop catalog name from the selection criteria
* @param schemaPattern a schema name pattern; "" retrieves those
* without a schema
* @param procedureNamePattern a procedure name pattern
* @param columnNamePattern a column name pattern
* @return ResultSet - each row is a stored procedure parameter or column description
* @throws SQLException if a database-access error occurs.
* @see #getSearchStringEscape
*/
public java.sql.ResultSet getProcedureColumns(String catalog,
String schemaPattern,
String procedureNamePattern,
String columnNamePattern)
throws SQLException {
String colNames[] = {"PROCEDURE_CAT", "PROCEDURE_SCHEM",
"PROCEDURE_NAME", "COLUMN_NAME",
"COLUMN_TYPE", "DATA_TYPE",
"TYPE_NAME", "PRECISION",
"LENGTH", "SCALE",
"RADIX", "NULLABLE",
"REMARKS"};
int colTypes[] = {Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR,
Types.SMALLINT, Types.INTEGER,
Types.VARCHAR, Types.INTEGER,
Types.INTEGER, Types.SMALLINT,
Types.SMALLINT, Types.SMALLINT,
Types.VARCHAR};
String query = "sp_sproc_columns ?, ?, ?, ?, ?";
CallableStatement s = connection.prepareCall(syscall(catalog,query));
s.setString(1, processEscapes(procedureNamePattern));
s.setString(2, processEscapes(schemaPattern));
s.setString(3, catalog);
s.setString(4, processEscapes(columnNamePattern));
s.setInt(5, 3); // ODBC version 3
JtdsResultSet rs = (JtdsResultSet)s.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
CachedResultSet rsTmp = new CachedResultSet((JtdsStatement)s, colNames, colTypes);
rsTmp.moveToInsertRow();
while (rs.next()) {
int offset = 0;
for (int i = 1; i + offset <= colNames.length; i++) {
if (i == 5 && !"column_type".equalsIgnoreCase(rsmd.getColumnName(i))) {
// With Sybase 11.92 despite what the documentation says, the
// column_type column is missing!
// Set the output value to 0 and shift the rest along by one.
String colName = rs.getString(4);
if ("RETURN_VALUE".equals(colName)) {
rsTmp.updateInt(i, DatabaseMetaData.procedureColumnReturn);
} else {
rsTmp.updateInt(i, DatabaseMetaData.procedureColumnUnknown);
}
offset = 1;
}
if (i == 3) {
String name = rs.getString(i);
if (name != null && name.length() > 0) {
int pos = name.lastIndexOf(';');
if (pos >= 0) {
name = name.substring(0, pos);
}
}
rsTmp.updateString(i + offset, name);
} else if ("data_type".equalsIgnoreCase(rsmd.getColumnName(i))) {
int type = TypeInfo.normalizeDataType(rs.getInt(i), connection.getUseLOBs());
rsTmp.updateInt(i + offset, type);
} else {
rsTmp.updateObject(i + offset, rs.getObject(i));
}
}
if (serverType == Driver.SYBASE && rsmd.getColumnCount() >= 22) {
//
// For Sybase 12.5+ we can obtain column in/out status from
// the mode column.
//
String mode = rs.getString(22);
if (mode != null) {
if (mode.equalsIgnoreCase("in")) {
rsTmp.updateInt(5, DatabaseMetaData.procedureColumnIn);
} else
if (mode.equalsIgnoreCase("out")) {
rsTmp.updateInt(5, DatabaseMetaData.procedureColumnInOut);
}
}
}
if (serverType == Driver.SYBASE
|| tdsVersion == Driver.TDS42
|| tdsVersion == Driver.TDS70) {
//
// Standardise the name of the return_value column as
// @RETURN_VALUE for Sybase and SQL < 2000
//
String colName = rs.getString(4);
if ("RETURN_VALUE".equals(colName)) {
rsTmp.updateString(4, "@RETURN_VALUE");
}
}
rsTmp.insertRow();
}
rs.close();
rsTmp.moveToCurrentRow();
rsTmp.setConcurrency(ResultSet.CONCUR_READ_ONLY);
return rsTmp;
}
/**
* Get a description of stored procedures available in a catalog.
* * Only procedure descriptions matching the schema and procedure name * criteria are returned. They are ordered by PROCEDURE_SCHEM, and * PROCEDURE_NAME.
* * Each procedure description has the the following columns: *
null means drop catalog name from the selection criteria
* @param schemaPattern a schema name pattern; "" retrieves those
* without a schema
* @param procedureNamePattern a procedure name pattern
* @return ResultSet - each row is a procedure description
* @throws SQLException if a database-access error occurs.
*
* @see #getSearchStringEscape
*/
public java.sql.ResultSet getProcedures(String catalog,
String schemaPattern,
String procedureNamePattern)
throws SQLException {
String colNames[] = {"PROCEDURE_CAT", "PROCEDURE_SCHEM",
"PROCEDURE_NAME", "RESERVED_1",
"RESERVED_2", "RESERVED_3",
"REMARKS", "PROCEDURE_TYPE"};
int colTypes[] = {Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.INTEGER,
Types.INTEGER, Types.INTEGER,
Types.VARCHAR, Types.SMALLINT};
String query = "sp_stored_procedures ?, ?, ?";
CallableStatement s = connection.prepareCall(syscall(catalog, query));
s.setString(1, processEscapes(procedureNamePattern));
s.setString(2, processEscapes(schemaPattern));
s.setString(3, catalog);
JtdsResultSet rs = (JtdsResultSet)s.executeQuery();
CachedResultSet rsTmp = new CachedResultSet((JtdsStatement)s, colNames, colTypes);
rsTmp.moveToInsertRow();
int colCnt = rs.getMetaData().getColumnCount();
//
// Copy results to local result set.
//
while (rs.next()) {
rsTmp.updateString(1, rs.getString(1));
rsTmp.updateString(2, rs.getString(2));
String name = rs.getString(3);
if (name != null) {
// Remove grouping integer
if (name.endsWith(";1")) {
name = name.substring(0, name.length() - 2);
}
}
rsTmp.updateString(3, name);
// Copy over rest of fields
for (int i = 4; i <= colCnt; i++) {
rsTmp.updateObject(i, rs.getObject(i));
}
if (colCnt < 8) {
// Sybase does not return this column so fake it now.
rsTmp.updateShort(8, (short)DatabaseMetaData.procedureReturnsResult);
}
rsTmp.insertRow();
}
rsTmp.moveToCurrentRow();
rsTmp.setConcurrency(ResultSet.CONCUR_READ_ONLY);
rs.close();
return rsTmp;
}
/**
* What's the database vendor's preferred term for "procedure"?
*
* @return the vendor term
* @throws SQLException if a database-access error occurs.
*/
public String getProcedureTerm() throws SQLException {
// per "Programming ODBC for SQLServer" Appendix A
return "stored procedure";
}
/**
* Get the schema names available in this database. The results are ordered
* by schema name. * * The schema column is: *
null, JDBC 3.0)
* ResultSet object in which each row is a schema description
* @throws SQLException if a database access error occurs
*/
public java.sql.ResultSet getSchemas() throws SQLException {
java.sql.Statement statement = connection.createStatement();
String sql;
if (connection.getServerType() == Driver.SQLSERVER && connection.getDatabaseMajorVersion() >= 9) {
sql = Driver.JDBC3
? "SELECT name AS TABLE_SCHEM, NULL as TABLE_CATALOG FROM sys.schemas"
: "SELECT name AS TABLE_SCHEM FROM sys.schemas";
} else {
sql = Driver.JDBC3
? "SELECT name AS TABLE_SCHEM, NULL as TABLE_CATALOG FROM dbo.sysusers"
: "SELECT name AS TABLE_SCHEM FROM dbo.sysusers";
//
// MJH - isLogin column only in MSSQL >= 7.0
//
if (tdsVersion >= Driver.TDS70) {
sql += " WHERE islogin=1";
} else {
sql += " WHERE uid>0";
}
}
sql += " ORDER BY TABLE_SCHEM";
return statement.executeQuery(sql);
}
/**
* What's the database vendor's preferred term for "schema"?
*
* @return the vendor term
* @throws SQLException if a database-access error occurs.
*/
public String getSchemaTerm() throws SQLException {
return "owner";
}
/**
* This is the string that can be used to escape '_' or '%' in the string
* pattern style catalog search parameters. * * The '_' character represents any single character.
* * The '%' character represents any sequence of zero or more characters. * * @return the string used to escape wildcard characters * @throws SQLException if a database-access error occurs. */ public String getSearchStringEscape() throws SQLException { // per "Programming ODBC for SQLServer" Appendix A return "\\"; } /** * Get a comma separated list of all a database's SQL keywords that are NOT * also SQL92 keywords. * * @return the list * @throws SQLException if a database-access error occurs. */ public String getSQLKeywords() throws SQLException { // // This is a superset of the SQL keywords in SQL Server and Sybase // return "ARITH_OVERFLOW,BREAK,BROWSE,BULK,CHAR_CONVERT,CHECKPOINT," + "CLUSTERED,COMPUTE,CONFIRM,CONTROLROW,DATA_PGS,DATABASE,DBCC," + "DISK,DUMMY,DUMP,ENDTRAN,ERRLVL,ERRORDATA,ERROREXIT,EXIT," + "FILLFACTOR,HOLDLOCK,IDENTITY_INSERT,IF,INDEX,KILL,LINENO," + "LOAD,MAX_ROWS_PER_PAGE,MIRROR,MIRROREXIT,NOHOLDLOCK,NONCLUSTERED," + "NUMERIC_TRUNCATION,OFF,OFFSETS,ONCE,ONLINE,OVER,PARTITION,PERM," + "PERMANENT,PLAN,PRINT,PROC,PROCESSEXIT,RAISERROR,READ,READTEXT," + "RECONFIGURE,REPLACE,RESERVED_PGS,RETURN,ROLE,ROWCNT,ROWCOUNT," + "RULE,SAVE,SETUSER,SHARED,SHUTDOWN,SOME,STATISTICS,STRIPE," + "SYB_IDENTITY,SYB_RESTREE,SYB_TERMINATE,TEMP,TEXTSIZE,TRAN," + "TRIGGER,TRUNCATE,TSEQUAL,UNPARTITION,USE,USED_PGS,USER_OPTION," + "WAITFOR,WHILE,WRITETEXT"; } /** * Get a comma separated list of string functions. * * @return the list * @throws SQLException if a database-access error occurs. */ public String getStringFunctions() throws SQLException { if (connection.getServerType() == Driver.SQLSERVER) { return "ascii,char,concat,difference,insert,lcase,left,length,locate," + "ltrim,repeat,replace,right,rtrim,soundex,space,substring,ucase"; } else { return "ascii,char,concat,difference,insert,lcase,length," + "ltrim,repeat,right,rtrim,soundex,space,substring,ucase"; } } /** * Get a comma separated list of system functions. * * @return the list * @throws SQLException if a database-access error occurs. */ public String getSystemFunctions() throws SQLException { return "database,ifnull,user,convert"; } /** * Get a description of the access rights for each table available in a * catalog. Note that a table privilege applies to one or more columns in * the table. It would be wrong to assume that this priviledge applies to * all columns (this may be true for some systems but is not true for all.) *
* * Only privileges matching the schema and table name criteria are * returned. They are ordered by TABLE_SCHEM, TABLE_NAME, and PRIVILEGE. *
* * Each privilige description has the following columns: *
null means drop catalog name from the selection criteria
* @param schemaPattern a schema name pattern; "" retrieves those
* without a schema
* @param tableNamePattern a table name pattern
* @return ResultSet - each row is a table privilege description
* @throws SQLException if a database-access error occurs.
*
* @see #getSearchStringEscape
*/
public java.sql.ResultSet getTablePrivileges(String catalog,
String schemaPattern,
String tableNamePattern)
throws SQLException {
String query = "sp_table_privileges ?, ?, ?";
CallableStatement s = connection.prepareCall(syscall(catalog, query));
s.setString(1, processEscapes(tableNamePattern));
s.setString(2, processEscapes(schemaPattern));
s.setString(3, catalog);
JtdsResultSet rs = (JtdsResultSet)s.executeQuery();
rs.setColLabel(1, "TABLE_CAT");
rs.setColLabel(2, "TABLE_SCHEM");
upperCaseColumnNames(rs);
return rs;
}
/**
* Get a description of tables available in a catalog. * * Only table descriptions matching the catalog, schema, table name and * type criteria are returned. They are ordered by TABLE_TYPE, TABLE_SCHEM * and TABLE_NAME.
* * Each table description has the following columns: *
null)
* null)
* null)
* null)
* null)
*
*
* Note: Some databases may not return information for all tables.
*
* @param catalog a catalog name; "" retrieves those without a
* null means drop catalog name from the selection criteria
* @param schemaPattern a schema name pattern; "" retrieves those
* without a schema
* @param tableNamePattern a table name pattern
* @param types a list of table types to include; null returns all types
* @return ResultSet - each row is a table description
* @throws SQLException if a database-access error occurs.
*
* @see #getSearchStringEscape
*/
public java.sql.ResultSet getTables(String catalog,
String schemaPattern,
String tableNamePattern,
String types[])
throws SQLException {
String colNames[] = {"TABLE_CAT", "TABLE_SCHEM",
"TABLE_NAME", "TABLE_TYPE",
"REMARKS", "TYPE_CAT",
"TYPE_SCHEM", "TYPE_NAME",
"SELF_REFERENCING_COL_NAME", "REF_GENERATION"};
int colTypes[] = {Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR};
String query = "sp_tables ?, ?, ?, ?";
CallableStatement cstmt = connection.prepareCall(syscall(catalog, query));
cstmt.setString(1, processEscapes(tableNamePattern));
cstmt.setString(2, processEscapes(schemaPattern));
cstmt.setString(3, catalog);
if (types == null) {
cstmt.setString(4, null);
} else {
StringBuffer buf = new StringBuffer(64);
buf.append('"');
for (int i = 0; i < types.length; i++) {
buf.append('\'').append(types[i]).append("',");
}
if (buf.length() > 1) {
buf.setLength(buf.length() - 1);
}
buf.append('"');
cstmt.setString(4, buf.toString());
}
JtdsResultSet rs = (JtdsResultSet) cstmt.executeQuery();
CachedResultSet rsTmp = new CachedResultSet((JtdsStatement)cstmt, colNames, colTypes);
rsTmp.moveToInsertRow();
int colCnt = rs.getMetaData().getColumnCount();
//
// Copy results to local result set.
//
while (rs.next()) {
for (int i = 1; i <= colCnt; i++) {
rsTmp.updateObject(i, rs.getObject(i));
}
rsTmp.insertRow();
}
rsTmp.moveToCurrentRow();
rsTmp.setConcurrency(ResultSet.CONCUR_READ_ONLY);
rs.close();
return rsTmp;
}
/**
* Get the table types available in this database. The results are ordered
* by table type.
* * The table type is: *
* * Each type description has the following columns: *
* * Only types matching the catalog, schema, type name and type criteria are * returned. They are ordered by DATA_TYPE, TYPE_SCHEM and TYPE_NAME. The * type name parameter may be a fully-qualified name. In this case, the * catalog and schemaPattern parameters are ignored.
* * Each type description has the following columns: *
*
* Note: If the driver does not support UDTs, an empty result set is
* returned.
*
* @param catalog a catalog name; "" retrieves those without a
* null means drop catalog name from the selection criteria
* @param schemaPattern a schema name pattern; "" retrieves those
* without a schema
* @param typeNamePattern a type name pattern; may be a fully-qualified
* name
* @param types a list of user-named types to include
* (JAVA_OBJECT, STRUCT, or DISTINCT); null returns all types
* @return ResultSet - each row is a type description
* @throws SQLException if a database access error occurs
*/
public java.sql.ResultSet getUDTs(String catalog,
String schemaPattern,
String typeNamePattern,
int[] types)
throws SQLException {
String colNames[] = {"TYPE_CAT", "TYPE_SCHEM",
"TYPE_NAME", "CLASS_NAME",
"DATA_TYPE", "REMARKS",
"BASE_TYPE"};
int colTypes[] = {Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR,
Types.INTEGER, Types.VARCHAR,
Types.SMALLINT};
//
// Return an empty result set
//
JtdsStatement dummyStmt = (JtdsStatement) connection.createStatement();
CachedResultSet rs = new CachedResultSet(dummyStmt, colNames, colTypes);
rs.setConcurrency(ResultSet.CONCUR_READ_ONLY);
return rs;
}
/**
* What's the URL for this database?
*
* @return the URL or null if it can't be generated
* @throws SQLException if a database-access error occurs
*/
public String getURL() throws SQLException {
return connection.getURL();
}
/**
* What's our user name as known to the database?
*
* @return our database user name
* @throws SQLException if a database-access error occurs.
*/
public String getUserName() throws SQLException {
java.sql.Statement s = null;
java.sql.ResultSet rs = null;
String result = "";
try {
s = connection.createStatement();
// MJH Sybase does not support system_user
if (connection.getServerType() == Driver.SYBASE) {
rs = s.executeQuery("select suser_name()");
} else {
rs = s.executeQuery("select system_user");
}
if (!rs.next()) {
throw new SQLException(Messages.get("error.dbmeta.nouser"), "HY000");
}
result = rs.getString(1);
} finally {
if (rs != null) {
rs.close();
}
if (s != null) {
s.close();
}
}
return result;
}
/**
* Get a description of a table's columns that are automatically updated
* when any value in a row is updated. They are unordered.
* * Each column description has the following columns: *
null means drop catalog name from the selection criteria
* @param schema a schema name; "" retrieves those without a schema
* @param table a table name
* @return ResultSet - each row is a column description
* @throws SQLException if a database-access error occurs.
*/
public java.sql.ResultSet getVersionColumns(String catalog,
String schema,
String table)
throws SQLException {
String colNames[] = {"SCOPE", "COLUMN_NAME","DATA_TYPE",
"TYPE_NAME","COLUMN_SIZE",
"BUFFER_LENGTH","DECIMAL_DIGITS",
"PSEUDO_COLUMN"};
int colTypes[] = {Types.SMALLINT,Types.VARCHAR,
Types.INTEGER, Types.VARCHAR,
Types.INTEGER, Types.INTEGER,
Types.SMALLINT,Types.SMALLINT};
String query = "sp_special_columns ?, ?, ?, ?, ?, ?, ?";
CallableStatement s = connection.prepareCall(syscall(catalog, query));
s.setString(1, table);
s.setString(2, schema);
s.setString(3, catalog);
s.setString(4, "V");
s.setString(5, "C");
s.setString(6, "O");
s.setInt(7, 3); // ODBC version 3
JtdsResultSet rs = (JtdsResultSet) s.executeQuery();
CachedResultSet rsTmp = new CachedResultSet((JtdsStatement)s, colNames, colTypes);
rsTmp.moveToInsertRow();
int colCnt = rs.getMetaData().getColumnCount();
//
// Copy results to local result set.
//
while (rs.next()) {
for (int i = 1; i <= colCnt; i++) {
rsTmp.updateObject(i, rs.getObject(i));
}
rsTmp.insertRow();
}
rsTmp.moveToCurrentRow();
rsTmp.setConcurrency(ResultSet.CONCUR_READ_ONLY);
rs.close();
return rsTmp;
}
/**
* Retrieves whether a catalog appears at the start of a fully qualified
* table name. If not, the catalog appears at the end.
*
* @return true if it appears at the start
* @throws SQLException if a database-access error occurs.
*/
public boolean isCatalogAtStart() throws SQLException {
return true;
}
/**
* Is the database in read-only mode?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean isReadOnly() throws SQLException {
return false;
}
/**
* JDBC 2.0 Retrieves the connection that produced this metadata object.
*
* @return the connection that produced this metadata object
* @throws SQLException if a database-access error occurs.
*/
public java.sql.Connection getConnection() throws SQLException {
return connection;
}
/**
* Retrieves whether this database supports concatenations between
* NULL and non-NULL values being
* NULL.
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean nullPlusNonNullIsNull() throws SQLException {
// Sybase 11.92 says true
// MS SQLServer seems to break with the SQL standard here.
// maybe there is an option to make null behavior comply
//
// SAfe: Nope, it seems to work fine in SQL Server 7.0
return true;
}
/**
* Are NULL values sorted at the end regardless of sort order?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean nullsAreSortedAtEnd() throws SQLException {
return false;
}
/**
* Are NULL values sorted at the start regardless of sort order?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean nullsAreSortedAtStart() throws SQLException {
return false;
}
/**
* Are NULL values sorted high?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean nullsAreSortedHigh() throws SQLException {
return false;
}
/**
* Are NULL values sorted low?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean nullsAreSortedLow() throws SQLException {
return true;
}
/**
* Does the database treat mixed case unquoted SQL identifiers as case
* insensitive and store them in lower case?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean storesLowerCaseIdentifiers() throws SQLException {
return false;
}
/**
* Does the database treat mixed case quoted SQL identifiers as case
* insensitive and store them in lower case?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean storesLowerCaseQuotedIdentifiers() throws SQLException {
return false;
}
/**
* Does the database treat mixed case unquoted SQL identifiers as case
* insensitive and store them in mixed case?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean storesMixedCaseIdentifiers() throws SQLException {
setCaseSensitiveFlag();
return !caseSensitive.booleanValue();
}
/**
* Does the database treat mixed case quoted SQL identifiers as case
* insensitive and store them in mixed case?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean storesMixedCaseQuotedIdentifiers() throws SQLException {
setCaseSensitiveFlag();
return !caseSensitive.booleanValue();
}
/**
* Does the database treat mixed case unquoted SQL identifiers as case
* insensitive and store them in upper case?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean storesUpperCaseIdentifiers() throws SQLException {
return false;
}
/**
* Does the database treat mixed case quoted SQL identifiers as case
* insensitive and store them in upper case?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean storesUpperCaseQuotedIdentifiers() throws SQLException {
return false;
}
//--------------------------------------------------------------------
// Functions describing which features are supported.
/**
* Is "ALTER TABLE" with add column supported?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsAlterTableWithAddColumn() throws SQLException {
return true;
}
/**
* Is "ALTER TABLE" with drop column supported?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsAlterTableWithDropColumn() throws SQLException {
return true;
}
/**
* Retrieves whether this database supports the ANSI92 entry level SQL
* grammar.
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsANSI92EntryLevelSQL() throws SQLException {
return true;
}
/**
* Is the ANSI92 full SQL grammar supported?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsANSI92FullSQL() throws SQLException {
return false;
}
/**
* Is the ANSI92 intermediate SQL grammar supported?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsANSI92IntermediateSQL() throws SQLException {
return false;
}
/**
* Can a catalog name be used in a data manipulation statement?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsCatalogsInDataManipulation() throws SQLException {
return true;
}
/**
* Can a catalog name be used in an index definition statement?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsCatalogsInIndexDefinitions() throws SQLException {
return true;
}
/**
* Can a catalog name be used in a privilege definition statement?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException {
return true;
}
/**
* Can a catalog name be used in a procedure call statement?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsCatalogsInProcedureCalls() throws SQLException {
return true;
}
/**
* Can a catalog name be used in a table definition statement?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsCatalogsInTableDefinitions() throws SQLException {
return true;
}
/**
* Retrieves whether this database supports column aliasing.
*
* If so, the SQL AS clause can be used to provide names for computed
* columns or to provide alias names for columns as required. A
* JDBC-Compliant driver always returns true.
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsColumnAliasing() throws SQLException {
return true;
}
/**
* Is the CONVERT function between SQL types supported?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsConvert() throws SQLException {
return true;
}
/**
* Is CONVERT between the given SQL types supported?
*
* @param fromType the type to convert from
* @param toType the type to convert to
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsConvert(int fromType, int toType)
throws SQLException {
if (fromType == toType) {
return true;
}
switch (fromType) {
// SAfe Most types will convert to anything but IMAGE and
// TEXT/NTEXT (and UNIQUEIDENTIFIER, but that's not a standard
// type).
case Types.BIT:
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
case Types.BIGINT:
case Types.FLOAT:
case Types.REAL:
case Types.DOUBLE:
case Types.NUMERIC:
case Types.DECIMAL:
case Types.DATE:
case Types.TIME:
case Types.TIMESTAMP:
return toType != Types.LONGVARCHAR && toType != Types.LONGVARBINARY
&& toType != Types.BLOB && toType != Types.CLOB;
case Types.BINARY:
case Types.VARBINARY:
return toType != Types.FLOAT && toType != Types.REAL
&& toType != Types.DOUBLE;
// IMAGE
case Types.BLOB:
case Types.LONGVARBINARY:
return toType == Types.BINARY || toType == Types.VARBINARY
|| toType == Types.BLOB || toType == Types.LONGVARBINARY;
// TEXT and NTEXT
case Types.CLOB:
case Types.LONGVARCHAR:
return toType == Types.CHAR || toType == Types.VARCHAR
|| toType == Types.CLOB || toType == Types.LONGVARCHAR;
// These types can be converted to anything
case Types.NULL:
case Types.CHAR:
case Types.VARCHAR:
return true;
// We can't tell for sure what will happen with other types, so...
case Types.OTHER:
default:
return false;
}
}
/**
* Is the ODBC Core SQL grammar supported?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsCoreSQLGrammar() throws SQLException {
return true;
}
/**
* Retrieves whether this database supports correlated subqueries.
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsCorrelatedSubqueries() throws SQLException {
return true;
}
/**
* Are both data definition and data manipulation statements within a
* transaction supported?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsDataDefinitionAndDataManipulationTransactions()
throws SQLException {
// Sybase requires the 'DDL IN TRAN' db option to be set for
// This to be strictly true.
return true;
}
/**
* Are only data manipulation statements within a transaction supported?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsDataManipulationTransactionsOnly()
throws SQLException {
return false;
}
/**
* If table correlation names are supported, are they restricted to be
* different from the names of the tables?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsDifferentTableCorrelationNames() throws SQLException {
return false;
}
/**
* Are expressions in "ORDER BY" lists supported?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsExpressionsInOrderBy() throws SQLException {
return true;
}
/**
* Is the ODBC Extended SQL grammar supported?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsExtendedSQLGrammar() throws SQLException {
return false;
}
/**
* Are full nested outer joins supported?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsFullOuterJoins() throws SQLException {
if (connection.getServerType() == Driver.SYBASE) {
// Supported since version 12
return getDatabaseMajorVersion() >= 12;
}
return true;
}
/**
* Is some form of "GROUP BY" clause supported?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsGroupBy() throws SQLException {
return true;
}
/**
* Can a "GROUP BY" clause add columns not in the SELECT provided it
* specifies all the columns in the SELECT?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsGroupByBeyondSelect() throws SQLException {
// per "Programming ODBC for SQLServer" Appendix A
return true;
}
/**
* Can a "GROUP BY" clause use columns not in the SELECT?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsGroupByUnrelated() throws SQLException {
return true;
}
/**
* Is the SQL Integrity Enhancement Facility supported?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsIntegrityEnhancementFacility() throws SQLException {
return false;
}
/**
* Retrieves whether this database supports specifying a LIKE
* escape clause.
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsLikeEscapeClause() throws SQLException {
// per "Programming ODBC for SQLServer" Appendix A
return true;
}
/**
* Retrieves whether this database provides limited support for outer
* joins. (This will be true if the method
* supportsFullOuterJoins returns true).
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsLimitedOuterJoins() throws SQLException {
return true;
}
/**
* Retrieves whether this database supports the ODBC Minimum SQL grammar.
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsMinimumSQLGrammar() throws SQLException {
return true;
}
/**
* Retrieves whether this database treats mixed case unquoted SQL identifiers as
* case sensitive and as a result stores them in mixed case.
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsMixedCaseIdentifiers() throws SQLException {
setCaseSensitiveFlag();
return caseSensitive.booleanValue();
}
/**
* Retrieves whether this database treats mixed case quoted SQL identifiers as
* case sensitive and as a result stores them in mixed case.
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException {
setCaseSensitiveFlag();
return caseSensitive.booleanValue();
}
/**
* Are multiple ResultSets from a single execute supported?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsMultipleResultSets() throws SQLException {
return true;
}
/**
* Can we have multiple transactions open at once (on different
* connections)?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsMultipleTransactions() throws SQLException {
return true;
}
/**
* Retrieves whether columns in this database may be defined as non-nullable.
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsNonNullableColumns() throws SQLException {
return true;
}
/**
* Can cursors remain open across commits?
*
* @return true if cursors always remain open;
* false if they might not remain open
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsOpenCursorsAcrossCommit() throws SQLException {
// MS JDBC says false
return true;
}
/**
* Can cursors remain open across rollbacks?
*
* @return true if cursors always remain open;
* false if they might not remain open
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsOpenCursorsAcrossRollback() throws SQLException {
// JConnect says true
return connection.getServerType() == Driver.SYBASE;
}
/**
* Can statements remain open across commits?
*
* @return true if statements always remain open;
* false if they might not remain open
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsOpenStatementsAcrossCommit() throws SQLException {
return true;
}
/**
* Can statements remain open across rollbacks?
*
* @return true if statements always remain open;
* false if they might not remain open
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsOpenStatementsAcrossRollback() throws SQLException {
return true;
}
/**
* Can an "ORDER BY" clause use columns not in the SELECT?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsOrderByUnrelated() throws SQLException {
return true;
}
/**
* Is some form of outer join supported?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsOuterJoins() throws SQLException {
return true;
}
/**
* Is positioned DELETE supported?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsPositionedDelete() throws SQLException {
return true;
}
/**
* Is positioned UPDATE supported?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsPositionedUpdate() throws SQLException {
return true;
}
/**
* Can a schema name be used in a data manipulation statement?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsSchemasInDataManipulation() throws SQLException {
return true;
}
/**
* Can a schema name be used in an index definition statement?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsSchemasInIndexDefinitions() throws SQLException {
return true;
}
/**
* Can a schema name be used in a privilege definition statement?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsSchemasInPrivilegeDefinitions() throws SQLException {
return true;
}
/**
* Can a schema name be used in a procedure call statement?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsSchemasInProcedureCalls() throws SQLException {
return true;
}
/**
* Can a schema name be used in a table definition statement?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsSchemasInTableDefinitions() throws SQLException {
return true;
}
/**
* Is SELECT for UPDATE supported?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsSelectForUpdate() throws SQLException {
// XXX Server supports it driver doesn't currently
// As far as I know the SQL Server FOR UPDATE is not the same as the
// standard SQL FOR UPDATE
return false;
}
/**
* Are stored procedure calls using the stored procedure escape syntax
* supported?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsStoredProcedures() throws SQLException {
return true;
}
/**
* Retrieves whether this database supports subqueries in comparison
* expressions.
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsSubqueriesInComparisons() throws SQLException {
return true;
}
/**
* Retrieves whether this database supports subqueries in
* EXISTS expressions.
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsSubqueriesInExists() throws SQLException {
return true;
}
/**
* Retrieves whether this database supports subqueries in
* IN statements.
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsSubqueriesInIns() throws SQLException {
return true;
}
/**
* Retrieves whether this database supports subqueries in quantified
* expressions.
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsSubqueriesInQuantifieds() throws SQLException {
return true;
}
/**
* Retrieves whether this database supports table correlation names.
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsTableCorrelationNames() throws SQLException {
return true;
}
/**
* Does the database support the given transaction isolation level?
*
* @param level the values are defined in java.sql.Connection
* @return true if so
* @throws SQLException if a database-access error occurs.
*
* @see Connection
*/
public boolean supportsTransactionIsolationLevel(int level)
throws SQLException {
switch (level) {
case Connection.TRANSACTION_READ_UNCOMMITTED:
case Connection.TRANSACTION_READ_COMMITTED:
case Connection.TRANSACTION_REPEATABLE_READ:
case Connection.TRANSACTION_SERIALIZABLE:
return true;
// TRANSACTION_NONE not supported. It means there is no support for
// transactions
case Connection.TRANSACTION_NONE:
default:
return false;
}
}
/**
* Retrieves whether this database supports transactions. If not, invoking the
* method commit is a noop, and the isolation level is
* TRANSACTION_NONE.
*
* @return true if transactions are supported
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsTransactions() throws SQLException {
return true;
}
/**
* Is SQL UNION supported?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsUnion() throws SQLException {
return true;
}
/**
* Is SQL UNION ALL supported?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean supportsUnionAll() throws SQLException {
return true;
}
/**
* Does the database use a file for each table?
*
* @return true if the database uses a local file for each
* table
* @throws SQLException if a database-access error occurs.
*/
public boolean usesLocalFilePerTable() throws SQLException {
return false;
}
/**
* Does the database store tables in a local file?
*
* @return true if so
* @throws SQLException if a database-access error occurs.
*/
public boolean usesLocalFiles() throws SQLException {
return false;
}
//--------------------------JDBC 2.0-----------------------------
/**
* Does the database support the given result set type?
*
| JDBC type | *SQL Server cursor type | *Server load | *Description | *
| TYPE_FORWARD_ONLY | *Forward-only, dynamic (fast forward-only, static with useCursors=true) |
* Light | *Fast, will read all data (less fast, doesn't read all data with useCursors=true). Forward only. |
*
| TYPE_SCROLL_INSENSITIVE | *Static cursor | *Heavy | *Only use with CONCUR_READ_ONLY. SQL Server generates a temporary table, so changes made by others are not visible. Scrollable. | *
| TYPE_SCROLL_SENSITIVE | *Keyset cursor | *Medium | *Others' updates or deletes visible, but not others' inserts. Scrollable. | *
| TYPE_SCROLL_SENSITIVE + 1 | *Dynamic cursor | *Heavy | *Others' updates, deletes and inserts visible. Scrollable. | *
java.sql.ResultSet
* @return true if so; false otherwise
* @throws SQLException if a database access error occurs
*
* @see Connection
* @see #supportsResultSetConcurrency
*/
public boolean supportsResultSetType(int type) throws SQLException {
// jTDS supports all standard ResultSet types plus
// TYPE_SCROLL_SENSITIVE + 1
return type >= ResultSet.TYPE_FORWARD_ONLY
&& type <= ResultSet.TYPE_SCROLL_SENSITIVE + 1;
}
/**
* Does the database support the concurrency type in combination with the
* given result set type?
*
* Supported concurrencies for SQL Server:
* | JDBC concurrency | *SQL Server concurrency | *Row locks | *Description | *
| CONCUR_READ_ONLY | *Read only | *No | *Read-only. | *
| CONCUR_UPDATABLE | *Optimistic concurrency, updatable | *No | *Row integrity checked with timestamp comparison or, when not available, value comparison (except text and image fields). | *
| CONCUR_UPDATABLE+1 | *Pessimistic concurrency, updatable | *Yes | *Row integrity is ensured by locking rows. | *
| CONCUR_UPDATABLE+2 | *Optimistic concurrency, updatable | *No | *Row integrity checked with value comparison (except text and image fields). | *
java.sql.ResultSet
* @param concurrency type defined in java.sql.ResultSet
* @return true if so; false otherwise
* @throws SQLException if a database access error occurs
*
* @see Connection
* @see #supportsResultSetType
*/
public boolean supportsResultSetConcurrency(int type, int concurrency)
throws SQLException {
// jTDS supports both all standard ResultSet concurencies plus
// CONCUR_UPDATABLE + 1 and CONCUR_UPDATABLE + 2, except the
// TYPE_SCROLL_INSENSITIVE/CONCUR_UPDATABLE combination on SQL Server
if (!supportsResultSetType(type)) {
return false;
}
if (concurrency < ResultSet.CONCUR_READ_ONLY
|| concurrency > ResultSet.CONCUR_UPDATABLE + 2) {
return false;
}
return type != ResultSet.TYPE_SCROLL_INSENSITIVE
|| concurrency == ResultSet.CONCUR_READ_ONLY;
}
/**
* JDBC 2.0 Indicates whether a result set's own updates are visible.
*
* @param type ResultSet type
* @return true if updates are visible for the
* result set type; false otherwise
* @throws SQLException if a database access error occurs
*/
public boolean ownUpdatesAreVisible(int type) throws SQLException {
return true;
}
/**
* JDBC 2.0 Indicates whether a result set's own deletes are visible.
*
* @param type ResultSet type
* @return true if deletes are visible for the
* result set type; false otherwise
* @throws SQLException if a database access error occurs
*/
public boolean ownDeletesAreVisible(int type) throws SQLException {
return true;
}
/**
* JDBC 2.0 Indicates whether a result set's own inserts are visible.
*
* @param type ResultSet type
* @return true if inserts are visible for the
* result set type; false otherwise
* @throws SQLException if a database access error occurs
*/
public boolean ownInsertsAreVisible(int type) throws SQLException {
return true;
}
/**
* JDBC 2.0 Indicates whether updates made by others are visible.
*
* @param type ResultSet type
* @return true if updates made by others are
* visible for the result set type; false otherwise
* @throws SQLException if a database access error occurs
*/
public boolean othersUpdatesAreVisible(int type) throws SQLException {
// Updates are visibile in scroll sensitive ResultSets
return type >= ResultSet.TYPE_SCROLL_SENSITIVE;
}
/**
* JDBC 2.0 Indicates whether deletes made by others are visible.
*
* @param type ResultSet type
* @return true if deletes made by others are
* visible for the result set type; false otherwise
* @throws SQLException if a database access error occurs
*/
public boolean othersDeletesAreVisible(int type) throws SQLException {
// Deletes are visibile in scroll sensitive ResultSets
return type >= ResultSet.TYPE_SCROLL_SENSITIVE;
}
/**
* JDBC 2.0 Indicates whether inserts made by others are visible.
*
* @param type ResultSet type
* @return true if inserts made by others are visible
* for the result set type; false otherwise
* @throws SQLException if a database access error occurs
*/
public boolean othersInsertsAreVisible(int type) throws SQLException {
// Inserts are only visibile with dynamic cursors
return type == ResultSet.TYPE_SCROLL_SENSITIVE + 1;
}
/**
* JDBC 2.0 Indicates whether or not a visible row update can be detected
* by calling the method ResultSet.rowUpdated .
*
* @param type ResultSet type
* @return true if changes are detected by the
* result set type; false otherwise
* @throws SQLException if a database access error occurs
*/
public boolean updatesAreDetected(int type) throws SQLException {
// Seems like there's no support for this in SQL Server
return false;
}
/**
* JDBC 2.0 Indicates whether or not a visible row delete can be detected
* by calling ResultSet.rowDeleted(). If deletesAreDetected() returns
* false, then deleted rows are removed from the result set.
*
* @param type ResultSet type
* @return true if changes are detected by the result set type
* @throws SQLException if a database access error occurs
*/
public boolean deletesAreDetected(int type) throws SQLException {
return true;
}
/**
* JDBC 2.0 Indicates whether or not a visible row insert can be detected
* by calling ResultSet.rowInserted().
*
* @param type ResultSet type
* @return true if changes are detected by the result set type
* @throws SQLException if a database access error occurs
*/
public boolean insertsAreDetected(int type) throws SQLException {
// Seems like there's no support for this in SQL Server
return false;
}
/**
* JDBC 2.0 Indicates whether the driver supports batch updates.
*
* @return true if the driver supports batch updates;
* false otherwise
* @throws SQLException if a database access error occurs
*/
public boolean supportsBatchUpdates() throws SQLException {
return true;
}
private void setCaseSensitiveFlag() throws SQLException {
if (caseSensitive == null) {
Statement s = connection.createStatement();
ResultSet rs = s.executeQuery("sp_server_info 16");
rs.next();
caseSensitive = "MIXED".equalsIgnoreCase(rs.getString(3)) ?
Boolean.FALSE : Boolean.TRUE;
s.close();
}
}
public java.sql.ResultSet getAttributes(String catalog,
String schemaPattern,
String typeNamePattern,
String attributeNamePattern)
throws SQLException {
String colNames[] = {"TYPE_CAT", "TYPE_SCHEM",
"TYPE_NAME", "ATTR_NAME",
"DATA_TYPE", "ATTR_TYPE_NAME",
"ATTR_SIZE", "DECIMAL_DIGITS",
"NUM_PREC_RADIX", "NULLABLE",
"REMARKS", "ATTR_DEF",
"SQL_DATA_TYPE", "SQL_DATETIME_SUB",
"CHAR_OCTET_LENGTH","ORDINAL_POSITION",
"IS_NULLABLE", "SCOPE_CATALOG",
"SCOPE_SCHEMA", "SCOPE_TABLE",
"SOURCE_DATA_TYPE"};
int colTypes[] = {Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR,
Types.INTEGER, Types.VARCHAR,
Types.INTEGER, Types.INTEGER,
Types.INTEGER, Types.INTEGER,
Types.VARCHAR, Types.VARCHAR,
Types.INTEGER, Types.INTEGER,
Types.INTEGER, Types.INTEGER,
Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR,
Types.SMALLINT};
//
// Return an empty result set
//
JtdsStatement dummyStmt = (JtdsStatement) connection.createStatement();
CachedResultSet rs = new CachedResultSet(dummyStmt, colNames, colTypes);
rs.setConcurrency(ResultSet.CONCUR_READ_ONLY);
return rs;
}
/**
* Returns the database major version.
*/
public int getDatabaseMajorVersion() throws SQLException {
return connection.getDatabaseMajorVersion();
}
/**
* Returns the database minor version.
*/
public int getDatabaseMinorVersion() throws SQLException {
return connection.getDatabaseMinorVersion();
}
/**
* Returns the JDBC major version.
*/
public int getJDBCMajorVersion() throws SQLException {
return 3;
}
/**
* Returns the JDBC minor version.
*/
public int getJDBCMinorVersion() throws SQLException {
return 0;
}
public int getResultSetHoldability() throws SQLException {
return JtdsResultSet.HOLD_CURSORS_OVER_COMMIT;
}
public int getSQLStateType() throws SQLException {
return sqlStateXOpen;
}
public java.sql.ResultSet getSuperTables(String catalog,
String schemaPattern,
String tableNamePattern)
throws SQLException {
String colNames[] = {"TABLE_CAT", "TABLE_SCHEM",
"TABLE_NAME", "SUPERTABLE_NAME"};
int colTypes[] = {Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR};
//
// Return an empty result set
//
JtdsStatement dummyStmt = (JtdsStatement) connection.createStatement();
CachedResultSet rs = new CachedResultSet(dummyStmt, colNames, colTypes);
rs.setConcurrency(ResultSet.CONCUR_READ_ONLY);
return rs;
}
public java.sql.ResultSet getSuperTypes(String catalog,
String schemaPattern,
String typeNamePattern)
throws SQLException {
String colNames[] = {"TYPE_CAT", "TYPE_SCHEM",
"TYPE_NAME", "SUPERTYPE_CAT",
"SUPERTYPE_SCHEM", "SUPERTYPE_NAME"};
int colTypes[] = {Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR};
//
// Return an empty result set
//
JtdsStatement dummyStmt = (JtdsStatement) connection.createStatement();
CachedResultSet rs = new CachedResultSet(dummyStmt, colNames, colTypes);
rs.setConcurrency(ResultSet.CONCUR_READ_ONLY);
return rs;
}
/**
* Returns true if updates are made to a copy of the LOB; returns
* false if LOB updates are made directly to the database.
*
* NOTE: Since SQL Server / Sybase do not support LOB locators as Oracle does (AFAIK);
* this method always returns true.
*/
public boolean locatorsUpdateCopy() throws SQLException {
return true;
}
/**
* Returns true if getting auto-generated keys is supported after a
* statment is executed; returns false otherwise
*/
public boolean supportsGetGeneratedKeys() throws SQLException {
return true;
}
/**
* Returns true if Callable statements can return multiple result sets;
* returns false if they can only return one result set.
*/
public boolean supportsMultipleOpenResults() throws SQLException {
return true;
}
/**
* Returns true if the database supports named parameters;
* returns false if the database does not support named parameters.
*/
public boolean supportsNamedParameters() throws SQLException {
return true;
}
public boolean supportsResultSetHoldability(int param) throws SQLException {
// Not really sure about this one!
return false;
}
/**
* Returns true if savepoints are supported; returns
* false otherwise
*/
public boolean supportsSavepoints() throws SQLException {
return true;
}
/**
* Returns true if the database supports statement pooling;
* returns false otherwise.
*/
public boolean supportsStatementPooling() throws SQLException {
return true;
}
/**
* Format the supplied search pattern to transform the escape \x into [x].
*
* @param pattern the pattern to tranform
* @return the transformed pattern as a String
*/
private static String processEscapes(String pattern) {
final char escChar = '\\';
if (pattern == null || pattern.indexOf(escChar) == -1) {
return pattern;
}
int len = pattern.length();
StringBuffer buf = new StringBuffer(len + 10);
for (int i = 0; i < len; i++) {
if (pattern.charAt(i) != escChar) {
buf.append(pattern.charAt(i));
} else if (i < len - 1) {
buf.append('[');
buf.append(pattern.charAt(++i));
buf.append(']');
} else {
// Ignore final \
}
}
return buf.toString();
}
/**
* Format the supplied procedure call as a valid JDBC call escape.
*
* @param catalog the database name or null
* @param call the stored procedure call to format
* @return the formatted call escape as a String
*/
private String syscall(String catalog, String call) {
StringBuffer sql = new StringBuffer(30 + call.length());
sql.append("{call ");
if (catalog != null) {
if (tdsVersion >= Driver.TDS70) {
sql.append('[').append(catalog).append(']');
} else {
sql.append(catalog);
}
sql.append("..");
}
sql.append(call).append('}');
return sql.toString();
}
/**
* Uppercase all column names.
*
* Sybase returns column names in lowecase while the JDBC standard suggests
* they should be uppercase.
*
* @param results the result set to modify
* @throws SQLException
*/
private static void upperCaseColumnNames(JtdsResultSet results)
throws SQLException {
ResultSetMetaData rsmd = results.getMetaData();
int cnt = rsmd.getColumnCount();
for (int i = 1; i <= cnt; i++) {
String name = rsmd.getColumnLabel(i);
if (name != null && name.length() > 0) {
results.setColLabel(i, name.toUpperCase());
}
}
}
private static CachedResultSet createTypeInfoResultSet(JtdsResultSet rs, boolean useLOBs) throws SQLException {
CachedResultSet result = new CachedResultSet(rs, false);
if (result.getMetaData().getColumnCount() > TypeInfo.NUM_COLS) {
result.setColumnCount(TypeInfo.NUM_COLS);
}
result.setColLabel(3, "PRECISION");
result.setColLabel(11, "FIXED_PREC_SCALE");
upperCaseColumnNames(result);
result.setConcurrency(ResultSet.CONCUR_UPDATABLE);
result.moveToInsertRow();
for (Iterator iter = getSortedTypes(rs, useLOBs).iterator(); iter.hasNext();) {
TypeInfo ti = (TypeInfo) iter.next();
ti.update(result);
result.insertRow();
}
result.moveToCurrentRow();
result.setConcurrency(ResultSet.CONCUR_READ_ONLY);
return result;
}
private static Collection getSortedTypes(ResultSet rs, boolean useLOBs) throws SQLException {
List types = new ArrayList(40); // 40 should be enough capacity to hold all types
while (rs.next()) {
types.add(new TypeInfo(rs, useLOBs));
}
Collections.sort(types);
return types;
}
/////// JDBC4 demarcation, do NOT put any JDBC3 code below this line ///////
/* (non-Javadoc)
* @see java.sql.DatabaseMetaData#autoCommitFailureClosesAllResultSets()
*/
public boolean autoCommitFailureClosesAllResultSets() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.DatabaseMetaData#getClientInfoProperties()
*/
public ResultSet getClientInfoProperties() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.DatabaseMetaData#getFunctionColumns(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public ResultSet getFunctionColumns(String catalog, String schemaPattern,
String functionNamePattern, String columnNamePattern)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.DatabaseMetaData#getFunctions(java.lang.String, java.lang.String, java.lang.String)
*/
public ResultSet getFunctions(String catalog, String schemaPattern,
String functionNamePattern) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.DatabaseMetaData#getRowIdLifetime()
*/
public RowIdLifetime getRowIdLifetime() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.DatabaseMetaData#getSchemas(java.lang.String, java.lang.String)
*/
public ResultSet getSchemas(String catalog, String schemaPattern)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.DatabaseMetaData#supportsStoredFunctionsUsingCallSyntax()
*/
public boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#isWrapperFor(java.lang.Class)
*/
public boolean isWrapperFor(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#unwrap(java.lang.Class)
*/
public Object unwrap(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/XASupport.java 0000644 0001750 0001750 00000062424 11316672660 025660 0 ustar martin martin //jTDS JDBC Driver for Microsoft SQL Server and Sybase
//Copyright (C) 2004 The jTDS Project
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.sql.Connection;
import java.sql.SQLException;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import net.sourceforge.jtds.jdbcx.JtdsXid;
import net.sourceforge.jtds.util.Logger;
/**
* This class contains static utility methods used to implement distributed transactions.
* For SQL Server 2000 the driver can provide true distributed transactions provided that
* the external stored procedure in JtdsXA.dll is installed. For other types of server
* only an emulation is available at this stage.
*/
public class XASupport {
/**
* The Resource Manager ID allocated by jTDS
*/
private static final int XA_RMID = 1;
/**
* xa_open login string unique to jTDS.
*/
private static final String TM_ID = "TM=JTDS,RmRecoveryGuid=434CDE1A-F747-4942-9584-04937455CAB4";
//
// XA Switch constants
//
private static final int XA_OPEN = 1;
private static final int XA_CLOSE = 2;
private static final int XA_START = 3;
private static final int XA_END = 4;
private static final int XA_ROLLBACK = 5;
private static final int XA_PREPARE = 6;
private static final int XA_COMMIT = 7;
private static final int XA_RECOVER = 8;
private static final int XA_FORGET = 9;
private static final int XA_COMPLETE = 10;
/**
* Set this field to 1 to enable XA tracing.
*/
private static final int XA_TRACE = 0;
//
// ----- XA support routines -----
//
/**
* Invoke the xa_open routine on the SQL Server.
*
* @param connection the parent XAConnection object
* @return the XA connection ID allocated by xp_jtdsxa
*/
public static int xa_open(Connection connection)
throws SQLException {
ConnectionJDBC2 con = (ConnectionJDBC2)connection;
if (con.isXaEmulation()) {
//
// Emulate xa_open method
//
Logger.println("xa_open: emulating distributed transaction support");
if (con.getXid() != null) {
throw new SQLException(
Messages.get("error.xasupport.activetran", "xa_open"),
"HY000");
}
con.setXaState(XA_OPEN);
return 0;
}
//
// Execute xa_open via MSDTC
//
// Check that we are using SQL Server 2000+
//
if (((ConnectionJDBC2) connection).getServerType() != Driver.SQLSERVER
|| ((ConnectionJDBC2) connection).getTdsVersion() < Driver.TDS80) {
throw new SQLException(Messages.get("error.xasupport.nodist"), "HY000");
}
Logger.println("xa_open: Using SQL2000 MSDTC to support distributed transactions");
//
// OK Now invoke extended stored procedure to register this connection.
//
int args[] = new int[5];
args[1] = XA_OPEN;
args[2] = XA_TRACE;
args[3] = XA_RMID;
args[4] = XAResource.TMNOFLAGS;
byte[][] id;
id = ((ConnectionJDBC2) connection).sendXaPacket(args, TM_ID.getBytes());
if (args[0] != XAResource.XA_OK
|| id == null
|| id[0] == null
|| id[0].length != 4) {
throw new SQLException(
Messages.get("error.xasupport.badopen"), "HY000");
}
return (id[0][0] & 0xFF) |
((id[0][1] & 0xFF) << 8) |
((id[0][2] & 0xFF) << 16) |
((id[0][3] & 0xFF) << 24);
}
/**
* Invoke the xa_close routine on the SQL Server.
*
* @param connection JDBC Connection to be enlisted in the transaction
* @param xaConId the connection ID allocated by the server
*/
public static void xa_close(Connection connection, int xaConId)
throws SQLException {
ConnectionJDBC2 con = (ConnectionJDBC2)connection;
if (con.isXaEmulation()) {
//
// Emulate xa_close method
//
con.setXaState(0);
if (con.getXid() != null) {
con.setXid(null);
try {
con.rollback();
} catch(SQLException e) {
Logger.println("xa_close: rollback() returned " + e);
}
try {
con.setAutoCommit(true);
} catch(SQLException e) {
Logger.println("xa_close: setAutoCommit() returned " + e);
}
throw new SQLException(
Messages.get("error.xasupport.activetran", "xa_close"),
"HY000");
}
return;
}
//
// Execute xa_close via MSDTC
//
int args[] = new int[5];
args[1] = XA_CLOSE;
args[2] = xaConId;
args[3] = XA_RMID;
args[4] = XAResource.TMNOFLAGS;
((ConnectionJDBC2) connection).sendXaPacket(args, TM_ID.getBytes());
}
/**
* Invoke the xa_start routine on the SQL Server.
*
* @param connection JDBC Connection to be enlisted in the transaction
* @param xaConId the connection ID allocated by the server
* @param xid the XA Transaction ID object
* @param flags XA Flags for start command
* @exception javax.transaction.xa.XAException
* if an error condition occurs
*/
public static void xa_start(Connection connection, int xaConId, Xid xid, int flags)
throws XAException {
ConnectionJDBC2 con = (ConnectionJDBC2)connection;
if (con.isXaEmulation()) {
//
// Emulate xa_start method
//
JtdsXid lxid = new JtdsXid(xid);
if (con.getXaState() == 0) {
// Connection not opened
raiseXAException(XAException.XAER_PROTO);
}
JtdsXid tran = (JtdsXid)con.getXid();
if (tran != null) {
if (tran.equals(lxid)) {
raiseXAException(XAException.XAER_DUPID);
} else {
raiseXAException(XAException.XAER_PROTO);
}
}
if (flags != XAResource.TMNOFLAGS) {
// TMJOIN and TMRESUME cannot be supported
raiseXAException(XAException.XAER_INVAL);
}
try {
connection.setAutoCommit(false);
} catch (SQLException e) {
raiseXAException(XAException.XAER_RMERR);
}
con.setXid(lxid);
con.setXaState(XA_START);
return;
}
//
// Execute xa_start via MSDTC
//
int args[] = new int[5];
args[1] = XA_START;
args[2] = xaConId;
args[3] = XA_RMID;
args[4] = flags;
byte[][] cookie;
try {
cookie = ((ConnectionJDBC2) connection).sendXaPacket(args, toBytesXid(xid));
if (args[0] == XAResource.XA_OK && cookie != null) {
((ConnectionJDBC2) connection).enlistConnection(cookie[0]);
}
} catch (SQLException e) {
raiseXAException(e);
}
if (args[0] != XAResource.XA_OK) {
raiseXAException(args[0]);
}
}
/**
* Invoke the xa_end routine on the SQL Server.
*
* @param connection JDBC Connection enlisted in the transaction
* @param xaConId the connection ID allocated by the server
* @param xid the XA Transaction ID object
* @param flags XA Flags for start command
* @exception javax.transaction.xa.XAException
* if an error condition occurs
*/
public static void xa_end(Connection connection, int xaConId, Xid xid, int flags)
throws XAException {
ConnectionJDBC2 con = (ConnectionJDBC2)connection;
if (con.isXaEmulation()) {
//
// Emulate xa_end method
//
JtdsXid lxid = new JtdsXid(xid);
if (con.getXaState() != XA_START) {
// Connection not started
raiseXAException(XAException.XAER_PROTO);
}
JtdsXid tran = (JtdsXid)con.getXid();
if (tran == null || !tran.equals(lxid)) {
raiseXAException(XAException.XAER_NOTA);
}
if (flags != XAResource.TMSUCCESS &&
flags != XAResource.TMFAIL) {
// TMSUSPEND and TMMIGRATE cannot be supported
raiseXAException(XAException.XAER_INVAL);
}
con.setXaState(XA_END);
return;
}
//
// Execute xa_end via MSDTC
//
int args[] = new int[5];
args[1] = XA_END;
args[2] = xaConId;
args[3] = XA_RMID;
args[4] = flags;
try {
((ConnectionJDBC2) connection).sendXaPacket(args, toBytesXid(xid));
((ConnectionJDBC2) connection).enlistConnection(null);
} catch (SQLException e) {
raiseXAException(e);
}
if (args[0] != XAResource.XA_OK) {
raiseXAException(args[0]);
}
}
/**
* Invoke the xa_prepare routine on the SQL Server.
*
* @param connection JDBC Connection enlisted in the transaction.
* @param xaConId The connection ID allocated by the server.
* @param xid The XA Transaction ID object.
* @return prepare status (XA_OK or XA_RDONLY) as an int.
* @exception javax.transaction.xa.XAException
* if an error condition occurs
*/
public static int xa_prepare(Connection connection, int xaConId, Xid xid)
throws XAException {
ConnectionJDBC2 con = (ConnectionJDBC2)connection;
if (con.isXaEmulation()) {
//
// Emulate xa_prepare method
// In emulation mode this is essentially a noop as we
// are not able to offer true two phase commit.
//
JtdsXid lxid = new JtdsXid(xid);
if (con.getXaState() != XA_END) {
// Connection not ended
raiseXAException(XAException.XAER_PROTO);
}
JtdsXid tran = (JtdsXid)con.getXid();
if (tran == null || !tran.equals(lxid)) {
raiseXAException(XAException.XAER_NOTA);
}
con.setXaState(XA_PREPARE);
Logger.println("xa_prepare: Warning: Two phase commit not available in XA emulation mode.");
return XAResource.XA_OK;
}
//
// Execute xa_prepare via MSDTC
//
int args[] = new int[5];
args[1] = XA_PREPARE;
args[2] = xaConId;
args[3] = XA_RMID;
args[4] = XAResource.TMNOFLAGS;
try {
((ConnectionJDBC2) connection).sendXaPacket(args, toBytesXid(xid));
} catch (SQLException e) {
raiseXAException(e);
}
if (args[0] != XAResource.XA_OK && args[0] != XAResource.XA_RDONLY) {
raiseXAException(args[0]);
}
return args[0];
}
/**
* Invoke the xa_commit routine on the SQL Server.
*
* @param connection JDBC Connection enlisted in the transaction
* @param xaConId the connection ID allocated by the server
* @param xid the XA Transaction ID object
* @param onePhase true if single phase commit required
* @exception javax.transaction.xa.XAException
* if an error condition occurs
*/
public static void xa_commit(Connection connection, int xaConId, Xid xid, boolean onePhase)
throws XAException {
ConnectionJDBC2 con = (ConnectionJDBC2)connection;
if (con.isXaEmulation()) {
//
// Emulate xa_commit method
//
JtdsXid lxid = new JtdsXid(xid);
if (con.getXaState() != XA_END &&
con.getXaState() != XA_PREPARE) {
// Connection not ended or prepared
raiseXAException(XAException.XAER_PROTO);
}
JtdsXid tran = (JtdsXid)con.getXid();
if (tran == null || !tran.equals(lxid)) {
raiseXAException(XAException.XAER_NOTA);
}
con.setXid(null);
try {
con.commit();
} catch (SQLException e) {
raiseXAException(e);
} finally {
try {
con.setAutoCommit(true);
} catch(SQLException e) {
Logger.println("xa_close: setAutoCommit() returned " + e);
}
con.setXaState(XA_OPEN);
}
return;
}
//
// Execute xa_commit via MSDTC
//
int args[] = new int[5];
args[1] = XA_COMMIT;
args[2] = xaConId;
args[3] = XA_RMID;
args[4] = (onePhase) ? XAResource.TMONEPHASE : XAResource.TMNOFLAGS;
try {
((ConnectionJDBC2) connection).sendXaPacket(args, toBytesXid(xid));
} catch (SQLException e) {
raiseXAException(e);
}
if (args[0] != XAResource.XA_OK) {
raiseXAException(args[0]);
}
}
/**
* Invoke the xa_rollback routine on the SQL Server.
*
* @param connection JDBC Connection enlisted in the transaction
* @param xaConId the connection ID allocated by the server
* @param xid the XA Transaction ID object
* @exception javax.transaction.xa.XAException
* if an error condition occurs
*/
public static void xa_rollback(Connection connection, int xaConId, Xid xid)
throws XAException {
ConnectionJDBC2 con = (ConnectionJDBC2)connection;
if (con.isXaEmulation()) {
//
// Emulate xa_rollback method
//
JtdsXid lxid = new JtdsXid(xid);
if (con.getXaState()!= XA_END && con.getXaState() != XA_PREPARE) {
// Connection not ended
raiseXAException(XAException.XAER_PROTO);
}
JtdsXid tran = (JtdsXid)con.getXid();
if (tran == null || !tran.equals(lxid)) {
raiseXAException(XAException.XAER_NOTA);
}
con.setXid(null);
try {
con.rollback();
} catch (SQLException e) {
raiseXAException(e);
} finally {
try {
con.setAutoCommit(true);
} catch(SQLException e) {
Logger.println("xa_close: setAutoCommit() returned " + e);
}
con.setXaState(XA_OPEN);
}
return;
}
//
// Execute xa_rollback via MSDTC
//
int args[] = new int[5];
args[1] = XA_ROLLBACK;
args[2] = xaConId;
args[3] = XA_RMID;
args[4] = XAResource.TMNOFLAGS;
try {
((ConnectionJDBC2) connection).sendXaPacket(args, toBytesXid(xid));
} catch (SQLException e) {
raiseXAException(e);
}
if (args[0] != XAResource.XA_OK) {
raiseXAException(args[0]);
}
}
/**
* Invoke the xa_recover routine on the SQL Server.
*
Xid[]
* @exception javax.transaction.xa.XAException
* if an error condition occurs
*/
public static Xid[] xa_recover(Connection connection, int xaConId, int flags)
throws XAException {
ConnectionJDBC2 con = (ConnectionJDBC2)connection;
if (con.isXaEmulation()) {
//
// Emulate xa_recover method
//
// There is no state available all uncommited transactions
// will have been rolled back by the server.
if (flags != XAResource.TMSTARTRSCAN &&
flags != XAResource.TMENDRSCAN &&
flags != XAResource.TMNOFLAGS) {
raiseXAException(XAException.XAER_INVAL);
}
return new JtdsXid[0];
}
//
// Execute xa_recover via MSDTC
//
int args[] = new int[5];
args[1] = XA_RECOVER;
args[2] = xaConId;
args[3] = XA_RMID;
args[4] = XAResource.TMNOFLAGS;
Xid[] list = null;
if (flags != XAResource.TMSTARTRSCAN) {
return new JtdsXid[0];
}
try {
byte[][] buffer = ((ConnectionJDBC2) connection).sendXaPacket(args, null);
if (args[0] >= 0) {
int n = buffer.length;
list = new JtdsXid[n];
for (int i = 0; i < n; i++) {
list[i] = new JtdsXid(buffer[i], 0);
}
}
} catch (SQLException e) {
raiseXAException(e);
}
if (args[0] < 0) {
raiseXAException(args[0]);
}
if (list == null) {
list = new JtdsXid[0];
}
return list;
}
/**
* Invoke the xa_forget routine on the SQL Server.
*
* @param connection JDBC Connection enlisted in the transaction
* @param xaConId the connection ID allocated by the server
* @param xid the XA Transaction ID object
* @exception javax.transaction.xa.XAException
* if an error condition occurs
*/
public static void xa_forget(Connection connection, int xaConId, Xid xid)
throws XAException {
ConnectionJDBC2 con = (ConnectionJDBC2)connection;
if (con.isXaEmulation()) {
//
// Emulate xa_forget method
//
JtdsXid lxid = new JtdsXid(xid);
JtdsXid tran = (JtdsXid)con.getXid();
if (tran == null || !tran.equals(lxid)) {
raiseXAException(XAException.XAER_NOTA);
}
if (con.getXaState() != XA_END && con.getXaState() != XA_PREPARE) {
// Connection not ended
raiseXAException(XAException.XAER_PROTO);
}
con.setXid(null);
try {
con.rollback();
} catch (SQLException e) {
raiseXAException(e);
} finally {
try {
con.setAutoCommit(true);
} catch(SQLException e) {
Logger.println("xa_close: setAutoCommit() returned " + e);
}
con.setXaState(XA_OPEN);
}
return;
}
//
// Execute xa_forget via MSDTC
//
int args[] = new int[5];
args[1] = XA_FORGET;
args[2] = xaConId;
args[3] = XA_RMID;
args[4] = XAResource.TMNOFLAGS;
try {
((ConnectionJDBC2) connection).sendXaPacket(args, toBytesXid(xid));
} catch (SQLException e) {
raiseXAException(e);
}
if (args[0] != XAResource.XA_OK) {
raiseXAException(args[0]);
}
}
/**
* Construct and throw an XAException with an explanatory message derived from the
* SQLException and the XA error code set to XAER_RMFAIL.
*
* @param sqle The SQLException.
* @exception javax.transaction.xa.XAException
* exception derived from the code>SQLException
*/
public static void raiseXAException(SQLException sqle)
throws XAException {
XAException e = new XAException(sqle.getMessage());
e.errorCode = XAException.XAER_RMFAIL;
Logger.println("XAException: " + e.getMessage());
throw e;
}
/**
* Construct and throw an XAException with an explanatory message and the XA error code set.
*
* @param errorCode the XA Error code
* @exception javax.transaction.xa.XAException
* the constructed exception
*/
public static void raiseXAException(int errorCode)
throws XAException {
String err = "xaerunknown";
switch (errorCode) {
case XAException.XA_RBROLLBACK:
err = "xarbrollback";
break;
case XAException.XA_RBCOMMFAIL:
err = "xarbcommfail";
break;
case XAException.XA_RBDEADLOCK:
err = "xarbdeadlock";
break;
case XAException.XA_RBINTEGRITY:
err = "xarbintegrity";
break;
case XAException.XA_RBOTHER:
err = "xarbother";
break;
case XAException.XA_RBPROTO:
err = "xarbproto";
break;
case XAException.XA_RBTIMEOUT:
err = "xarbtimeout";
break;
case XAException.XA_RBTRANSIENT:
err = "xarbtransient";
break;
case XAException.XA_NOMIGRATE:
err = "xanomigrate";
break;
case XAException.XA_HEURHAZ:
err = "xaheurhaz";
break;
case XAException.XA_HEURCOM:
err = "xaheurcom";
break;
case XAException.XA_HEURRB:
err = "xaheurrb";
break;
case XAException.XA_HEURMIX:
err = "xaheurmix";
break;
case XAException.XA_RETRY:
err = "xaretry";
break;
case XAException.XA_RDONLY:
err = "xardonly";
break;
case XAException.XAER_ASYNC:
err = "xaerasync";
break;
case XAException.XAER_NOTA:
err = "xaernota";
break;
case XAException.XAER_INVAL:
err = "xaerinval";
break;
case XAException.XAER_PROTO:
err = "xaerproto";
break;
case XAException.XAER_RMERR:
err = "xaerrmerr";
break;
case XAException.XAER_RMFAIL:
err = "xaerrmfail";
break;
case XAException.XAER_DUPID:
err = "xaerdupid";
break;
case XAException.XAER_OUTSIDE:
err = "xaeroutside";
break;
}
XAException e = new XAException(Messages.get("error.xaexception." + err));
e.errorCode = errorCode;
Logger.println("XAException: " + e.getMessage());
throw e;
}
// ------------- Private methods ---------
/**
* Format an XA transaction ID into a 140 byte array.
*
* @param xid the XA transaction ID
* @return the formatted ID as a byte[]
*/
private static byte[] toBytesXid(Xid xid) {
byte[] buffer = new byte[12 +
xid.getGlobalTransactionId().length +
xid.getBranchQualifier().length];
int fmt = xid.getFormatId();
buffer[0] = (byte) fmt;
buffer[1] = (byte) (fmt >> 8);
buffer[2] = (byte) (fmt >> 16);
buffer[3] = (byte) (fmt >> 24);
buffer[4] = (byte) xid.getGlobalTransactionId().length;
buffer[8] = (byte) xid.getBranchQualifier().length;
System.arraycopy(xid.getGlobalTransactionId(), 0, buffer, 12, buffer[4]);
System.arraycopy(xid.getBranchQualifier(), 0, buffer, 12 + buffer[4], buffer[8]);
return buffer;
}
private XASupport() {
// Prevent an instance of this class being created.
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/ParameterMetaDataImpl.java 0000644 0001750 0001750 00000011341 11316672660 030106 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.sql.*;
/**
* jTDS implementation of ParameterMetaData.
*
* For Sybase it is usually possible to obtain true parameter data for prepared
* statements. For Microsoft just use information determined from the actual
* parameters if set or return some reasonable defaults otherwise.
*
* @author Brian Heineman
* @author Mike Hutchinson
* @version $Id: ParameterMetaDataImpl.java,v 1.7.2.3 2009/12/30 08:45:34 ickzon Exp $
*/
public class ParameterMetaDataImpl implements ParameterMetaData {
private final ParamInfo[] parameterList;
private final int maxPrecision;
private final boolean useLOBs;
public ParameterMetaDataImpl(ParamInfo[] parameterList, ConnectionJDBC2 connection) {
if (parameterList == null) {
parameterList = new ParamInfo[0];
}
this.parameterList = parameterList;
this.maxPrecision = connection.getMaxPrecision();
this.useLOBs = connection.getUseLOBs();
}
public int getParameterCount() throws SQLException {
return parameterList.length;
}
public int isNullable(int param) throws SQLException {
return ParameterMetaData.parameterNullableUnknown;
}
public int getParameterType(int param) throws SQLException {
if (useLOBs) {
return getParameter(param).jdbcType;
} else {
return Support.convertLOBType(getParameter(param).jdbcType);
}
}
public int getScale(int param) throws SQLException {
ParamInfo pi = getParameter(param);
return (pi.scale >= 0) ? pi.scale : 0;
}
public boolean isSigned(int param) throws SQLException {
ParamInfo pi = getParameter(param);
switch (pi.jdbcType) {
case java.sql.Types.BIGINT:
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.INTEGER:
case java.sql.Types.SMALLINT:
case java.sql.Types.REAL:
case java.sql.Types.NUMERIC:
return true;
default:
return false;
}
}
public int getPrecision(int param) throws SQLException {
ParamInfo pi = getParameter(param);
return (pi.precision >= 0) ? pi.precision : maxPrecision;
}
public String getParameterTypeName(int param) throws SQLException {
return getParameter(param).sqlType;
}
public String getParameterClassName(int param) throws SQLException {
return Support.getClassName(getParameterType(param));
}
public int getParameterMode(int param) throws SQLException {
ParamInfo pi = getParameter(param);
if (pi.isOutput) {
return pi.isSet ? parameterModeInOut : parameterModeOut;
}
return pi.isSet ? parameterModeIn : parameterModeUnknown;
}
private ParamInfo getParameter(int param) throws SQLException {
if (param < 1 || param > parameterList.length) {
throw new SQLException(
Messages.get("error.prepare.paramindex",
Integer.toString(param)), "07009");
}
return parameterList[param - 1];
}
/////// JDBC4 demarcation, do NOT put any JDBC3 code below this line ///////
/* (non-Javadoc)
* @see java.sql.Wrapper#isWrapperFor(java.lang.Class)
*/
public boolean isWrapperFor(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#unwrap(java.lang.Class)
*/
public Object unwrap(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/SavepointImpl.java 0000644 0001750 0001750 00000004463 11316672660 026544 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.sql.Savepoint;
import java.sql.SQLException;
/**
* Savepoint implementation class.
*
* @author Brian Heineman
* @version $Id: SavepointImpl.java,v 1.5 2005/04/28 14:29:27 alin_sinpalean Exp $
*/
class SavepointImpl implements Savepoint {
private final int id;
private final String name;
/**
* Constructs a savepoint with a specific identifier.
*
* @param id a savepoint identifier
*/
SavepointImpl(int id) {
this(id, null);
}
/**
* Constructs a savepoint with a specific identifier and name.
*
* @param id a savepoint identifier
* @param name the savepoint name
*/
SavepointImpl(int id, String name) {
this.id = id;
this.name = name;
}
public int getSavepointId() throws SQLException {
if (name != null) {
throw new SQLException(Messages.get("error.savepoint.named"), "HY024");
}
return id;
}
public String getSavepointName() throws SQLException {
if (name == null) {
throw new SQLException(Messages.get("error.savepoint.unnamed"), "HY024");
}
return name;
}
/**
* Returns the savepoint id. This will not throw an exception for
* named savepoints as would {@link #getSavepointId}.
*
* @return the savepoint id
*/
int getId() {
return id;
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/DefaultProperties.java 0000644 0001750 0001750 00000044143 11316672660 027412 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.io.*;
import java.util.Properties;
import java.util.Map;
import java.util.HashMap;
import net.sourceforge.jtds.ssl.Ssl;
/**
* Container for default property constants.
*
* This class also provides static utility methods for
* {@link Properties} and Settings objects.
*
* To add new properties to the jTDS driver, do the following:
* prop.foo and prop.desc.foo
* properties to Messages.properties.static final default field to {@link DefaultProperties}.Driver.createChoicesMap() and
* DriverUnitTest.test_getPropertyInfo_Choices() if the property
* has a specific set of inputs, e.g., "true" and "false", or "1" and "2".Driver.createRequiredTrueMap() and
* DriverUnitTest.test_getPropertyInfo_Required() if the property
* is required.DefaultPropertiesTestLibrary for the new
* property.appName property. */
public static final String APP_NAME = "jTDS";
/** Default batchSize property for SQL Server. */
public static final String BATCH_SIZE_SQLSERVER = "0";
/** Default batchSize property for Sybase. */
public static final String BATCH_SIZE_SYBASE = "1000";
/** Default bindAddress property. */
public static final String BIND_ADDRESS = "";
/** Default bufferMaxMemory property. */
public static final String BUFFER_MAX_MEMORY = "1024";
/** Default bufferMinPackets property. */
public static final String BUFFER_MIN_PACKETS = "8";
/** Default cacheMetaData property. */
public static final String CACHEMETA = "false";
/** Default charset property. */
public static final String CHARSET = "";
/** Default databaseName property. */
public static final String DATABASE_NAME = "";
/** Default instance property. */
public static final String INSTANCE = "";
/** Default domain property. */
public static final String DOMAIN = "";
/** Default lastUpdateCount property. */
public static final String LAST_UPDATE_COUNT = "true";
/** Default lobBufferSize property. */
public static final String LOB_BUFFER_SIZE = "32768";
/** Default loginTimeout property. */
public static final String LOGIN_TIMEOUT = "0";
/** Default macAddress property. */
public static final String MAC_ADDRESS = "000000000000";
/** Default maxStatements property. */
public static final String MAX_STATEMENTS = "500";
/** Default namedPipe property. */
public static final String NAMED_PIPE = "false";
/** Default namedPipePath property for SQL Server. */
public static final String NAMED_PIPE_PATH_SQLSERVER = "/sql/query";
/** Default namedPipePath property for Sybase. */
public static final String NAMED_PIPE_PATH_SYBASE = "/sybase/query";
/** Default packetSize property for TDS 4.2. */
public static final String PACKET_SIZE_42 = String.valueOf(TdsCore.MIN_PKT_SIZE);
/** Default packetSize property for TDS 5.0. */
public static final String PACKET_SIZE_50 = "0";
/** Default packetSize property for TDS 7.0 and TDS 8.0. */
public static final String PACKET_SIZE_70_80 = "0"; // server sets packet size
/** Default password property. */
public static final String PASSWORD = "";
/** Default portNumber property for SQL Server. */
public static final String PORT_NUMBER_SQLSERVER = "1433";
/** Default portNumber property for Sybase. */
public static final String PORT_NUMBER_SYBASE = "7100";
/** Default language property. */
public static final String LANGUAGE = "";
/** Default prepareSql property for SQL Server. */
public static final String PREPARE_SQLSERVER = String.valueOf(TdsCore.PREPARE);
/** Default prepareSql property for Sybase. */
public static final String PREPARE_SYBASE = String.valueOf(TdsCore.TEMPORARY_STORED_PROCEDURES);
/** Default progName property. */
public static final String PROG_NAME = "jTDS";
/** Default tcpNoDelay property. */
public static final String TCP_NODELAY = "true";
/** Default tmpDir property. */
public static final String BUFFER_DIR = new File(System.getProperty("java.io.tmpdir")).toString();
/** Default sendStringParametersAsUnicode property. */
public static final String USE_UNICODE = "true";
/** Default useCursors property. */
public static final String USECURSORS = "false";
/** Default useJCIFS property. */
public static final String USEJCIFS = "false";
/** Default useLOBs property. */
public static final String USELOBS = "true";
/** Default user property. */
public static final String USER = "";
/** Default wsid property. */
public static final String WSID = "";
/** Default XaEmulation property. */
public static final String XAEMULATION = "true";
/** Default logfile property. */
public static final String LOGFILE = "";
/** Default sockeTimeout property. */
public static final String SOCKET_TIMEOUT = "0";
/** Default socketKeepAlive property. */
public static final String SOCKET_KEEPALIVE = "false";
/** Default processId property. */
public static final String PROCESS_ID = "123";
/** Default serverType property for SQL Server. */
public static final String SERVER_TYPE_SQLSERVER = "sqlserver";
/** Default serverType property for Sybase. */
public static final String SERVER_TYPE_SYBASE = "sybase";
/** Default tds property for TDS 4.2. */
public static final String TDS_VERSION_42 = "4.2";
/** Default tds property for TDS 5.0. */
public static final String TDS_VERSION_50 = "5.0";
/** Default tds property for TDS 7.0. */
public static final String TDS_VERSION_70 = "7.0";
/** Default tds property for TDS 8.0. */
public static final String TDS_VERSION_80 = "8.0";
/** Default ssl property. */
public static final String SSL = Ssl.SSL_OFF;
/** Default TDS version based on server type */
private static final HashMap tdsDefaults;
/** Default port number based on server type */
private static final HashMap portNumberDefaults;
/** Default packet size based on TDS version */
private static final HashMap packetSizeDefaults;
/** Default max batch size based on server type */
private static final HashMap batchSizeDefaults;
/** Default prepare SQL mode based on server type */
private static final HashMap prepareSQLDefaults;
static {
tdsDefaults = new HashMap(2);
tdsDefaults.put(String.valueOf(Driver.SQLSERVER), TDS_VERSION_80);
tdsDefaults.put(String.valueOf(Driver.SYBASE), TDS_VERSION_50);
portNumberDefaults = new HashMap(2);
portNumberDefaults.put(String.valueOf(Driver.SQLSERVER), PORT_NUMBER_SQLSERVER);
portNumberDefaults.put(String.valueOf(Driver.SYBASE), PORT_NUMBER_SYBASE);
packetSizeDefaults = new HashMap(4);
packetSizeDefaults.put(TDS_VERSION_42, PACKET_SIZE_42);
packetSizeDefaults.put(TDS_VERSION_50, PACKET_SIZE_50);
packetSizeDefaults.put(TDS_VERSION_70, PACKET_SIZE_70_80);
packetSizeDefaults.put(TDS_VERSION_80, PACKET_SIZE_70_80);
batchSizeDefaults = new HashMap(2);
batchSizeDefaults.put(String.valueOf(Driver.SQLSERVER),
BATCH_SIZE_SQLSERVER);
batchSizeDefaults.put(String.valueOf(Driver.SYBASE),
BATCH_SIZE_SYBASE);
prepareSQLDefaults = new HashMap(2);
prepareSQLDefaults.put(String.valueOf(Driver.SQLSERVER),
PREPARE_SQLSERVER);
prepareSQLDefaults.put(String.valueOf(Driver.SYBASE),
PREPARE_SYBASE);
}
/**
* Add default properties to the props properties object.
*
* @param props The properties object.
* @return The updated props object, or null
* if the serverType property is not set.
*/
public static Properties addDefaultProperties(final Properties props) {
final String serverType = props.getProperty(Messages.get(Driver.SERVERTYPE));
if (serverType == null) {
return null;
}
addDefaultPropertyIfNotSet(props, Driver.TDS, Driver.SERVERTYPE, tdsDefaults);
addDefaultPropertyIfNotSet(props, Driver.PORTNUMBER, Driver.SERVERTYPE, portNumberDefaults);
addDefaultPropertyIfNotSet(props, Driver.USER, USER);
addDefaultPropertyIfNotSet(props, Driver.PASSWORD, PASSWORD);
addDefaultPropertyIfNotSet(props, Driver.DATABASENAME, DATABASE_NAME);
addDefaultPropertyIfNotSet(props, Driver.INSTANCE, INSTANCE);
addDefaultPropertyIfNotSet(props, Driver.DOMAIN, DOMAIN);
addDefaultPropertyIfNotSet(props, Driver.APPNAME, APP_NAME);
addDefaultPropertyIfNotSet(props, Driver.PROGNAME, PROG_NAME);
addDefaultPropertyIfNotSet(props, Driver.WSID, WSID);
addDefaultPropertyIfNotSet(props, Driver.BATCHSIZE, Driver.SERVERTYPE, batchSizeDefaults);
addDefaultPropertyIfNotSet(props, Driver.LASTUPDATECOUNT, LAST_UPDATE_COUNT);
addDefaultPropertyIfNotSet(props, Driver.LOBBUFFER, LOB_BUFFER_SIZE);
addDefaultPropertyIfNotSet(props, Driver.LOGINTIMEOUT, LOGIN_TIMEOUT);
addDefaultPropertyIfNotSet(props, Driver.SOTIMEOUT, SOCKET_TIMEOUT);
addDefaultPropertyIfNotSet(props, Driver.SOKEEPALIVE, SOCKET_KEEPALIVE);
addDefaultPropertyIfNotSet(props, Driver.PROCESSID, PROCESS_ID);
addDefaultPropertyIfNotSet(props, Driver.MACADDRESS, MAC_ADDRESS);
addDefaultPropertyIfNotSet(props, Driver.MAXSTATEMENTS, MAX_STATEMENTS);
addDefaultPropertyIfNotSet(props, Driver.NAMEDPIPE, NAMED_PIPE);
addDefaultPropertyIfNotSet(props, Driver.PACKETSIZE, Driver.TDS, packetSizeDefaults);
addDefaultPropertyIfNotSet(props, Driver.CACHEMETA, CACHEMETA);
addDefaultPropertyIfNotSet(props, Driver.CHARSET, CHARSET);
addDefaultPropertyIfNotSet(props, Driver.LANGUAGE, LANGUAGE);
addDefaultPropertyIfNotSet(props, Driver.PREPARESQL, Driver.SERVERTYPE, prepareSQLDefaults);
addDefaultPropertyIfNotSet(props, Driver.SENDSTRINGPARAMETERSASUNICODE, USE_UNICODE);
addDefaultPropertyIfNotSet(props, Driver.TCPNODELAY, TCP_NODELAY);
addDefaultPropertyIfNotSet(props, Driver.XAEMULATION, XAEMULATION);
addDefaultPropertyIfNotSet(props, Driver.LOGFILE, LOGFILE);
addDefaultPropertyIfNotSet(props, Driver.SSL, SSL);
addDefaultPropertyIfNotSet(props, Driver.USECURSORS, USECURSORS);
addDefaultPropertyIfNotSet(props, Driver.BUFFERMAXMEMORY, BUFFER_MAX_MEMORY);
addDefaultPropertyIfNotSet(props, Driver.BUFFERMINPACKETS, BUFFER_MIN_PACKETS);
addDefaultPropertyIfNotSet(props, Driver.USELOBS, USELOBS);
addDefaultPropertyIfNotSet(props, Driver.BINDADDRESS, BIND_ADDRESS);
addDefaultPropertyIfNotSet(props, Driver.USEJCIFS, USEJCIFS);
addDefaultPropertyIfNotSet(props, Driver.BUFFERDIR, BUFFER_DIR);
return props;
}
/**
* Sets a default property if the property is not already set.
*
* @param props The properties object.
* @param key The message key to set.
* @param defaultValue The default value to set.
*/
private static void addDefaultPropertyIfNotSet(
final Properties props, final String key, final String defaultValue) {
final String messageKey = Messages.get(key);
if (props.getProperty(messageKey) == null) {
props.setProperty(messageKey, defaultValue);
}
}
/**
* Sets a default property if the property is not already set, using
* the defaultKey and the defaults map to
* determine the correct value.
*
* @param props The properties object.
* @param key The message key to set.
* @param defaultKey The key whose value determines which default
* value to set from defaults.
* @param defaults The mapping of defaultKey values to
* the correct key value to set.
*/
private static void addDefaultPropertyIfNotSet(
final Properties props, final String key, final String defaultKey, final Map defaults) {
final String defaultKeyValue = props.getProperty(Messages.get(defaultKey));
if (defaultKeyValue == null) {
return;
}
final String messageKey = Messages.get(key);
if (props.getProperty(messageKey) == null) {
final Object defaultValue = defaults.get(defaultKeyValue);
if (defaultValue != null) {
props.setProperty(messageKey, String.valueOf(defaultValue));
}
}
}
/**
* Returns the default path for the named pipe for a given serverType.
*
* @param serverType {@link Driver#SQLSERVER} or {@link Driver#SYBASE} or 0 (default)
* @return default named pipe path
* @throws IllegalArgumentException if an invalid serverType is given
*/
public static String getNamedPipePath(int serverType) {
if (serverType == 0 || serverType == Driver.SQLSERVER) {
return NAMED_PIPE_PATH_SQLSERVER;
}
else if (serverType == Driver.SYBASE) {
return NAMED_PIPE_PATH_SYBASE;
}
throw new IllegalArgumentException("Unknown serverType: " + serverType);
}
/**
* Converts an integer server type to its string representation.
*
* @param serverType the server type as an int
* @return the server type as a string if known, or null if unknown
*/
public static String getServerType(int serverType) {
if (serverType == Driver.SQLSERVER) {
return SERVER_TYPE_SQLSERVER;
} else if (serverType == Driver.SYBASE) {
return SERVER_TYPE_SYBASE;
}
return null;
}
/**
* Converts a string server type to its integer representation.
*
* @param serverType the server type as a string
* @return the server type as an integer if known or null if
* unknown
*/
public static Integer getServerType(String serverType) {
if (DefaultProperties.SERVER_TYPE_SQLSERVER.equals(serverType)) {
return new Integer(Driver.SQLSERVER);
} else if (DefaultProperties.SERVER_TYPE_SYBASE.equals(serverType)) {
return new Integer(Driver.SYBASE);
}
return null;
}
/**
* Same as {@link #getServerType(int)}, only it returns the default server
* type ("sqlserver") if serverType is 0.
*
* @param serverType integer server type or 0 for default
* @return the server type as a string if known or "sqlserver"
* if unknown
*/
public static String getServerTypeWithDefault(int serverType) {
if (serverType == 0) {
return DefaultProperties.SERVER_TYPE_SQLSERVER;
} else if (serverType == Driver.SQLSERVER
|| serverType == Driver.SYBASE) {
return getServerType(serverType);
} else {
throw new IllegalArgumentException(
"Only 0, 1 and 2 accepted for serverType");
}
}
/**
* Converts a string TDS version to its integer representation.
*
* @param tdsVersion The TDS version as a string.
* @return The TDS version as an integer if known, or null if unknown.
*/
public static Integer getTdsVersion(String tdsVersion) {
if (DefaultProperties.TDS_VERSION_42.equals(tdsVersion)) {
return new Integer(Driver.TDS42);
} else if (DefaultProperties.TDS_VERSION_50.equals(tdsVersion)) {
return new Integer(Driver.TDS50);
} else if (DefaultProperties.TDS_VERSION_70.equals(tdsVersion)) {
return new Integer(Driver.TDS70);
} else if (DefaultProperties.TDS_VERSION_80.equals(tdsVersion)) {
return new Integer(Driver.TDS80);
}
return null;
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/TdsData.java 0000644 0001750 0001750 00000327311 11316672660 025276 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.io.*;
import java.math.BigInteger;
import java.math.BigDecimal;
import java.sql.SQLException;
import net.sourceforge.jtds.util.BlobBuffer;
/**
* Implement TDS data types and related I/O logic.
*
* Implementation notes:
*
*
*
Special values as follows: *
If this is -1 precision must be calculated from buffer size * eg for varchar fields. */ public final int precision; /** * The display size of the type. *
-1 If the display size must be calculated from the buffer size.
*/
public final int displaySize;
/** true if type is a signed numeric. */
public final boolean isSigned;
/** true if type requires TDS80 collation. */
public final boolean isCollation;
/** The java.sql.Types constant for this data type. */
public final int jdbcType;
/**
* Construct a new TDS data type descriptor.
*
* @param sqlType SQL type name.
* @param size Byte size for this type or < 0 for variable length types.
* @param precision Decimal precision or -1
* @param displaySize Printout size for this type or special values -1,-2.
* @param isSigned True if signed numeric type.
* @param isCollation True if type has TDS 8 collation information.
* @param jdbcType The java.sql.Type constant for this type.
*/
TypeInfo(String sqlType, int size, int precision, int displaySize,
boolean isSigned, boolean isCollation, int jdbcType) {
this.sqlType = sqlType;
this.size = size;
this.precision = precision;
this.displaySize = displaySize;
this.isSigned = isSigned;
this.isCollation = isCollation;
this.jdbcType = jdbcType;
}
}
/*
* Constants for TDS data types
*/
private static final int SYBCHAR = 47; // 0x2F
private static final int SYBVARCHAR = 39; // 0x27
private static final int SYBINTN = 38; // 0x26
private static final int SYBINT1 = 48; // 0x30
private static final int SYBDATE = 49; // 0x31 Sybase 12
private static final int SYBTIME = 51; // 0x33 Sybase 12
private static final int SYBINT2 = 52; // 0x34
private static final int SYBINT4 = 56; // 0x38
private static final int SYBINT8 = 127;// 0x7F
private static final int SYBFLT8 = 62; // 0x3E
private static final int SYBDATETIME = 61; // 0x3D
private static final int SYBBIT = 50; // 0x32
private static final int SYBTEXT = 35; // 0x23
private static final int SYBNTEXT = 99; // 0x63
private static final int SYBIMAGE = 34; // 0x22
private static final int SYBMONEY4 = 122;// 0x7A
private static final int SYBMONEY = 60; // 0x3C
private static final int SYBDATETIME4 = 58; // 0x3A
private static final int SYBREAL = 59; // 0x3B
private static final int SYBBINARY = 45; // 0x2D
private static final int SYBVOID = 31; // 0x1F
private static final int SYBVARBINARY = 37; // 0x25
private static final int SYBNVARCHAR = 103;// 0x67
private static final int SYBBITN = 104;// 0x68
private static final int SYBNUMERIC = 108;// 0x6C
private static final int SYBDECIMAL = 106;// 0x6A
private static final int SYBFLTN = 109;// 0x6D
private static final int SYBMONEYN = 110;// 0x6E
private static final int SYBDATETIMN = 111;// 0x6F
private static final int SYBDATEN = 123;// 0x7B SYBASE 12
private static final int SYBTIMEN = 147;// 0x93 SYBASE 12
private static final int XSYBCHAR = 175;// 0xAF
private static final int XSYBVARCHAR = 167;// 0xA7
private static final int XSYBNVARCHAR = 231;// 0xE7
private static final int XSYBNCHAR = 239;// 0xEF
private static final int XSYBVARBINARY = 165;// 0xA5
private static final int XSYBBINARY = 173;// 0xAD
private static final int SYBUNITEXT = 174;// 0xAE SYBASE 15
private static final int SYBLONGBINARY = 225;// 0xE1 SYBASE 12
private static final int SYBSINT1 = 64; // 0x40
private static final int SYBUINT2 = 65; // 0x41 SYBASE 15
private static final int SYBUINT4 = 66; // 0x42 SYBASE 15
private static final int SYBUINT8 = 67; // 0x43 SYBASE 15
private static final int SYBUINTN = 68; // 0x44 SYBASE 15
private static final int SYBUNIQUE = 36; // 0x24
private static final int SYBVARIANT = 98; // 0x62
private static final int SYBSINT8 = 191;// 0xBF SYBASE 15
/*
* Special case for Sybase 12.5+
* This long data type is used to send text and image
* data as statement parameters as a replacement for
* writetext.
* As far as I can tell this data type is only sent not
* received.
*/
static final int SYBLONGDATA = 36; // 0x24 SYBASE 12
/*
* Constants for Sybase User Defined data types used to
* qualify the new longchar and longbinary types.
*/
// Common to Sybase and SQL Server
private static final int UDT_CHAR = 1; // 0x01
private static final int UDT_VARCHAR = 2; // 0x02
private static final int UDT_BINARY = 3; // 0x03
private static final int UDT_VARBINARY = 4; // 0x04
private static final int UDT_SYSNAME = 18; // 0x12
// Sybase only
private static final int UDT_NCHAR = 24; // 0x18
private static final int UDT_NVARCHAR = 25; // 0x19
private static final int UDT_UNICHAR = 34; // 0x22
private static final int UDT_UNIVARCHAR = 35; // 0x23
private static final int UDT_UNITEXT = 36; // 0x24
private static final int UDT_LONGSYSNAME = 42; // 0x2A
private static final int UDT_TIMESTAMP = 80; // 0x50
// SQL Server 7+
private static final int UDT_NEWSYSNAME =256; // 0x100
/*
* Constants for variable length data types
*/
private static final int VAR_MAX = 255;
private static final int SYB_LONGVAR_MAX = 16384;
private static final int MS_LONGVAR_MAX = 8000;
private static final int SYB_CHUNK_SIZE = 8192;
/**
* Array of TDS data type descriptors.
*/
private final static TypeInfo types[] = new TypeInfo[256];
/**
* Static block to initialise TDS data type descriptors.
*/
static {// SQL Type Size Prec DS signed TDS8 Col java Type
types[SYBCHAR] = new TypeInfo("char", -1, -1, 1, false, false, java.sql.Types.CHAR);
types[SYBVARCHAR] = new TypeInfo("varchar", -1, -1, 1, false, false, java.sql.Types.VARCHAR);
types[SYBINTN] = new TypeInfo("int", -1, 10, 11, true, false, java.sql.Types.INTEGER);
types[SYBINT1] = new TypeInfo("tinyint", 1, 3, 4, false, false, java.sql.Types.TINYINT);
types[SYBINT2] = new TypeInfo("smallint", 2, 5, 6, true, false, java.sql.Types.SMALLINT);
types[SYBINT4] = new TypeInfo("int", 4, 10, 11, true, false, java.sql.Types.INTEGER);
types[SYBINT8] = new TypeInfo("bigint", 8, 19, 20, true, false, java.sql.Types.BIGINT);
types[SYBFLT8] = new TypeInfo("float", 8, 15, 24, true, false, java.sql.Types.DOUBLE);
types[SYBDATETIME] = new TypeInfo("datetime", 8, 23, 23, false, false, java.sql.Types.TIMESTAMP);
types[SYBBIT] = new TypeInfo("bit", 1, 1, 1, false, false, java.sql.Types.BIT);
types[SYBTEXT] = new TypeInfo("text", -4, -1, -1, false, true, java.sql.Types.CLOB);
types[SYBNTEXT] = new TypeInfo("ntext", -4, -1, -1, false, true, java.sql.Types.CLOB);
types[SYBUNITEXT] = new TypeInfo("unitext", -4, -1, -1, false, true, java.sql.Types.CLOB);
types[SYBIMAGE] = new TypeInfo("image", -4, -1, -1, false, false, java.sql.Types.BLOB);
types[SYBMONEY4] = new TypeInfo("smallmoney", 4, 10, 12, true, false, java.sql.Types.DECIMAL);
types[SYBMONEY] = new TypeInfo("money", 8, 19, 21, true, false, java.sql.Types.DECIMAL);
types[SYBDATETIME4] = new TypeInfo("smalldatetime", 4, 16, 19, false, false, java.sql.Types.TIMESTAMP);
types[SYBREAL] = new TypeInfo("real", 4, 7, 14, true, false, java.sql.Types.REAL);
types[SYBBINARY] = new TypeInfo("binary", -1, -1, 2, false, false, java.sql.Types.BINARY);
types[SYBVOID] = new TypeInfo("void", -1, 1, 1, false, false, 0);
types[SYBVARBINARY] = new TypeInfo("varbinary", -1, -1, -1, false, false, java.sql.Types.VARBINARY);
types[SYBNVARCHAR] = new TypeInfo("nvarchar", -1, -1, -1, false, false, java.sql.Types.VARCHAR);
types[SYBBITN] = new TypeInfo("bit", -1, 1, 1, false, false, java.sql.Types.BIT);
types[SYBNUMERIC] = new TypeInfo("numeric", -1, -1, -1, true, false, java.sql.Types.NUMERIC);
types[SYBDECIMAL] = new TypeInfo("decimal", -1, -1, -1, true, false, java.sql.Types.DECIMAL);
types[SYBFLTN] = new TypeInfo("float", -1, 15, 24, true, false, java.sql.Types.DOUBLE);
types[SYBMONEYN] = new TypeInfo("money", -1, 19, 21, true, false, java.sql.Types.DECIMAL);
types[SYBDATETIMN] = new TypeInfo("datetime", -1, 23, 23, false, false, java.sql.Types.TIMESTAMP);
types[SYBDATE] = new TypeInfo("date", 4, 10, 10, false, false, java.sql.Types.DATE);
types[SYBTIME] = new TypeInfo("time", 4, 8, 8, false, false, java.sql.Types.TIME);
types[SYBDATEN] = new TypeInfo("date", -1, 10, 10, false, false, java.sql.Types.DATE);
types[SYBTIMEN] = new TypeInfo("time", -1, 8, 8, false, false, java.sql.Types.TIME);
types[XSYBCHAR] = new TypeInfo("char", -2, -1, -1, false, true, java.sql.Types.CHAR);
types[XSYBVARCHAR] = new TypeInfo("varchar", -2, -1, -1, false, true, java.sql.Types.VARCHAR);
types[XSYBNVARCHAR] = new TypeInfo("nvarchar", -2, -1, -1, false, true, java.sql.Types.VARCHAR);
types[XSYBNCHAR] = new TypeInfo("nchar", -2, -1, -1, false, true, java.sql.Types.CHAR);
types[XSYBVARBINARY]= new TypeInfo("varbinary", -2, -1, -1, false, false, java.sql.Types.VARBINARY);
types[XSYBBINARY] = new TypeInfo("binary", -2, -1, -1, false, false, java.sql.Types.BINARY);
types[SYBLONGBINARY]= new TypeInfo("varbinary", -5, -1, 2, false, false, java.sql.Types.BINARY);
types[SYBSINT1] = new TypeInfo("tinyint", 1, 2, 3, false, false, java.sql.Types.TINYINT);
types[SYBUINT2] = new TypeInfo("unsigned smallint", 2, 5, 6, false, false, java.sql.Types.INTEGER);
types[SYBUINT4] = new TypeInfo("unsigned int", 4, 10, 11, false, false, java.sql.Types.BIGINT);
types[SYBUINT8] = new TypeInfo("unsigned bigint",8, 20, 20, false, false, java.sql.Types.DECIMAL);
types[SYBUINTN] = new TypeInfo("unsigned int", -1, 10, 11, true, false, java.sql.Types.BIGINT);
types[SYBUNIQUE] = new TypeInfo("uniqueidentifier",-1,36,36, false, false, java.sql.Types.CHAR);
types[SYBVARIANT] = new TypeInfo("sql_variant", -5, 0, 8000, false, false, java.sql.Types.VARCHAR);
types[SYBSINT8] = new TypeInfo("bigint", 8, 19, 20, true, false, java.sql.Types.BIGINT);
}
/** Default Decimal Scale. */
static final int DEFAULT_SCALE = 10;
/** Default precision for SQL Server 6.5 and 7. */
static final int DEFAULT_PRECISION_28 = 28;
/** Default precision for Sybase and SQL Server 2000 and newer. */
static final int DEFAULT_PRECISION_38 = 38;
/**
* TDS 8 supplies collation information for character data types.
*
* @param in the server response stream
* @param ci the column descriptor
* @return the number of bytes read from the stream as an int
*/
static int getCollation(ResponseStream in, ColInfo ci) throws IOException {
if (TdsData.isCollation(ci)) {
// Read TDS8 collation info
ci.collation = new byte[5];
in.read(ci.collation);
return 5;
}
return 0;
}
/**
* Set the charsetInfo field of ci according to
* the value of its collation field.
*
* The Connection is used to find out whether a specific
* charset was requested. In this case, the column charset will be ignored.
*
* @param ci the ColInfo instance to update
* @param connection a Connection instance to check whether it
* has a fixed charset or not
* @throws SQLException if a CharsetInfo is not found for this
* particular column collation
*/
static void setColumnCharset(ColInfo ci, ConnectionJDBC2 connection)
throws SQLException {
if (connection.isCharsetSpecified()) {
// If a charset was requested on connection creation, ignore the
// column collation and use default
ci.charsetInfo = connection.getCharsetInfo();
} else if (ci.collation != null) {
// TDS version will be 8.0 or higher in this case and connection
// collation will be non-null
byte[] collation = ci.collation;
byte[] defaultCollation = connection.getCollation();
int i;
for (i = 0; i < 5; ++i) {
if (collation[i] != defaultCollation[i]) {
break;
}
}
if (i == 5) {
ci.charsetInfo = connection.getCharsetInfo();
} else {
ci.charsetInfo = CharsetInfo.getCharset(collation);
}
}
}
/**
* Read the TDS datastream and populate the ColInfo parameter with
* data type and related information.
*
The type infomation conforms to one of the following formats: *
The data size is either implicit in the type for example
* fixed size integers, or a count field precedes the actual data.
* The size of the count field varies with the data type.
*
* @param connection an object reference to the caller of this method;
* must be a Connection, Statement or
* ResultSet
* @param in The server ResponseStream.
* @param ci The ColInfo column descriptor object.
* @return The data item Object or null.
* @throws IOException
* @throws ProtocolException
*/
static Object readData(ConnectionJDBC2 connection, ResponseStream in, ColInfo ci)
throws IOException, ProtocolException {
int len;
switch (ci.tdsType) {
case SYBINTN:
switch (in.read()) {
case 1:
return new Integer(in.read() & 0xFF);
case 2:
return new Integer(in.readShort());
case 4:
return new Integer(in.readInt());
case 8:
return new Long(in.readLong());
}
break;
// Sybase ASE 15+ supports unsigned null smallint, int and bigint
case SYBUINTN:
switch (in.read()) {
case 1:
return new Integer(in.read() & 0xFF);
case 2:
return new Integer((int)in.readShort() & 0xFFFF);
case 4:
return new Long((long)in.readInt() & 0xFFFFFFFFL );
case 8:
return in.readUnsignedLong();
}
break;
case SYBINT1:
return new Integer(in.read() & 0xFF);
case SYBINT2:
return new Integer(in.readShort());
case SYBINT4:
return new Integer(in.readInt());
// SQL Server bigint
case SYBINT8:
return new Long(in.readLong());
// Sybase ASE 15+ bigint
case SYBSINT8:
return new Long(in.readLong());
// Sybase ASE 15+ unsigned smallint
case SYBUINT2:
return new Integer((int)in.readShort() & 0xFFFF);
// Sybase ASE 15+ unsigned int
case SYBUINT4:
return new Long((long)in.readInt() & 0xFFFFFFFFL);
// Sybase ASE 15+ unsigned bigint
case SYBUINT8:
return in.readUnsignedLong();
case SYBIMAGE:
len = in.read();
if (len > 0) {
in.skip(24); // Skip textptr and timestamp
int dataLen = in.readInt();
BlobImpl blob;
if (dataLen == 0 && in.getTdsVersion() <= Driver.TDS50) {
// Length of zero may indicate an initialized image
// column that has been updated to null.
break;
}
if (dataLen <= connection.getLobBuffer()) {
//
// OK Small enough to load into memory
//
byte[] data = new byte[dataLen];
in.read(data);
blob = new BlobImpl(connection, data);
} else {
// Too big, need to write straight to disk
try {
blob = new BlobImpl(connection);
OutputStream out = blob.setBinaryStream(1);
byte[] buffer = new byte[1024];
int result;
while ((result = in.read(buffer, 0,
Math.min(dataLen, buffer.length)))
!= -1 && dataLen != 0) {
out.write(buffer, 0, result);
dataLen -= result;
}
out.close();
} catch (SQLException e) {
// Transform setBinaryStream SQLException
throw new IOException(e.getMessage());
}
}
return blob;
}
break;
case SYBTEXT:
len = in.read();
if (len > 0) {
String charset;
if (ci.charsetInfo != null) {
charset = ci.charsetInfo.getCharset();
} else {
charset = connection.getCharset();
}
in.skip(24); // Skip textptr and timestamp
int dataLen = in.readInt();
if (dataLen == 0 && in.getTdsVersion() <= Driver.TDS50) {
// Length of zero may indicate an initialized text
// column that has been updated to null.
break;
}
ClobImpl clob = new ClobImpl(connection);
BlobBuffer blobBuffer = clob.getBlobBuffer();
if (dataLen <= connection.getLobBuffer()) {
//
// OK Small enough to load into memory
//
BufferedReader rdr =
new BufferedReader(
new InputStreamReader(in.getInputStream(dataLen),
charset),
1024);
byte[] data = new byte[dataLen * 2];
int p = 0;
int c;
while ((c = rdr.read()) >= 0) {
data[p++] = (byte)c;
data[p++] = (byte)(c >> 8);
}
rdr.close();
blobBuffer.setBuffer(data, false);
if (p == 2 && data[0] == 0x20 && data[1] == 0
&& in.getTdsVersion() < Driver.TDS70) {
// Single space with Sybase equates to empty string
p = 0;
}
// Explicitly set length as multi byte character sets
// may not fill array completely.
blobBuffer.setLength(p);
} else {
// Too big, need to write straight to disk
BufferedReader rdr =
new BufferedReader(
new InputStreamReader(in.getInputStream(dataLen),
charset),
1024);
try {
OutputStream out = blobBuffer.setBinaryStream(1, false);
int c;
while ((c = rdr.read()) >= 0) {
out.write(c);
out.write(c >> 8);
}
out.close();
rdr.close();
} catch (SQLException e) {
// Turn back into an IOException
throw new IOException(e.getMessage());
}
}
return clob;
}
break;
case SYBUNITEXT: // ASE 15+ unicode text type
case SYBNTEXT:
len = in.read();
if (len > 0) {
in.skip(24); // Skip textptr and timestamp
int dataLen = in.readInt();
if (dataLen == 0 && in.getTdsVersion() <= Driver.TDS50) {
// Length of zero may indicate an initialized unitext
// column that has been updated to null.
break;
}
ClobImpl clob = new ClobImpl(connection);
BlobBuffer blobBuffer = clob.getBlobBuffer();
if (dataLen <= connection.getLobBuffer()) {
//
// OK Small enough to load into memory
//
byte[] data = new byte[dataLen];
in.read(data);
blobBuffer.setBuffer(data, false);
if (dataLen == 2 && data[0] == 0x20 && data[1] == 0
&& in.getTdsVersion() == Driver.TDS50) {
// Single space with Sybase equates to empty string
dataLen = 0;
}
// Explicitly set length as multi byte character sets
// may not fill array completely.
blobBuffer.setLength(dataLen);
} else {
// Too big, need to write straight to disk
try {
OutputStream out = blobBuffer.setBinaryStream(1, false);
byte[] buffer = new byte[1024];
int result;
while ((result = in.read(buffer, 0,
Math.min(dataLen, buffer.length)))
!= -1 && dataLen != 0) {
out.write(buffer, 0, result);
dataLen -= result;
}
out.close();
} catch (SQLException e) {
// Transform setBinaryStream SQLException
throw new IOException(e.getMessage());
}
}
return clob;
}
break;
case SYBCHAR:
case SYBVARCHAR:
len = in.read();
if (len > 0) {
String value = in.readNonUnicodeString(len,
ci.charsetInfo == null ? connection.getCharsetInfo() : ci.charsetInfo);
if (len == 1 && ci.tdsType == SYBVARCHAR &&
in.getTdsVersion() < Driver.TDS70) {
// In TDS 4/5 zero length varchars are stored as a
// single space to distinguish them from nulls.
return (" ".equals(value)) ? "" : value;
}
return value;
}
break;
case SYBNVARCHAR:
len = in.read();
if (len > 0) {
return in.readUnicodeString(len / 2);
}
break;
case XSYBCHAR:
case XSYBVARCHAR:
if (in.getTdsVersion() == Driver.TDS50) {
// This is a Sybase wide table String
len = in.readInt();
if (len > 0) {
String tmp = in.readNonUnicodeString(len);
if (" ".equals(tmp) && !"char".equals(ci.sqlType)) {
tmp = "";
}
return tmp;
}
} else {
// This is a TDS 7+ long string
len = in.readShort();
if (len != -1) {
return in.readNonUnicodeString(len,
ci.charsetInfo == null ? connection.getCharsetInfo() : ci.charsetInfo);
}
}
break;
case XSYBNCHAR:
case XSYBNVARCHAR:
len = in.readShort();
if (len != -1) {
return in.readUnicodeString(len / 2);
}
break;
case SYBVARBINARY:
case SYBBINARY:
len = in.read();
if (len > 0) {
byte[] bytes = new byte[len];
in.read(bytes);
return bytes;
}
break;
case XSYBVARBINARY:
case XSYBBINARY:
len = in.readShort();
if (len != -1) {
byte[] bytes = new byte[len];
in.read(bytes);
return bytes;
}
break;
case SYBLONGBINARY:
len = in.readInt();
if (len != 0) {
if ("unichar".equals(ci.sqlType) ||
"univarchar".equals(ci.sqlType)) {
char[] buf = new char[len / 2];
in.read(buf);
if ((len & 1) != 0) {
// Bad length should be divisible by 2
in.skip(1); // Deal with it anyway.
}
if (len == 2 && buf[0] == ' ') {
return "";
} else {
return new String(buf);
}
} else {
byte[] bytes = new byte[len];
in.read(bytes);
return bytes;
}
}
break;
case SYBMONEY4:
case SYBMONEY:
case SYBMONEYN:
return getMoneyValue(in, ci.tdsType);
case SYBDATETIME4:
case SYBDATETIMN:
case SYBDATETIME:
return getDatetimeValue(in, ci.tdsType);
case SYBDATEN:
case SYBDATE:
len = (ci.tdsType == SYBDATEN)? in.read(): 4;
if (len == 4) {
return new DateTime(in.readInt(), DateTime.TIME_NOT_USED);
} else {
// Invalid length or 0 for null
in.skip(len);
}
break;
case SYBTIMEN:
case SYBTIME:
len = (ci.tdsType == SYBTIMEN)? in.read(): 4;
if (len == 4) {
return new DateTime(DateTime.DATE_NOT_USED, in.readInt());
} else {
// Invalid length or 0 for null
in.skip(len);
}
break;
case SYBBIT:
return (in.read() != 0) ? Boolean.TRUE : Boolean.FALSE;
case SYBBITN:
len = in.read();
if (len > 0) {
return (in.read() != 0) ? Boolean.TRUE : Boolean.FALSE;
}
break;
case SYBREAL:
return new Float(Float.intBitsToFloat(in.readInt()));
case SYBFLT8:
return new Double(Double.longBitsToDouble(in.readLong()));
case SYBFLTN:
len = in.read();
if (len == 4) {
return new Float(Float.intBitsToFloat(in.readInt()));
} else if (len == 8) {
return new Double(Double.longBitsToDouble(in.readLong()));
}
break;
case SYBUNIQUE:
len = in.read();
if (len > 0) {
byte[] bytes = new byte[len];
in.read(bytes);
return new UniqueIdentifier(bytes);
}
break;
case SYBNUMERIC:
case SYBDECIMAL:
len = in.read();
if (len > 0) {
int sign = in.read();
len--;
byte[] bytes = new byte[len];
BigInteger bi;
if (in.getServerType() == Driver.SYBASE) {
// Sybase order is MSB first!
for (int i = 0; i < len; i++) {
bytes[i] = (byte) in.read();
}
bi = new BigInteger((sign == 0) ? 1 : -1, bytes);
} else {
while (len-- > 0) {
bytes[len] = (byte)in.read();
}
bi = new BigInteger((sign == 0) ? -1 : 1, bytes);
}
return new BigDecimal(bi, ci.scale);
}
break;
case SYBVARIANT:
return getVariant(connection, in);
default:
throw new ProtocolException("Unsupported TDS data type 0x"
+ Integer.toHexString(ci.tdsType & 0xFF));
}
return null;
}
/**
* Retrieve the signed status of the column.
*
* @param ci the column meta data
* @return true if the column is a signed numeric.
*/
static boolean isSigned(ColInfo ci) {
int type = ci.tdsType;
if (type < 0 || type > 255 || types[type] == null) {
throw new IllegalArgumentException("TDS data type " + type
+ " invalid");
}
if (type == TdsData.SYBINTN && ci.bufferSize == 1) {
type = TdsData.SYBINT1; // Tiny int is not signed!
}
return types[type].isSigned;
}
/**
* Retrieve the collation status of the column.
*
true if the column requires collation data.
*/
static boolean isCollation(ColInfo ci) {
int type = ci.tdsType;
if (type < 0 || type > 255 || types[type] == null) {
throw new IllegalArgumentException("TDS data type " + type
+ " invalid");
}
return types[type].isCollation;
}
/**
* Retrieve the currency status of the column.
*
* @param ci The column meta data.
* @return boolean true if the column is a currency type.
*/
static boolean isCurrency(ColInfo ci) {
int type = ci.tdsType;
if (type < 0 || type > 255 || types[type] == null) {
throw new IllegalArgumentException("TDS data type " + type
+ " invalid");
}
return type == SYBMONEY || type == SYBMONEY4 || type == SYBMONEYN;
}
/**
* Retrieve the searchable status of the column.
*
* @param ci the column meta data
* @return true if the column is not a text or image type.
*/
static boolean isSearchable(ColInfo ci) {
int type = ci.tdsType;
if (type < 0 || type > 255 || types[type] == null) {
throw new IllegalArgumentException("TDS data type " + type
+ " invalid");
}
return types[type].size != -4;
}
/**
* Determines whether the column is Unicode encoded.
*
* @param ci the column meta data
* @return true if the column is Unicode encoded
*/
static boolean isUnicode(ColInfo ci) {
int type = ci.tdsType;
if (type < 0 || type > 255 || types[type] == null) {
throw new IllegalArgumentException("TDS data type " + type
+ " invalid");
}
switch (type) {
case SYBNVARCHAR:
case SYBNTEXT:
case XSYBNCHAR:
case XSYBNVARCHAR:
case XSYBCHAR: // Not always
case SYBVARIANT: // Not always
return true;
default:
return false;
}
}
/**
* Fill in the TDS native type code and all other fields for a
* ColInfo instance with the JDBC type set.
*
* @param ci the ColInfo instance
*/
static void fillInType(ColInfo ci)
throws SQLException {
switch (ci.jdbcType) {
case java.sql.Types.VARCHAR:
ci.tdsType = SYBVARCHAR;
ci.bufferSize = MS_LONGVAR_MAX;
ci.displaySize = MS_LONGVAR_MAX;
ci.precision = MS_LONGVAR_MAX;
break;
case java.sql.Types.INTEGER:
ci.tdsType = SYBINT4;
ci.bufferSize = 4;
ci.displaySize = 11;
ci.precision = 10;
break;
case java.sql.Types.SMALLINT:
ci.tdsType = SYBINT2;
ci.bufferSize = 2;
ci.displaySize = 6;
ci.precision = 5;
break;
case java.sql.Types.BIT:
ci.tdsType = SYBBIT;
ci.bufferSize = 1;
ci.displaySize = 1;
ci.precision = 1;
break;
default:
throw new SQLException(Messages.get(
"error.baddatatype",
Integer.toString(ci.jdbcType)), "HY000");
}
ci.sqlType = types[ci.tdsType].sqlType;
ci.scale = 0;
}
/**
* Retrieve the TDS native type code for the parameter.
*
* @param connection the connectionJDBC object
* @param pi the parameter descriptor
*/
static void getNativeType(ConnectionJDBC2 connection, ParamInfo pi)
throws SQLException {
int len;
int jdbcType = pi.jdbcType;
if (jdbcType == java.sql.Types.OTHER) {
jdbcType = Support.getJdbcType(pi.value);
}
switch (jdbcType) {
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.LONGVARCHAR:
case java.sql.Types.CLOB:
if (pi.value == null) {
len = 0;
} else {
len = pi.length;
}
if (connection.getTdsVersion() < Driver.TDS70) {
String charset = connection.getCharset();
if (len > 0
&& (len <= SYB_LONGVAR_MAX / 2 || connection.getSybaseInfo(TdsCore.SYB_UNITEXT))
&& connection.getSybaseInfo(TdsCore.SYB_UNICODE)
&& connection.getUseUnicode()
&& !"UTF-8".equals(charset)) {
// Sybase can send values as unicode if conversion to the
// server charset fails.
// One option to determine if conversion will fail is to use
// the CharSetEncoder class but this is only available from
// JDK 1.4.
// For now we will call a local method to see if the string
// should be sent as unicode.
// This behaviour can be disabled by setting the connection
// property sendParametersAsUnicode=false.
// TODO: Find a better way of testing for convertable charset.
// With ASE 15 this code will read a CLOB into memory just to
// check for unicode characters. This is wasteful if no unicode
// data is present and we are targetting a text column. The option
// of always sending unicode does not work as the server will
// complain about image to text conversions unless the target
// column actually is unitext.
try {
String tmp = pi.getString(charset);
if (!canEncode(tmp, charset)) {
// Conversion fails need to send as unicode.
pi.length = tmp.length();
if (pi.length > SYB_LONGVAR_MAX / 2) {
pi.sqlType = "unitext";
pi.tdsType = SYBLONGDATA;
} else {
pi.sqlType = "univarchar("+pi.length+')';
pi.tdsType = SYBLONGBINARY;
}
break;
}
} catch (IOException e) {
throw new SQLException(
Messages.get("error.generic.ioerror", e.getMessage()), "HY000");
}
}
//
// If the client character set is wide then we need to ensure that the size
// is within bounds even after conversion from Unicode
//
if (connection.isWideChar() && len <= SYB_LONGVAR_MAX) {
try {
byte tmp[] = pi.getBytes(charset);
len = (tmp == null) ? 0 : tmp.length;
} catch (IOException e) {
throw new SQLException(
Messages.get("error.generic.ioerror", e.getMessage()), "HY000");
}
}
if (len <= VAR_MAX) {
pi.tdsType = SYBVARCHAR;
pi.sqlType = "varchar(255)";
} else {
if (connection.getSybaseInfo(TdsCore.SYB_LONGDATA)) {
if (len > SYB_LONGVAR_MAX) {
// Use special Sybase long data type which
// allows text data to be sent as a statement parameter
// (although not as a SP parameter).
pi.tdsType = SYBLONGDATA;
pi.sqlType = "text";
} else {
// Use Sybase 12.5+ long varchar type which
// is limited to 16384 bytes.
pi.tdsType = XSYBCHAR;
pi.sqlType = "varchar(" + len + ')';
}
} else {
pi.tdsType = SYBTEXT;
pi.sqlType = "text";
}
}
} else {
if (pi.isUnicode && len <= MS_LONGVAR_MAX / 2) {
pi.tdsType = XSYBNVARCHAR;
pi.sqlType = "nvarchar(4000)";
} else if (!pi.isUnicode && len <= MS_LONGVAR_MAX) {
CharsetInfo csi = connection.getCharsetInfo();
try {
if (len > 0 && csi.isWideChars() && pi.getBytes(csi.getCharset()).length > MS_LONGVAR_MAX) {
pi.tdsType = SYBTEXT;
pi.sqlType = "text";
} else {
pi.tdsType = XSYBVARCHAR;
pi.sqlType = "varchar(8000)";
}
} catch (IOException e) {
throw new SQLException(
Messages.get("error.generic.ioerror", e.getMessage()), "HY000");
}
} else {
if (pi.isOutput) {
throw new SQLException(
Messages.get("error.textoutparam"), "HY000");
}
if (pi.isUnicode) {
pi.tdsType = SYBNTEXT;
pi.sqlType = "ntext";
} else {
pi.tdsType = SYBTEXT;
pi.sqlType = "text";
}
}
}
break;
case java.sql.Types.TINYINT:
case java.sql.Types.SMALLINT:
case java.sql.Types.INTEGER:
pi.tdsType = SYBINTN;
pi.sqlType = "int";
break;
case JtdsStatement.BOOLEAN:
case java.sql.Types.BIT:
if (connection.getTdsVersion() >= Driver.TDS70 ||
connection.getSybaseInfo(TdsCore.SYB_BITNULL)) {
pi.tdsType = SYBBITN;
} else {
pi.tdsType = SYBBIT;
}
pi.sqlType = "bit";
break;
case java.sql.Types.REAL:
pi.tdsType = SYBFLTN;
pi.sqlType = "real";
break;
case java.sql.Types.FLOAT:
case java.sql.Types.DOUBLE:
pi.tdsType = SYBFLTN;
pi.sqlType = "float";
break;
case java.sql.Types.DATE:
if (connection.getSybaseInfo(TdsCore.SYB_DATETIME)) {
pi.tdsType = SYBDATEN;
pi.sqlType = "date";
} else {
pi.tdsType = SYBDATETIMN;
pi.sqlType = "datetime";
}
break;
case java.sql.Types.TIME:
if (connection.getSybaseInfo(TdsCore.SYB_DATETIME)) {
pi.tdsType = SYBTIMEN;
pi.sqlType = "time";
} else {
pi.tdsType = SYBDATETIMN;
pi.sqlType = "datetime";
}
break;
case java.sql.Types.TIMESTAMP:
pi.tdsType = SYBDATETIMN;
pi.sqlType = "datetime";
break;
case java.sql.Types.BINARY:
case java.sql.Types.VARBINARY:
case java.sql.Types.BLOB:
case java.sql.Types.LONGVARBINARY:
if (pi.value == null) {
len = 0;
} else {
len = pi.length;
}
if (connection.getTdsVersion() < Driver.TDS70) {
if (len <= VAR_MAX) {
pi.tdsType = SYBVARBINARY;
pi.sqlType = "varbinary(255)";
} else {
if (connection.getSybaseInfo(TdsCore.SYB_LONGDATA)) {
if (len > SYB_LONGVAR_MAX) {
// Need to use special Sybase long binary type
pi.tdsType = SYBLONGDATA;
pi.sqlType = "image";
} else {
// Sybase long binary that can be used as a SP parameter
pi.tdsType = SYBLONGBINARY;
pi.sqlType = "varbinary(" + len + ')';
}
} else {
// Sybase < 12.5 or SQL Server 6.5
pi.tdsType = SYBIMAGE;
pi.sqlType = "image";
}
}
} else {
if (len <= MS_LONGVAR_MAX) {
pi.tdsType = XSYBVARBINARY;
pi.sqlType = "varbinary(8000)";
} else {
if (pi.isOutput) {
throw new SQLException(
Messages.get("error.textoutparam"), "HY000");
}
pi.tdsType = SYBIMAGE;
pi.sqlType = "image";
}
}
break;
case java.sql.Types.BIGINT:
if (connection.getTdsVersion() >= Driver.TDS80 ||
connection.getSybaseInfo(TdsCore.SYB_BIGINT)) {
pi.tdsType = SYBINTN;
pi.sqlType = "bigint";
} else {
// int8 not supported send as a decimal field
pi.tdsType = SYBDECIMAL;
pi.sqlType = "decimal(" + connection.getMaxPrecision() + ')';
pi.scale = 0;
}
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.NUMERIC:
pi.tdsType = SYBDECIMAL;
int prec = connection.getMaxPrecision();
int scale = DEFAULT_SCALE;
if (pi.value instanceof BigDecimal) {
scale = ((BigDecimal)pi.value).scale();
} else if (pi.scale >= 0 && pi.scale <= prec) {
scale = pi.scale;
}
pi.sqlType = "decimal(" + prec + ',' + scale + ')';
break;
case java.sql.Types.OTHER:
case java.sql.Types.NULL:
// Send a null String in the absence of anything better
pi.tdsType = SYBVARCHAR;
pi.sqlType = "varchar(255)";
break;
default:
throw new SQLException(Messages.get(
"error.baddatatype",
Integer.toString(pi.jdbcType)), "HY000");
}
}
/**
* Calculate the size of the parameter descriptor array for TDS 5 packets.
*
* @param charset The encoding character set.
* @param isWideChar True if multi byte encoding.
* @param pi The parameter to describe.
* @param useParamNames True if named parameters should be used.
* @return The size of the parameter descriptor as an int.
*/
static int getTds5ParamSize(String charset,
boolean isWideChar,
ParamInfo pi,
boolean useParamNames) {
int size = 8;
if (pi.name != null && useParamNames) {
// Size of parameter name
if (isWideChar) {
byte[] buf = Support.encodeString(charset, pi.name);
size += buf.length;
} else {
size += pi.name.length();
}
}
switch (pi.tdsType) {
case SYBVARCHAR:
case SYBVARBINARY:
case SYBINTN:
case SYBFLTN:
case SYBDATETIMN:
case SYBDATEN:
case SYBTIMEN:
size += 1;
break;
case SYBDECIMAL:
case SYBLONGDATA:
size += 3;
break;
case XSYBCHAR:
case SYBLONGBINARY:
size += 4;
break;
case SYBBIT:
break;
default:
throw new IllegalStateException("Unsupported output TDS type 0x"
+ Integer.toHexString(pi.tdsType));
}
return size;
}
/**
* Write a TDS 5 parameter format descriptor.
*
* @param out The server RequestStream.
* @param charset The encoding character set.
* @param isWideChar True if multi byte encoding.
* @param pi The parameter to describe.
* @param useParamNames True if named parameters should be used.
* @throws IOException
*/
static void writeTds5ParamFmt(RequestStream out,
String charset,
boolean isWideChar,
ParamInfo pi,
boolean useParamNames)
throws IOException {
if (pi.name != null && useParamNames) {
// Output parameter name.
if (isWideChar) {
byte[] buf = Support.encodeString(charset, pi.name);
out.write((byte) buf.length);
out.write(buf);
} else {
out.write((byte) pi.name.length());
out.write(pi.name);
}
} else {
out.write((byte)0);
}
out.write((byte) (pi.isOutput ? 1 : 0)); // Output param
if (pi.sqlType.startsWith("univarchar")) {
out.write((int) UDT_UNIVARCHAR);
} else if ("unitext".equals(pi.sqlType)) {
out.write((int) UDT_UNITEXT);
} else {
out.write((int) 0); // user type
}
out.write((byte) pi.tdsType); // TDS data type token
// Output length fields
switch (pi.tdsType) {
case SYBVARCHAR:
case SYBVARBINARY:
out.write((byte) VAR_MAX);
break;
case XSYBCHAR:
out.write((int)0x7FFFFFFF);
break;
case SYBLONGDATA:
// It appears that type 3 = send text data
// and type 4 = send image or unitext data
// No idea if there is a type 1/2 or what they are.
out.write("text".equals(pi.sqlType) ? (byte) 3 : (byte) 4);
out.write((byte)0);
out.write((byte)0);
break;
case SYBLONGBINARY:
out.write((int)0x7FFFFFFF);
break;
case SYBBIT:
break;
case SYBINTN:
out.write("bigint".equals(pi.sqlType) ? (byte) 8: (byte) 4);
break;
case SYBFLTN:
if (pi.value instanceof Float) {
out.write((byte) 4);
} else {
out.write((byte) 8);
}
break;
case SYBDATETIMN:
out.write((byte) 8);
break;
case SYBDATEN:
case SYBTIMEN:
out.write((byte)4);
break;
case SYBDECIMAL:
out.write((byte) 17);
out.write((byte) 38);
if (pi.jdbcType == java.sql.Types.BIGINT) {
out.write((byte) 0);
} else {
if (pi.value instanceof BigDecimal) {
out.write((byte) ((BigDecimal) pi.value).scale());
} else {
if (pi.scale >= 0 && pi.scale <= TdsData.DEFAULT_PRECISION_38) {
out.write((byte) pi.scale);
} else {
out.write((byte) DEFAULT_SCALE);
}
}
}
break;
default:
throw new IllegalStateException(
"Unsupported output TDS type " + Integer.toHexString(pi.tdsType));
}
out.write((byte) 0); // Locale information
}
/**
* Write the actual TDS 5 parameter data.
*
* @param out the server RequestStream
* @param charsetInfo the encoding character set
* @param pi the parameter to output
* @throws IOException
* @throws SQLException
*/
static void writeTds5Param(RequestStream out,
CharsetInfo charsetInfo,
ParamInfo pi)
throws IOException, SQLException {
if (pi.charsetInfo == null) {
pi.charsetInfo = charsetInfo;
}
switch (pi.tdsType) {
case SYBVARCHAR:
if (pi.value == null) {
out.write((byte) 0);
} else {
byte buf[] = pi.getBytes(pi.charsetInfo.getCharset());
if (buf.length == 0) {
buf = new byte[1];
buf[0] = ' ';
}
if (buf.length > VAR_MAX) {
throw new SQLException(
Messages.get("error.generic.truncmbcs"), "HY000");
}
out.write((byte) buf.length);
out.write(buf);
}
break;
case SYBVARBINARY:
if (pi.value == null) {
out.write((byte) 0);
} else {
byte buf[] = pi.getBytes(pi.charsetInfo.getCharset());
if (out.getTdsVersion() < Driver.TDS70 && buf.length == 0) {
// Sybase and SQL 6.5 do not allow zero length binary
out.write((byte) 1); out.write((byte) 0);
} else {
out.write((byte) buf.length);
out.write(buf);
}
}
break;
case XSYBCHAR:
if (pi.value == null) {
out.write((byte) 0);
} else {
byte buf[] = pi.getBytes(pi.charsetInfo.getCharset());
if (buf.length == 0) {
buf = new byte[1];
buf[0] = ' ';
}
out.write((int) buf.length);
out.write(buf);
}
break;
case SYBLONGDATA:
//
// Write a three byte prefix usage unknown
//
out.write((byte)0);
out.write((byte)0);
out.write((byte)0);
//
// Write BLOB direct from input stream
//
if (pi.value instanceof InputStream) {
byte buffer[] = new byte[SYB_CHUNK_SIZE];
int len = ((InputStream) pi.value).read(buffer);
while (len > 0) {
out.write((byte) len);
out.write((byte) (len >> 8));
out.write((byte) (len >> 16));
out.write((byte) ((len >> 24) | 0x80)); // 0x80 means more to come
out.write(buffer, 0, len);
len = ((InputStream) pi.value).read(buffer);
}
} else
//
// Write CLOB direct from input Reader
//
if (pi.value instanceof Reader && !pi.charsetInfo.isWideChars()) {
// For ASE 15+ the getNativeType() routine will already have
// read the data from the reader so this code will not be
// reached unless sendStringParametersAsUnicode=false.
char buffer[] = new char[SYB_CHUNK_SIZE];
int len = ((Reader) pi.value).read(buffer);
while (len > 0) {
out.write((byte) len);
out.write((byte) (len >> 8));
out.write((byte) (len >> 16));
out.write((byte) ((len >> 24) | 0x80)); // 0x80 means more to come
out.write(Support.encodeString(
pi.charsetInfo.getCharset(),
new String(buffer, 0, len)));
len = ((Reader) pi.value).read(buffer);
}
} else
//
// Write data from memory buffer
//
if (pi.value != null) {
//
// Actual data needs to be written out in chunks of
// 8192 bytes.
//
if ("unitext".equals(pi.sqlType)) {
// Write out String as unicode bytes
String buf = pi.getString(pi.charsetInfo.getCharset());
int pos = 0;
while (pos < buf.length()) {
int clen = (buf.length() - pos >= SYB_CHUNK_SIZE / 2)?
SYB_CHUNK_SIZE / 2: buf.length() - pos;
int len = clen * 2;
out.write((byte) len);
out.write((byte) (len >> 8));
out.write((byte) (len >> 16));
out.write((byte) ((len >> 24) | 0x80)); // 0x80 means more to come
// Write data
out.write(buf.substring(pos, pos+clen).toCharArray(), 0, clen);
pos += clen;
}
} else {
// Write text as bytes
byte buf[] = pi.getBytes(pi.charsetInfo.getCharset());
int pos = 0;
while (pos < buf.length) {
int len = (buf.length - pos >= SYB_CHUNK_SIZE)
? SYB_CHUNK_SIZE : buf.length - pos;
out.write((byte) len);
out.write((byte) (len >> 8));
out.write((byte) (len >> 16));
out.write((byte) ((len >> 24) | 0x80)); // 0x80 means more to come
// Write data
for (int i = 0; i < len; i++) {
out.write(buf[pos++]);
}
}
}
}
// Write terminator
out.write((int) 0);
break;
case SYBLONGBINARY:
// Sybase data <= 16284 bytes long
if (pi.value == null) {
out.write((int) 0);
} else {
if (pi.sqlType.startsWith("univarchar")){
String tmp = pi.getString(pi.charsetInfo.getCharset());
if (tmp.length() == 0) {
tmp = " ";
}
out.write((int)tmp.length() * 2);
out.write(tmp.toCharArray(), 0, tmp.length());
} else {
byte buf[] = pi.getBytes(pi.charsetInfo.getCharset());
if (buf.length > 0) {
out.write((int) buf.length);
out.write(buf);
} else {
out.write((int) 1);
out.write((byte) 0);
}
}
}
break;
case SYBINTN:
if (pi.value == null) {
out.write((byte) 0);
} else {
if ("bigint".equals(pi.sqlType)) {
out.write((byte) 8);
out.write((long) ((Number) pi.value).longValue());
} else {
out.write((byte) 4);
out.write((int) ((Number) pi.value).intValue());
}
}
break;
case SYBFLTN:
if (pi.value == null) {
out.write((byte) 0);
} else {
if (pi.value instanceof Float) {
out.write((byte) 4);
out.write(((Number) pi.value).floatValue());
} else {
out.write((byte) 8);
out.write(((Number) pi.value).doubleValue());
}
}
break;
case SYBDATETIMN:
putDateTimeValue(out, (DateTime) pi.value);
break;
case SYBDATEN:
if (pi.value == null) {
out.write((byte)0);
} else {
out.write((byte)4);
out.write((int)((DateTime) pi.value).getDate());
}
break;
case SYBTIMEN:
if (pi.value == null) {
out.write((byte)0);
} else {
out.write((byte)4);
out.write((int)((DateTime) pi.value).getTime());
}
break;
case SYBBIT:
if (pi.value == null) {
out.write((byte) 0);
} else {
out.write((byte) (((Boolean) pi.value).booleanValue() ? 1 : 0));
}
break;
case SYBNUMERIC:
case SYBDECIMAL:
BigDecimal value = null;
if (pi.value != null) {
if (pi.value instanceof Long) {
// Long to BigDecimal conversion is buggy. It's actually
// long to double to BigDecimal.
value = new BigDecimal(pi.value.toString());
} else {
value = (BigDecimal) pi.value;
}
}
out.write(value);
break;
default:
throw new IllegalStateException(
"Unsupported output TDS type " + Integer.toHexString(pi.tdsType));
}
}
/**
* TDS 8 requires collation information for char data descriptors.
*
* @param out The Server request stream.
* @param pi The parameter descriptor.
* @throws IOException
*/
static void putCollation(RequestStream out, ParamInfo pi)
throws IOException {
//
// For TDS 8 write a collation string
// I am assuming this can be all zero for now if none is known
//
if (types[pi.tdsType].isCollation) {
if (pi.collation != null) {
out.write(pi.collation);
} else {
byte collation[] = {0x00, 0x00, 0x00, 0x00, 0x00};
out.write(collation);
}
}
}
/**
* Write a parameter to the server request stream.
*
* @param out the server request stream
* @param charsetInfo the default character set
* @param collation the default SQL Server 2000 collation
* @param pi the parameter descriptor
*/
static void writeParam(RequestStream out,
CharsetInfo charsetInfo,
byte[] collation,
ParamInfo pi)
throws IOException {
int len;
String tmp;
byte[] buf;
boolean isTds8 = out.getTdsVersion() >= Driver.TDS80;
if (isTds8) {
if (pi.collation == null) {
pi.collation = collation;
}
}
if (pi.charsetInfo == null) {
pi.charsetInfo = charsetInfo;
}
switch (pi.tdsType) {
case XSYBVARCHAR:
if (pi.value == null) {
out.write((byte) pi.tdsType);
out.write((short) MS_LONGVAR_MAX);
if (isTds8) {
putCollation(out, pi);
}
out.write((short) 0xFFFF);
} else {
buf = pi.getBytes(pi.charsetInfo.getCharset());
if (buf.length > MS_LONGVAR_MAX) {
out.write((byte) SYBTEXT);
out.write((int) buf.length);
if (isTds8) {
putCollation(out, pi);
}
out.write((int) buf.length);
out.write(buf);
} else {
out.write((byte) pi.tdsType);
out.write((short) MS_LONGVAR_MAX);
if (isTds8) {
putCollation(out, pi);
}
out.write((short) buf.length);
out.write(buf);
}
}
break;
case SYBVARCHAR:
if (pi.value == null) {
out.write((byte) pi.tdsType);
out.write((byte) VAR_MAX);
out.write((byte) 0);
} else {
buf = pi.getBytes(pi.charsetInfo.getCharset());
if (buf.length > VAR_MAX) {
if (buf.length <= MS_LONGVAR_MAX && out.getTdsVersion() >= Driver.TDS70) {
out.write((byte) XSYBVARCHAR);
out.write((short) MS_LONGVAR_MAX);
if (isTds8) {
putCollation(out, pi);
}
out.write((short) buf.length);
out.write(buf);
} else {
out.write((byte) SYBTEXT);
out.write((int) buf.length);
if (isTds8) {
putCollation(out, pi);
}
out.write((int) buf.length);
out.write(buf);
}
} else {
if (buf.length == 0) {
buf = new byte[1];
buf[0] = ' ';
}
out.write((byte) pi.tdsType);
out.write((byte) VAR_MAX);
out.write((byte) buf.length);
out.write(buf);
}
}
break;
case XSYBNVARCHAR:
out.write((byte) pi.tdsType);
out.write((short) MS_LONGVAR_MAX);
if (isTds8) {
putCollation(out, pi);
}
if (pi.value == null) {
out.write((short) 0xFFFF);
} else {
tmp = pi.getString(pi.charsetInfo.getCharset());
out.write((short) (tmp.length() * 2));
out.write(tmp);
}
break;
case SYBTEXT:
if (pi.value == null) {
len = 0;
} else {
len = pi.length;
if (len == 0 && out.getTdsVersion() < Driver.TDS70) {
pi.value = " ";
len = 1;
}
}
out.write((byte) pi.tdsType);
if (len > 0) {
if (pi.value instanceof InputStream) {
// Write output directly from stream
out.write((int) len);
if (isTds8) {
putCollation(out, pi);
}
out.write((int) len);
out.writeStreamBytes((InputStream) pi.value, len);
} else if (pi.value instanceof Reader && !pi.charsetInfo.isWideChars()) {
// Write output directly from stream with character translation
out.write((int) len);
if (isTds8) {
putCollation(out, pi);
}
out.write((int) len);
out.writeReaderBytes((Reader) pi.value, len);
} else {
buf = pi.getBytes(pi.charsetInfo.getCharset());
out.write((int) buf.length);
if (isTds8) {
putCollation(out, pi);
}
out.write((int) buf.length);
out.write(buf);
}
} else {
out.write((int) len); // Zero length
if (isTds8) {
putCollation(out, pi);
}
out.write((int)len);
}
break;
case SYBNTEXT:
if (pi.value == null) {
len = 0;
} else {
len = pi.length;
}
out.write((byte)pi.tdsType);
if (len > 0) {
if (pi.value instanceof Reader) {
out.write((int) len);
if (isTds8) {
putCollation(out, pi);
}
out.write((int) len * 2);
out.writeReaderChars((Reader) pi.value, len);
} else if (pi.value instanceof InputStream && !pi.charsetInfo.isWideChars()) {
out.write((int) len);
if (isTds8) {
putCollation(out, pi);
}
out.write((int) len * 2);
out.writeReaderChars(new InputStreamReader(
(InputStream) pi.value, pi.charsetInfo.getCharset()), len);
} else {
tmp = pi.getString(pi.charsetInfo.getCharset());
len = tmp.length();
out.write((int) len);
if (isTds8) {
putCollation(out, pi);
}
out.write((int) len * 2);
out.write(tmp);
}
} else {
out.write((int) len);
if (isTds8) {
putCollation(out, pi);
}
out.write((int) len);
}
break;
case XSYBVARBINARY:
out.write((byte) pi.tdsType);
out.write((short) MS_LONGVAR_MAX);
if (pi.value == null) {
out.write((short)0xFFFF);
} else {
buf = pi.getBytes(pi.charsetInfo.getCharset());
out.write((short) buf.length);
out.write(buf);
}
break;
case SYBVARBINARY:
out.write((byte) pi.tdsType);
out.write((byte) VAR_MAX);
if (pi.value == null) {
out.write((byte) 0);
} else {
buf = pi.getBytes(pi.charsetInfo.getCharset());
if (out.getTdsVersion() < Driver.TDS70 && buf.length == 0) {
// Sybase and SQL 6.5 do not allow zero length binary
out.write((byte) 1); out.write((byte) 0);
} else {
out.write((byte) buf.length);
out.write(buf);
}
}
break;
case SYBIMAGE:
if (pi.value == null) {
len = 0;
} else {
len = pi.length;
}
out.write((byte) pi.tdsType);
if (len > 0) {
if (pi.value instanceof InputStream) {
out.write((int) len);
out.write((int) len);
out.writeStreamBytes((InputStream) pi.value, len);
} else {
buf = pi.getBytes(pi.charsetInfo.getCharset());
out.write((int) buf.length);
out.write((int) buf.length);
out.write(buf);
}
} else {
if (out.getTdsVersion() < Driver.TDS70) {
// Sybase and SQL 6.5 do not allow zero length binary
out.write((int) 1);
out.write((int) 1);
out.write((byte) 0);
} else {
out.write((int) len);
out.write((int) len);
}
}
break;
case SYBINTN:
out.write((byte) pi.tdsType);
if (pi.value == null) {
out.write(("bigint".equals(pi.sqlType))? (byte)8: (byte)4);
out.write((byte) 0);
} else {
if ("bigint".equals(pi.sqlType)) {
out.write((byte) 8);
out.write((byte) 8);
out.write((long) ((Number) pi.value).longValue());
} else {
out.write((byte) 4);
out.write((byte) 4);
out.write((int) ((Number) pi.value).intValue());
}
}
break;
case SYBFLTN:
out.write((byte) pi.tdsType);
if (pi.value instanceof Float) {
out.write((byte) 4);
out.write((byte) 4);
out.write(((Number) pi.value).floatValue());
} else {
out.write((byte) 8);
if (pi.value == null) {
out.write((byte) 0);
} else {
out.write((byte) 8);
out.write(((Number) pi.value).doubleValue());
}
}
break;
case SYBDATETIMN:
out.write((byte) SYBDATETIMN);
out.write((byte) 8);
putDateTimeValue(out, (DateTime) pi.value);
break;
case SYBBIT:
out.write((byte) pi.tdsType);
if (pi.value == null) {
out.write((byte) 0);
} else {
out.write((byte) (((Boolean) pi.value).booleanValue() ? 1 : 0));
}
break;
case SYBBITN:
out.write((byte) SYBBITN);
out.write((byte) 1);
if (pi.value == null) {
out.write((byte) 0);
} else {
out.write((byte) 1);
out.write((byte) (((Boolean) pi.value).booleanValue() ? 1 : 0));
}
break;
case SYBNUMERIC:
case SYBDECIMAL:
out.write((byte) pi.tdsType);
BigDecimal value = null;
int prec = out.getMaxPrecision();
int scale;
if (pi.value == null) {
if (pi.jdbcType == java.sql.Types.BIGINT) {
scale = 0;
} else {
if (pi.scale >= 0 && pi.scale <= prec) {
scale = pi.scale;
} else {
scale = DEFAULT_SCALE;
}
}
} else {
if (pi.value instanceof Long) {
value = new BigDecimal(((Long) pi.value).toString());
scale = 0;
} else {
value = (BigDecimal) pi.value;
scale = value.scale();
}
}
out.write((byte) out.getMaxDecimalBytes());
out.write((byte) prec);
out.write((byte) scale);
out.write(value);
break;
default:
throw new IllegalStateException("Unsupported output TDS type "
+ Integer.toHexString(pi.tdsType));
}
}
//
// ---------------------- Private methods from here -----------------------
//
/**
* Private constructor to prevent users creating an
* actual instance of this class.
*/
private TdsData() {
}
/**
* Get a DATETIME value from the server response stream.
*
* @param in The server response stream.
* @param type The TDS data type.
* @return The java.sql.Timestamp value or null.
* @throws java.io.IOException
*/
private static Object getDatetimeValue(ResponseStream in, final int type)
throws IOException, ProtocolException {
int len;
int daysSince1900;
int time;
int minutes;
if (type == SYBDATETIMN) {
len = in.read(); // No need to & with 0xff
} else if (type == SYBDATETIME4) {
len = 4;
} else {
len = 8;
}
switch (len) {
case 0:
return null;
case 8:
// A datetime is made of of two 32 bit integers
// The first one is the number of days since 1900
// The second integer is the number of seconds*300
// Negative days indicate dates earlier than 1900.
// The full range is 1753-01-01 to 9999-12-31.
daysSince1900 = in.readInt();
time = in.readInt();
return new DateTime(daysSince1900, time);
case 4:
// A smalldatetime is two 16 bit integers.
// The first is the number of days past January 1, 1900,
// the second smallint is the number of minutes past
// midnight.
// The full range is 1900-01-01 to 2079-06-06.
daysSince1900 = ((int) in.readShort()) & 0xFFFF;
minutes = in.readShort();
return new DateTime((short) daysSince1900, (short) minutes);
default:
throw new ProtocolException("Invalid DATETIME value with size of "
+ len + " bytes.");
}
}
/**
* Output a java.sql.Date/Time/Timestamp value to the server
* as a Sybase datetime value.
*
* @param out the server request stream
* @param value the date value to write
*/
private static void putDateTimeValue(RequestStream out, DateTime value)
throws IOException {
if (value == null) {
out.write((byte) 0);
return;
}
out.write((byte) 8);
out.write((int)value.getDate());
out.write((int)value.getTime());
}
/**
* Read a MONEY value from the server response stream.
*
* @param in The server response stream.
* @param type The TDS data type.
* @return The java.math.BigDecimal value or null.
* @throws IOException
* @throws ProtocolException
*/
private static Object getMoneyValue(ResponseStream in, final int type)
throws IOException, ProtocolException {
final int len;
if (type == SYBMONEY) {
len = 8;
} else if (type == SYBMONEYN) {
len = in.read();
} else {
len = 4;
}
BigInteger x = null;
if (len == 4) {
x = BigInteger.valueOf(in.readInt());
} else if (len == 8) {
final byte b4 = (byte) in.read();
final byte b5 = (byte) in.read();
final byte b6 = (byte) in.read();
final byte b7 = (byte) in.read();
final byte b0 = (byte) in.read();
final byte b1 = (byte) in.read();
final byte b2 = (byte) in.read();
final byte b3 = (byte) in.read();
final long l = (long) (b0 & 0xff) + ((long) (b1 & 0xff) << 8)
+ ((long) (b2 & 0xff) << 16) + ((long) (b3 & 0xff) << 24)
+ ((long) (b4 & 0xff) << 32) + ((long) (b5 & 0xff) << 40)
+ ((long) (b6 & 0xff) << 48) + ((long) (b7 & 0xff) << 56);
x = BigInteger.valueOf(l);
} else if (len != 0) {
throw new ProtocolException("Invalid money value.");
}
return (x == null) ? null : new BigDecimal(x, 4);
}
/**
* Read a MSQL 2000 sql_variant data value from the input stream.
* SQL_VARIANT has the following structure: *
String
*/
public static String getMSTypeName(String typeName, int tdsType) {
if (typeName.equalsIgnoreCase("text") && tdsType != SYBTEXT) {
return "varchar";
} else if (typeName.equalsIgnoreCase("ntext") && tdsType != SYBTEXT) {
return "nvarchar";
} else if (typeName.equalsIgnoreCase("image") && tdsType != SYBIMAGE) {
return "varbinary";
} else {
return typeName;
}
}
/**
* Extract the TDS protocol version from the value returned by the server in the LOGINACK
* packet.
*
* @param rawTdsVersion the TDS protocol version as returned by the server
* @return the jTDS internal value for the protocol version (i.e one of the
* Driver.TDSXX values)
*/
public static int getTdsVersion(int rawTdsVersion) {
if (rawTdsVersion >= 0x71000001) {
return Driver.TDS81;
} else if (rawTdsVersion >= 0x07010000) {
return Driver.TDS80;
} else if (rawTdsVersion >= 0x07000000) {
return Driver.TDS70;
} else if (rawTdsVersion >= 0x05000000) {
return Driver.TDS50;
} else {
return Driver.TDS42;
}
}
/**
* Establish if a String can be converted to a byte based character set.
*
* @param value The String to test.
* @param charset The server character set in force.
* @return boolean true if string can be converted.
*/
private static boolean canEncode(String value, String charset)
{
if (value == null) {
return true;
}
if ("UTF-8".equals(charset)) {
// Should be no problem with UTF-8
return true;
}
if ("ISO-8859-1".equals(charset)) {
// ISO_1 = lower byte of unicode
for (int i = value.length() - 1; i >= 0; i--) {
if (value.charAt(i) > 255) {
return false; // Outside range
}
}
return true;
}
if ("ISO-8859-15".equals(charset) || "Cp1252".equals(charset)) {
// These will accept euro symbol
for (int i = value.length() - 1; i >= 0; i--) {
// FIXME This is not correct! Cp1252 also contains other characters.
// No: I think it is OK the point is to ensure that all characters are either
// < 256 in which case the sets are the same or the euro which is convertable.
// Any other combination will cause the string to be sent as unicode.
char c = value.charAt(i);
if (c > 255 && c != 0x20AC) {
return false; // Outside range
}
}
return true;
}
if ("US-ASCII".equals(charset)) {
for (int i = value.length() - 1; i >= 0; i--) {
if (value.charAt(i) > 127) {
return false; // Outside range
}
}
return true;
}
// OK need to do an expensive check
try {
return new String(value.getBytes(charset), charset).equals(value);
} catch (UnsupportedEncodingException e) {
return false;
}
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/Driver.java 0000644 0001750 0001750 00000043074 11316672660 025206 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import net.sourceforge.jtds.ssl.Ssl;
/**
* jTDS implementation of the java.sql.Driver interface.
* * Implementation note: *
jdbc:jtds:). */
private static String driverPrefix = "jdbc:jtds:";
/** Driver major version. */
static final int MAJOR_VERSION = 1;
/** Driver minor version. */
static final int MINOR_VERSION = 2;
/** Driver version miscellanea (e.g "-rc2", ".1" or null). */
static final String MISC_VERSION = ".5";
/** Set if the JDBC specification to implement is 3.0 or greater. */
public static final boolean JDBC3 =
"1.4".compareTo(System.getProperty("java.specification.version")) <= 0;
/** TDS 4.2 protocol (SQL Server 6.5 and later and Sybase 9 and later). */
public static final int TDS42 = 1;
/** TDS 5.0 protocol (Sybase 10 and later). */
public static final int TDS50 = 2;
/** TDS 7.0 protocol (SQL Server 7.0 and later). */
public static final int TDS70 = 3;
/** TDS 8.0 protocol (SQL Server 2000 and later)*/
public static final int TDS80 = 4;
/** TDS 8.1 protocol (SQL Server 2000 SP1 and later). */
public static final int TDS81 = 5;
/** Microsoft SQL Server. */
public static final int SQLSERVER = 1;
/** Sybase ASE. */
public static final int SYBASE = 2;
//
// Property name keys
//
public static final String APPNAME = "prop.appname";
public static final String BATCHSIZE = "prop.batchsize";
public static final String BINDADDRESS = "prop.bindaddress";
public static final String BUFFERDIR = "prop.bufferdir";
public static final String BUFFERMAXMEMORY = "prop.buffermaxmemory";
public static final String BUFFERMINPACKETS = "prop.bufferminpackets";
public static final String CACHEMETA = "prop.cachemetadata";
public static final String CHARSET = "prop.charset";
public static final String DATABASENAME = "prop.databasename";
public static final String DOMAIN = "prop.domain";
public static final String INSTANCE = "prop.instance";
public static final String LANGUAGE = "prop.language";
public static final String LASTUPDATECOUNT = "prop.lastupdatecount";
public static final String LOBBUFFER = "prop.lobbuffer";
public static final String LOGFILE = "prop.logfile";
public static final String LOGINTIMEOUT = "prop.logintimeout";
public static final String MACADDRESS = "prop.macaddress";
public static final String MAXSTATEMENTS = "prop.maxstatements";
public static final String NAMEDPIPE = "prop.namedpipe";
public static final String PACKETSIZE = "prop.packetsize";
public static final String PASSWORD = "prop.password";
public static final String PORTNUMBER = "prop.portnumber";
public static final String PREPARESQL = "prop.preparesql";
public static final String PROGNAME = "prop.progname";
public static final String SERVERNAME = "prop.servername";
public static final String SERVERTYPE = "prop.servertype";
public static final String SOTIMEOUT = "prop.sotimeout";
public static final String SOKEEPALIVE = "prop.sokeepalive";
public static final String PROCESSID = "prop.processid";
public static final String SSL = "prop.ssl";
public static final String TCPNODELAY = "prop.tcpnodelay";
public static final String TDS = "prop.tds";
public static final String USECURSORS = "prop.usecursors";
public static final String USEJCIFS = "prop.usejcifs";
public static final String USENTLMV2 = "prop.usentlmv2";
public static final String USELOBS = "prop.uselobs";
public static final String USER = "prop.user";
public static final String SENDSTRINGPARAMETERSASUNICODE = "prop.useunicode";
public static final String WSID = "prop.wsid";
public static final String XAEMULATION = "prop.xaemulation";
static {
try {
// Register this with the DriverManager
DriverManager.registerDriver(new Driver());
} catch (SQLException e) {
}
}
public int getMajorVersion() {
return MAJOR_VERSION;
}
public int getMinorVersion() {
return MINOR_VERSION;
}
/**
* Returns the driver version.
* * Per [908906] 0.7: Static Version information, please. * * @return the driver version */ public static final String getVersion() { return MAJOR_VERSION + "." + MINOR_VERSION + ((MISC_VERSION == null) ? "" : MISC_VERSION); } /** * Returns the string form of the object. *
* Per [887120] DriverVersion.getDriverVersion(); this will return a short * version name. *
* Added back to driver per [1006449] 0.9rc1: Driver version broken
*
* @return the driver version
*/
public String toString() {
return "jTDS " + getVersion();
}
public boolean jdbcCompliant() {
return false;
}
public boolean acceptsURL(String url) throws SQLException {
if (url == null) {
return false;
}
return url.toLowerCase().startsWith(driverPrefix);
}
public Connection connect(String url, Properties info)
throws SQLException {
if (url == null || !url.toLowerCase().startsWith(driverPrefix)) {
return null;
}
Properties props = setupConnectProperties(url, info);
if (JDBC3) {
return new ConnectionJDBC3(url, props);
}
return new ConnectionJDBC2(url, props);
}
public DriverPropertyInfo[] getPropertyInfo(final String url, final Properties props)
throws SQLException {
Properties parsedProps = parseURL(url, (props == null ? new Properties() : props));
if (parsedProps == null) {
throw new SQLException(
Messages.get("error.driver.badurl", url), "08001");
}
parsedProps = DefaultProperties.addDefaultProperties(parsedProps);
final Map propertyMap = new HashMap();
final Map descriptionMap = new HashMap();
Messages.loadDriverProperties(propertyMap, descriptionMap);
final Map choicesMap = createChoicesMap();
final Map requiredTrueMap = createRequiredTrueMap();
final DriverPropertyInfo[] dpi = new DriverPropertyInfo[propertyMap.size()];
final Iterator iterator = propertyMap.entrySet().iterator();
for (int i = 0; iterator.hasNext(); i++) {
final Map.Entry entry = (Map.Entry) iterator.next();
final String key = (String) entry.getKey();
final String name = (String) entry.getValue();
final DriverPropertyInfo info = new DriverPropertyInfo(name, parsedProps.getProperty(name));
info.description = (String) descriptionMap.get(key);
info.required = requiredTrueMap.containsKey(name);
if (choicesMap.containsKey(name)) {
info.choices = (String[]) choicesMap.get(name);
}
dpi[i] = info;
}
return dpi;
}
/**
* Sets up properties for the {@link #connect(String, java.util.Properties)} method.
*
* @param url the URL of the database to which to connect
* @param info a list of arbitrary string tag/value pairs as
* connection arguments.
* @return the set of properties for the connection
* @throws SQLException if an error occurs parsing the URL
*/
private Properties setupConnectProperties(String url, Properties info) throws SQLException {
Properties props = parseURL(url, info);
if (props == null) {
throw new SQLException(Messages.get("error.driver.badurl", url), "08001");
}
if (props.getProperty(Messages.get(Driver.LOGINTIMEOUT)) == null) {
props.setProperty(Messages.get(Driver.LOGINTIMEOUT), Integer.toString(DriverManager.getLoginTimeout()));
}
// Set default properties
props = DefaultProperties.addDefaultProperties(props);
return props;
}
/**
* Creates a map of driver properties whose choices
* field should be set when calling
* {@link #getPropertyInfo(String, Properties)}.
*
String[] objects
* that should be set to the choices field.
*
* @return The map of {@link DriverPropertyInfo} objects whose
* choices should be set.
*/
private static Map createChoicesMap() {
final HashMap choicesMap = new HashMap();
final String[] booleanChoices = new String[]{"true", "false"};
choicesMap.put(Messages.get(Driver.CACHEMETA), booleanChoices);
choicesMap.put(Messages.get(Driver.LASTUPDATECOUNT), booleanChoices);
choicesMap.put(Messages.get(Driver.NAMEDPIPE), booleanChoices);
choicesMap.put(Messages.get(Driver.TCPNODELAY), booleanChoices);
choicesMap.put(Messages.get(Driver.SENDSTRINGPARAMETERSASUNICODE), booleanChoices);
choicesMap.put(Messages.get(Driver.USECURSORS), booleanChoices);
choicesMap.put(Messages.get(Driver.USELOBS), booleanChoices);
choicesMap.put(Messages.get(Driver.XAEMULATION), booleanChoices);
final String[] prepareSqlChoices = new String[]{
String.valueOf(TdsCore.UNPREPARED),
String.valueOf(TdsCore.TEMPORARY_STORED_PROCEDURES),
String.valueOf(TdsCore.EXECUTE_SQL),
String.valueOf(TdsCore.PREPARE),
};
choicesMap.put(Messages.get(Driver.PREPARESQL), prepareSqlChoices);
final String[] serverTypeChoices = new String[]{
String.valueOf(SQLSERVER),
String.valueOf(SYBASE),
};
choicesMap.put(Messages.get(Driver.SERVERTYPE), serverTypeChoices);
final String[] tdsChoices = new String[]{
DefaultProperties.TDS_VERSION_42,
DefaultProperties.TDS_VERSION_50,
DefaultProperties.TDS_VERSION_70,
DefaultProperties.TDS_VERSION_80,
};
choicesMap.put(Messages.get(Driver.TDS), tdsChoices);
final String[] sslChoices = new String[]{
Ssl.SSL_OFF,
Ssl.SSL_REQUEST,
Ssl.SSL_REQUIRE,
Ssl.SSL_AUTHENTICATE
};
choicesMap.put(Messages.get(Driver.SSL), sslChoices);
return choicesMap;
}
/**
* Creates a map of driver properties that should be marked as
* required when calling {@link #getPropertyInfo(String, Properties)}.
*
* Note that only the key of the map is used to determine whether
* the required field should be set to true.
* If the key does not exist in the map, then the required
* field is set to false.
*
* @return The map of {@link DriverPropertyInfo} objects where
* required should be set to true.
*/
private static Map createRequiredTrueMap() {
final HashMap requiredTrueMap = new HashMap();
requiredTrueMap.put(Messages.get(Driver.SERVERNAME), null);
requiredTrueMap.put(Messages.get(Driver.SERVERTYPE), null);
return requiredTrueMap;
}
/**
* Parse the driver URL and extract the properties.
*
* @param url the URL to parse
* @param info any existing properties already loaded in a
* Properties object
* @return the URL properties as a Properties object
*/
private static Properties parseURL(String url, Properties info) {
Properties props = new Properties();
// Take local copy of existing properties
for (Enumeration e = info.propertyNames(); e.hasMoreElements();) {
String key = (String) e.nextElement();
String value = info.getProperty(key);
if (value != null) {
props.setProperty(key.toUpperCase(), value);
}
}
StringBuffer token = new StringBuffer(16);
int pos = 0;
pos = nextToken(url, pos, token); // Skip jdbc
if (!"jdbc".equalsIgnoreCase(token.toString())) {
return null; // jdbc: missing
}
pos = nextToken(url, pos, token); // Skip jtds
if (!"jtds".equalsIgnoreCase(token.toString())) {
return null; // jtds: missing
}
pos = nextToken(url, pos, token); // Get server type
String type = token.toString().toLowerCase();
Integer serverType = DefaultProperties.getServerType(type);
if (serverType == null) {
return null; // Bad server type
}
props.setProperty(Messages.get(Driver.SERVERTYPE), String.valueOf(serverType));
pos = nextToken(url, pos, token); // Null token between : and //
if (token.length() > 0) {
return null; // There should not be one!
}
pos = nextToken(url, pos, token); // Get server name
String host = token.toString();
if (host.length() == 0) {
host = props.getProperty(Messages.get(Driver.SERVERNAME));
if (host == null || host.length() == 0) {
return null; // Server name missing
}
}
props.setProperty(Messages.get(Driver.SERVERNAME), host);
if (url.charAt(pos - 1) == ':' && pos < url.length()) {
pos = nextToken(url, pos, token); // Get port number
try {
int port = Integer.parseInt(token.toString());
props.setProperty(Messages.get(Driver.PORTNUMBER), Integer.toString(port));
} catch(NumberFormatException e) {
return null; // Bad port number
}
}
if (url.charAt(pos - 1) == '/' && pos < url.length()) {
pos = nextToken(url, pos, token); // Get database name
props.setProperty(Messages.get(DATABASENAME), token.toString());
}
//
// Process any additional properties in URL
//
while (url.charAt(pos - 1) == ';' && pos < url.length()) {
pos = nextToken(url, pos, token);
String tmp = token.toString();
int index = tmp.indexOf('=');
if (index > 0 && index < tmp.length() - 1) {
props.setProperty(tmp.substring(0, index).toUpperCase(), tmp.substring(index + 1));
} else {
props.setProperty(tmp.toUpperCase(), "");
}
}
return props;
}
/**
* Extract the next lexical token from the URL.
*
* @param url The URL being parsed
* @param pos The current position in the URL string.
* @param token The buffer containing the extracted token.
* @return The updated position as an int.
*/
private static int nextToken(String url, int pos, StringBuffer token) {
token.setLength(0);
while (pos < url.length()) {
char ch = url.charAt(pos++);
if (ch == ':' || ch == ';') {
break;
}
if (ch == '/') {
if (pos < url.length() && url.charAt(pos) == '/') {
pos++;
}
break;
}
token.append(ch);
}
return pos;
}
public static void main(String[] args) {
System.out.println("jTDS " + getVersion());
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/SharedNamedPipe.java 0000644 0001750 0001750 00000012507 11316672660 026741 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.UnknownHostException;
import jcifs.Config;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbNamedPipe;
/**
* This class implements inter-process communication (IPC) to the
* database server using named pipes.
*
* @todo Extract abstract base class SharedIpc from SharedSocket and this class.
* @todo Implement connection timeouts for named pipes.
*
* @author David D. Kilzer
* @version $Id: SharedNamedPipe.java,v 1.19.2.2 2009/12/10 09:54:04 ickzon Exp $
*/
public class SharedNamedPipe extends SharedSocket {
/**
* The shared named pipe.
*/
private SmbNamedPipe pipe;
/**
* Creates a new instance of SharedNamedPipe.
*
* @param connection
* @throws IOException if the named pipe or its input or output streams do
* not open
* @throws UnknownHostException if host cannot be found for the named pipe
*/
public SharedNamedPipe(ConnectionJDBC2 connection) throws IOException {
super(connection.getBufferDir(), connection.getTdsVersion(), connection.getServerType());
// apply socketTimeout as responseTimeout
int timeout = connection.getSocketTimeout() * 1000;
String val = String.valueOf(timeout > 0 ? timeout : Integer.MAX_VALUE);
Config.setProperty("jcifs.smb.client.responseTimeout", val);
Config.setProperty("jcifs.smb.client.soTimeout", val);
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(
connection.getDomainName(), connection.getUser(), connection.getPassword());
StringBuffer url = new StringBuffer(32);
url.append("smb://");
url.append(connection.getServerName());
url.append("/IPC$");
final String instanceName = connection.getInstanceName();
if (instanceName != null && instanceName.length() != 0) {
url.append("/MSSQL$");
url.append(instanceName);
}
String namedPipePath = DefaultProperties.getNamedPipePath(connection.getServerType());
url.append(namedPipePath);
setPipe(new SmbNamedPipe(url.toString(), SmbNamedPipe.PIPE_TYPE_RDWR, auth));
setOut(new DataOutputStream(getPipe().getNamedPipeOutputStream()));
final int bufferSize = Support.calculateNamedPipeBufferSize(
connection.getTdsVersion(), connection.getPacketSize());
setIn(new DataInputStream(
new BufferedInputStream(
getPipe().getNamedPipeInputStream(), bufferSize)));
}
/**
* Get the connected status of this socket.
*
* @return true if the underlying socket is connected
*/
boolean isConnected() {
return getPipe() != null;
}
/**
* Close the socket (noop if in shared mode).
*/
void close() throws IOException {
super.close();
getOut().close();
getIn().close();
//getPipe().close();
}
/**
* Force close the socket causing any pending reads/writes to fail.
*
* Used by the login timer to abort a login attempt.
*/
void forceClose() {
try {
getOut().close();
}
catch (IOException e) {
// Ignore
}
finally {
setOut(null);
}
try {
getIn().close();
}
catch (IOException e) {
// Ignore
}
finally {
setIn(null);
}
setPipe(null);
}
/**
* Getter for {@link SharedNamedPipe#pipe} field.
*
* @return {@link SmbNamedPipe} used for communication
*/
private SmbNamedPipe getPipe() {
return pipe;
}
/**
* Setter for {@link SharedNamedPipe#pipe} field.
*
* @param pipe {@link SmbNamedPipe} to be used for communication
*/
private void setPipe(SmbNamedPipe pipe) {
this.pipe = pipe;
}
/**
* Set the socket timeout.
*
* Noop for now; timeouts are not implemented for SMB named pipes.
*
* @param timeout timeout value in milliseconds
*/
protected void setTimeout(int timeout) {
// FIXME - implement timeout functionality
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/SQLParser.java 0000644 0001750 0001750 00000114026 11316672660 025563 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import net.sourceforge.jtds.jdbc.cache.SimpleLRUCache;
import net.sourceforge.jtds.jdbc.cache.SQLCacheKey;
/**
* Process JDBC escape strings and parameter markers in the SQL string.
* * This code recognizes the following escapes: *
null if no parameters
* are expected.
*/
private final ArrayList params;
/** Current expected terminator character. */
private char terminator;
/** Procedure name in call escape. */
private String procName;
/** First SQL keyword or identifier in statement. */
private String keyWord;
/** First table name in from clause */
private String tableName;
/** Connection object for server specific parsing. */
private final ConnectionJDBC2 connection;
/**
* Parse the SQL statement processing JDBC escapes and parameter markers.
*
* @param extractTable
* true to return the first table name in the FROM clause of a select
* @return The processed SQL statement, any procedure name, the first SQL
* keyword and (optionally) the first table name as
* elements 0 1, 2 and 3 of the returned String[].
* @throws SQLException if a parse error occurs
*/
static String[] parse(String sql, ArrayList paramList,
ConnectionJDBC2 connection, boolean extractTable)
throws SQLException {
// Don't cache extract table parse requests, just process it
if (extractTable) {
SQLParser parser = new SQLParser(sql, paramList, connection);
return parser.parse(extractTable);
}
SimpleLRUCache cache = getCache(connection);
SQLCacheKey cacheKey = new SQLCacheKey(sql, connection);
// By not synchronizing on the cache, we're admitting that the possibility of multiple
// parses of the same statement can occur. However, it is 1) unlikely under normal
// usage, and 2) harmless to the cache. By avoiding a synchronization block around
// the get()-parse()-put(), we reduce the contention greatly in the nominal case.
CachedSQLQuery cachedQuery = (CachedSQLQuery) cache.get(cacheKey);
if (cachedQuery == null) {
// Parse and cache SQL
SQLParser parser = new SQLParser(sql, paramList, connection);
cachedQuery = new CachedSQLQuery(parser.parse(extractTable),
paramList);
cache.put(cacheKey, cachedQuery);
} else {
// Create full ParamInfo objects out of cached object
final int length = (cachedQuery.paramNames == null)
? 0 : cachedQuery.paramNames.length;
for (int i = 0; i < length; i++) {
ParamInfo paramInfo = new ParamInfo(cachedQuery.paramNames[i],
cachedQuery.paramMarkerPos[i],
cachedQuery.paramIsRetVal[i],
cachedQuery.paramIsUnicode[i]);
paramList.add(paramInfo);
}
}
return cachedQuery.parsedSql;
}
// --------------------------- Private Methods --------------------------------
/**
* Retrieves the statement cache, creating it if required.
*
* @return the cache as a SimpleLRUCache
*/
private synchronized static SimpleLRUCache getCache(ConnectionJDBC2 connection) {
if (cache == null) {
int maxStatements = connection.getMaxStatements();
maxStatements = Math.max(0, maxStatements);
maxStatements = Math.min(1000, maxStatements);
cache = new SimpleLRUCache(maxStatements);
}
return cache;
}
/** Lookup table to test if character is part of an identifier. */
private static boolean identifierChar[] = {
false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false,
false, false, false, true, true, false, false, false,
false, false, false, false, false, false, false, false,
true, true, true, true, true, true, true, true,
true, true, false, false, false, false, false, false,
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, false, false, false, false, true,
false, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true,
true, true, true, false, false, false, false, false
};
/**
* Determines if character could be part of an SQL identifier.
*
* Characters > 127 are assumed to be unicode letters in other
* languages than english which is reasonable in this application.
* @param ch the character to test.
* @return boolean true if ch in A-Z a-z 0-9 @ $ # _.
*/
private static boolean isIdentifier(int ch) {
return ch > 127 || identifierChar[ch];
}
/**
* Constructs a new parser object to process the supplied SQL.
*
* @param sqlIn the SQL statement to parse
* @param paramList the parameter list array to populate or
* null if no parameters are expected
* @param connection the parent Connection object
*/
private SQLParser(String sqlIn, ArrayList paramList, ConnectionJDBC2 connection) {
sql = sqlIn;
in = sql.toCharArray();
len = in.length;
out = new char[len + 256]; // Allow extra for curdate/curtime
params = paramList;
procName = "";
this.connection = connection;
}
/**
* Inserts a String literal in the output buffer.
*
* @param txt The text to insert.
*/
private void copyLiteral(String txt) throws SQLException {
final int len = txt.length();
for (int i = 0; i < len; i++) {
final char c = txt.charAt(i);
if (c == '?') {
if (params == null) {
throw new SQLException(
Messages.get("error.parsesql.unexpectedparam",
String.valueOf(s)),
"2A000");
}
// param marker embedded in escape
ParamInfo pi = new ParamInfo(d, connection.getUseUnicode());
params.add(pi);
}
out[d++] = c;
}
}
/**
* Copies over an embedded string literal unchanged.
*/
private void copyString() {
char saveTc = terminator;
char tc = in[s];
if (tc == '[') {
tc = ']';
}
terminator = tc;
out[d++] = in[s++];
while (in[s] != tc) {
out[d++] = in[s++];
}
out[d++] = in[s++];
terminator = saveTc;
}
/**
* Copies over possible SQL keyword eg 'SELECT'
*/
private String copyKeyWord() {
int start = d;
while (s < len && isIdentifier(in[s])) {
out[d++] = in[s++];
}
return String.valueOf(out, start, d - start).toLowerCase();
}
/**
* Builds a new parameter item.
*
* @param name Optional parameter name or null.
* @param pos The parameter marker position in the output buffer.
*/
private void copyParam(String name, int pos) throws SQLException {
if (params == null) {
throw new SQLException(
Messages.get("error.parsesql.unexpectedparam",
String.valueOf(s)),
"2A000");
}
ParamInfo pi = new ParamInfo(pos, connection.getUseUnicode());
pi.name = name;
if (pos >= 0) {
out[d++] = in[s++];
} else {
pi.isRetVal = true;
s++;
}
params.add(pi);
}
/**
* Copies an embedded stored procedure identifier over to the output buffer.
*
* @return The identifier as a String.
*/
private String copyProcName() throws SQLException {
int start = d;
do {
if (in[s] == '"' || in[s] == '[') {
copyString();
} else {
char c = in[s++];
while (isIdentifier(c) || c == ';') {
out[d++] = c;
c = in[s++];
}
s--;
}
if (in[s] == '.') {
while (in[s] == '.') {
out[d++] = in[s++];
}
} else {
break;
}
} while (true);
if (d == start) {
// Procedure name expected but found something else
throw new SQLException(
Messages.get("error.parsesql.syntax",
"call",
String.valueOf(s)),
"22025");
}
return new String(out, start, d - start);
}
/**
* Copies an embedded parameter name to the output buffer.
*
* @return The identifier as a String.
*/
private String copyParamName() {
int start = d;
char c = in[s++];
while (isIdentifier(c)) {
out[d++] = c;
c = in[s++];
}
s--;
return new String(out, start, d - start);
}
/**
* Copies over white space.
*/
private void copyWhiteSpace() {
while (s < in.length && Character.isWhitespace(in[s])) {
out[d++] = in[s++];
}
}
/**
* Checks that the next character is as expected.
*
* @param c The expected character.
* @param copy True if found character should be copied.
* @throws SQLException if expected characeter not found.
*/
private void mustbe(char c, boolean copy)
throws SQLException {
if (in[s] != c) {
throw new SQLException(
Messages.get("error.parsesql.mustbe",
String.valueOf(s),
String.valueOf(c)),
"22019");
}
if (copy) {
out[d++] = in[s++];
} else {
s++;
}
}
/**
* Skips embedded white space.
*/
private void skipWhiteSpace() {
while (Character.isWhitespace(in[s])) {
s++;
}
}
/**
* Skips single-line comments.
*/
private void skipSingleComments() {
while (s < len && in[s] != '\n' && in[s] != '\r') {
// comments should be passed on to the server
out[d++] = in[s++];
}
}
/**
* Skips multi-line comments
*/
private void skipMultiComments() throws SQLException {
int block = 0;
do {
if (s < len - 1) {
if (in[s] == '/' && in[s + 1] == '*') {
block++;
} else if (in[s] == '*' && in[s + 1] == '/') {
block--;
}
// comments should be passed on to the server
out[d++] = in[s++];
} else {
throw new SQLException(
Messages.get("error.parsesql.missing", "*/"),
"22025");
}
} while (block > 0);
out[d++] = in[s++];
}
/**
* Processes the JDBC {call procedure [(?,?,?)]} type escape.
*
* @throws SQLException if an error occurs
*/
private void callEscape() throws SQLException {
// Insert EXECUTE into SQL so that proc can be called as normal SQL
copyLiteral("EXECUTE ");
keyWord = "execute";
// Process procedure name
procName = copyProcName();
skipWhiteSpace();
if (in[s] == '(') { // Optional ( )
s++;
terminator = ')';
skipWhiteSpace();
} else {
terminator = '}';
}
out[d++] = ' ';
// Process any parameters
while (in[s] != terminator) {
String name = null;
if (in[s] == '@') {
// Named parameter
name = copyParamName();
skipWhiteSpace();
mustbe('=', true);
skipWhiteSpace();
if (in[s] == '?') {
copyParam(name, d);
} else {
// Named param has literal value can't call as RPC
procName = "";
}
} else if (in[s] == '?') {
copyParam(name, d);
} else {
// Literal parameter can't call as RPC
procName = "";
}
// Now find terminator or comma
while (in[s] != terminator && in[s] != ',') {
if (in[s] == '{') {
escape();
} else if (in[s] == '\'' || in[s] == '[' || in[s] == '"') {
copyString();
} else {
out[d++] = in[s++];
}
}
if (in[s] == ',') {
out[d++] = in[s++];
}
skipWhiteSpace();
}
if (terminator == ')') {
s++; // Elide
}
terminator = '}';
skipWhiteSpace();
}
/**
* Utility routine to validate date and time escapes.
*
* @param mask The validation mask
* @return True if the escape was valid and processed OK.
*/
private boolean getDateTimeField(byte[] mask) throws SQLException {
skipWhiteSpace();
if (in[s] == '?') {
// Allow {ts ?} type construct
copyParam(null, d);
skipWhiteSpace();
return in[s] == terminator;
}
out[d++] = '\'';
terminator = (in[s] == '\'' || in[s] == '"') ? in[s++] : '}';
skipWhiteSpace();
int ptr = 0;
while (ptr < mask.length) {
char c = in[s++];
if (c == ' ' && out[d - 1] == ' ') {
continue; // Eliminate multiple spaces
}
if (mask[ptr] == '#') {
if (!Character.isDigit(c)) {
return false;
}
} else if (mask[ptr] != c) {
return false;
}
if (c != '-') {
out[d++] = c;
}
ptr++;
}
if (mask.length == 19) { // Timestamp
int digits = 0;
if (in[s] == '.') {
out[d++] = in[s++];
while (Character.isDigit(in[s])) {
if (digits < 3) {
out[d++] = in[s++];
digits++;
} else {
s++;
}
}
} else {
out[d++] = '.';
}
for (; digits < 3; digits++) {
out[d++] = '0';
}
}
skipWhiteSpace();
if (in[s] != terminator) {
return false;
}
if (terminator != '}') {
s++; // Skip terminator
}
skipWhiteSpace();
out[d++] = '\'';
return true;
}
/** Syntax mask for time escape. */
private static final byte[] timeMask = {
'#','#',':','#','#',':','#','#'
};
/** Syntax mask for date escape. */
private static final byte[] dateMask = {
'#','#','#','#','-','#','#','-','#','#'
};
/** Syntax mask for timestamp escape. */
static final byte[] timestampMask = {
'#','#','#','#','-','#','#','-','#','#',' ',
'#','#',':','#','#',':','#','#'
};
/**
* Processes the JDBC escape {oj left outer join etc}.
*
* @throws SQLException
*/
private void outerJoinEscape()
throws SQLException {
while (in[s] != '}') {
final char c = in[s];
switch (c) {
case '\'':
case '"':
case '[':
copyString();
break;
case '{':
// Nested escape!
escape();
break;
case '?':
copyParam(null, d);
break;
default:
out[d++] = c;
s++;
break;
}
}
}
/** Map of jdbc to sybase function names. */
private static HashMap fnMap = new HashMap();
/** Map of jdbc to sql server function names. */
private static HashMap msFnMap = new HashMap();
/** Map of jdbc to server data types for convert */
private static HashMap cvMap = new HashMap();
static {
// Microsoft only functions
msFnMap.put("length", "len($)");
msFnMap.put("truncate", "round($, 1)");
// Common functions
fnMap.put("user", "user_name($)");
fnMap.put("database", "db_name($)");
fnMap.put("ifnull", "isnull($)");
fnMap.put("now", "getdate($)");
fnMap.put("atan2", "atn2($)");
fnMap.put("mod", "($)");
fnMap.put("length", "char_length($)");
fnMap.put("locate", "charindex($)");
fnMap.put("repeat", "replicate($)");
fnMap.put("insert", "stuff($)");
fnMap.put("lcase", "lower($)");
fnMap.put("ucase", "upper($)");
fnMap.put("concat", "($)");
fnMap.put("curdate", "convert(datetime, convert(varchar, getdate(), 112))");
fnMap.put("curtime", "convert(datetime, convert(varchar, getdate(), 108))");
fnMap.put("dayname", "datename(weekday,$)");
fnMap.put("dayofmonth", "datepart(day,$)");
fnMap.put("dayofweek", "((datepart(weekday,$)+@@DATEFIRST-1)%7+1)");
fnMap.put("dayofyear", "datepart(dayofyear,$)");
fnMap.put("hour", "datepart(hour,$)");
fnMap.put("minute", "datepart(minute,$)");
fnMap.put("second", "datepart(second,$)");
fnMap.put("year", "datepart(year,$)");
fnMap.put("quarter", "datepart(quarter,$)");
fnMap.put("month", "datepart(month,$)");
fnMap.put("week", "datepart(week,$)");
fnMap.put("monthname", "datename(month,$)");
fnMap.put("timestampadd", "dateadd($)");
fnMap.put("timestampdiff", "datediff($)");
// convert jdbc to sql types
cvMap.put("binary", "varbinary");
cvMap.put("char", "varchar");
cvMap.put("date", "datetime");
cvMap.put("double", "float");
cvMap.put("longvarbinary", "image");
cvMap.put("longvarchar", "text");
cvMap.put("time", "datetime");
cvMap.put("timestamp", "timestamp");
}
/**
* Processes the JDBC escape {fn function()}.
*
* @throws SQLException
*/
private void functionEscape() throws SQLException {
char tc = terminator;
skipWhiteSpace();
StringBuffer nameBuf = new StringBuffer();
//
// Capture name
//
while (isIdentifier(in[s])) {
nameBuf.append(in[s++]);
}
String name = nameBuf.toString().toLowerCase();
//
// Now collect arguments
//
skipWhiteSpace();
mustbe('(', false);
int parenCnt = 1;
int argStart = d;
int arg2Start = 0;
terminator = ')';
while (in[s] != ')' || parenCnt > 1) {
final char c = in[s];
switch (c) {
case '\'':
case '"':
case '[':
copyString();
break;
case '{':
// Process nested escapes!
escape();
break;
case ',':
if (arg2Start == 0) {
arg2Start = d - argStart;
}
if ("concat".equals(name)) {
out[d++] = '+'; s++;
} else if ("mod".equals(name)) {
out[d++] = '%'; s++;
} else {
out[d++] = c; s++;
}
break;
case '(':
parenCnt++;
out[d++] = c; s++;
break;
case ')':
parenCnt--;
out[d++] = c; s++;
break;
default:
out[d++] = c; s++;
break;
}
}
String args = String.valueOf(out, argStart, d - argStart).trim();
d = argStart;
mustbe(')', false);
terminator = tc;
skipWhiteSpace();
//
// Process convert scalar function.
// Arguments need to be reversed and the data type
// argument converted to an SQL server type
//
if ("convert".equals(name) && arg2Start < args.length() - 1) {
String arg2 = args.substring(arg2Start + 1).trim().toLowerCase();
String dataType = (String) cvMap.get(arg2);
if (dataType == null) {
// Will get server error if invalid type passed
dataType = arg2;
}
copyLiteral("convert(");
copyLiteral(dataType);
out[d++] = ',';
copyLiteral(args.substring(0, arg2Start));
out[d++] = ')';
return;
}
//
// See if function mapped
//
String fn;
if (connection.getServerType() == Driver.SQLSERVER) {
fn = (String) msFnMap.get(name);
if (fn == null) {
fn = (String) fnMap.get(name);
}
} else {
fn = (String) fnMap.get(name);
}
if (fn == null) {
// Not mapped so assume simple case
copyLiteral(name);
out[d++] = '(';
copyLiteral(args);
out[d++] = ')';
return;
}
//
// Process timestamp interval constants
//
if (args.length() > 8
&& args.substring(0, 8).equalsIgnoreCase("sql_tsi_")) {
args = args.substring(8);
if (args.length() > 11
&& args.substring(0, 11).equalsIgnoreCase("frac_second")) {
args = "millisecond" + args.substring(11);
}
}
//
// Substitute mapped function name and arguments
//
final int len = fn.length();
for (int i = 0; i < len; i++) {
final char c = fn.charAt(i);
if (c == '$') {
// Substitute arguments
copyLiteral(args);
} else {
out[d++] = c;
}
}
}
/**
* Processes the JDBC escape {escape 'X'}.
*
* @throws SQLException
*/
private void likeEscape() throws SQLException {
copyLiteral("escape ");
skipWhiteSpace();
if (in[s] == '\'' || in[s] == '"') {
copyString();
} else {
mustbe('\'', true);
}
skipWhiteSpace();
}
/**
* Processes the JDBC escape sequences.
*
* @throws SQLException
*/
private void escape() throws SQLException {
char tc = terminator;
terminator = '}';
StringBuffer escBuf = new StringBuffer();
s++;
skipWhiteSpace();
if (in[s] == '?') {
copyParam("@return_status", -1);
skipWhiteSpace();
mustbe('=', false);
skipWhiteSpace();
while (Character.isLetter(in[s])) {
escBuf.append(Character.toLowerCase(in[s++]));
}
skipWhiteSpace();
String esc = escBuf.toString();
if ("call".equals(esc)) {
callEscape();
} else {
throw new SQLException(
Messages.get("error.parsesql.syntax",
"call",
String.valueOf(s)),
"22019");
}
} else {
while (Character.isLetter(in[s])) {
escBuf.append(Character.toLowerCase(in[s++]));
}
skipWhiteSpace();
String esc = escBuf.toString();
if ("call".equals(esc)) {
callEscape();
} else if ("t".equals(esc)) {
if (!getDateTimeField(timeMask)) {
throw new SQLException(
Messages.get("error.parsesql.syntax",
"time",
String.valueOf(s)),
"22019");
}
} else if ("d".equals(esc)) {
if (!getDateTimeField(dateMask)) {
throw new SQLException(
Messages.get("error.parsesql.syntax",
"date",
String.valueOf(s)),
"22019");
}
} else if ("ts".equals(esc)) {
if (!getDateTimeField(timestampMask)) {
throw new SQLException(
Messages.get("error.parsesql.syntax",
"timestamp",
String.valueOf(s)),
"22019");
}
} else if ("oj".equals(esc)) {
outerJoinEscape();
} else if ("fn".equals(esc)) {
functionEscape();
} else if ("escape".equals(esc)) {
likeEscape();
} else {
throw new SQLException(
Messages.get("error.parsesql.badesc",
esc,
String.valueOf(s)),
"22019");
}
}
mustbe('}', false);
terminator = tc;
}
/**
* Extracts the first table name following the keyword FROM.
*
* @return the table name as a String
*/
private String getTableName() throws SQLException {
StringBuffer name = new StringBuffer(128);
copyWhiteSpace();
char c = (s < len) ? in[s] : ' ';
if (c == '{') {
// Start of {oj ... } we can assume that there is
// more than one table in select and therefore
// it would not be updateable.
return "";
}
//
// Skip any leading comments before first table name
//
while (c == '/' || c == '-' && s + 1 < len) {
if (c == '/') {
if (in[s + 1] == '*') {
skipMultiComments();
} else {
break;
}
} else {
if (in[s + 1] == '-') {
skipSingleComments();
} else {
break;
}
}
copyWhiteSpace();
c = (s < len) ? in[s] : ' ';
}
if (c == '{') {
// See comment above
return "";
}
//
// Now process table name
//
while (s < len) {
if (c == '[' || c == '"') {
int start = d;
copyString();
name.append(String.valueOf(out, start, d - start));
copyWhiteSpace();
c = (s < len) ? in[s] : ' ';
} else {
int start = d;
c = (s < len) ? in[s++] : ' ';
while ((isIdentifier(c))
&& c != '.'
&& c != ',') {
out[d++] = c;
c = (s < len) ? in[s++] : ' ';
}
name.append(String.valueOf(out, start, d - start));
s--;
copyWhiteSpace();
c = (s < len) ? in[s] : ' ';
}
if (c != '.') {
break;
}
name.append(c);
out[d++] = c; s++;
copyWhiteSpace();
c = (s < len) ? in[s] : ' ';
}
return name.toString();
}
/**
* Parses the SQL statement processing JDBC escapes and parameter markers.
*
* @param extractTable true to return the first table name in the FROM clause of a select
* @return The processed SQL statement, any procedure name, the first
* SQL keyword and (optionally) the first table name as elements 0 1, 2 and 3 of the
* returned String[].
* @throws SQLException
*/
String[] parse(boolean extractTable) throws SQLException {
boolean isSelect = false;
boolean isModified = false;
boolean isSlowScan = true;
try {
while (s < len) {
final char c = in[s];
switch (c) {
case '{':
escape();
isModified = true;
break;
case '[':
case '"':
case '\'':
copyString();
break;
case '?':
copyParam(null, d);
break;
case '/':
if (s+1 < len && in[s+1] == '*') {
skipMultiComments();
} else {
out[d++] = c; s++;
}
break;
case '-':
if (s+1 < len && in[s+1] == '-') {
skipSingleComments();
} else {
out[d++] = c; s++;
}
break;
default:
if (isSlowScan && Character.isLetter(c)) {
if (keyWord == null) {
keyWord = copyKeyWord();
if ("select".equals(keyWord)) {
isSelect = true;
}
isSlowScan = extractTable && isSelect;
break;
}
if (extractTable && isSelect) {
String sqlWord = copyKeyWord();
if ("from".equals(sqlWord)) {
// Ensure only first 'from' is processed
isSlowScan = false;
tableName = getTableName();
}
break;
}
}
out[d++] = c; s++;
break;
}
}
//
// Impose a reasonable maximum limit on the number of parameters
// unless the connection is sending statements unprepared (i.e. by
// building a plain query) and this is not a procedure call.
//
if (params != null && params.size() > 255
&& connection.getPrepareSql() != TdsCore.UNPREPARED
&& procName != null) {
int limit = 255; // SQL 6.5 and Sybase < 12.50
if (connection.getServerType() == Driver.SYBASE) {
if (connection.getDatabaseMajorVersion() > 12 ||
connection.getDatabaseMajorVersion() == 12 &&
connection.getDatabaseMinorVersion() >= 50) {
limit = 2000; // Actually 2048 but allow some head room
}
} else {
if (connection.getDatabaseMajorVersion() == 7) {
limit = 1000; // Actually 1024
} else
if (connection.getDatabaseMajorVersion() > 7) {
limit = 2000; // Actually 2100
}
}
if (params.size() > limit) {
throw new SQLException(
Messages.get("error.parsesql.toomanyparams",
Integer.toString(limit)),
"22025");
}
}
String result[] = new String[4];
// return sql and procname
result[0] = (isModified) ? new String(out, 0, d) : sql;
result[1] = procName;
result[2] = (keyWord == null) ? "" : keyWord;
result[3] = tableName;
return result;
} catch (IndexOutOfBoundsException e) {
// Should only come here if string is invalid in some way.
throw new SQLException(
Messages.get("error.parsesql.missing",
String.valueOf(terminator)),
"22025");
}
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbc/CharsetInfo.java 0000644 0001750 0001750 00000022272 11316672660 026155 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbc;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Properties;
import java.util.Enumeration;
import java.io.InputStream;
import java.io.IOException;
import net.sourceforge.jtds.util.Logger;
/**
* Loads and stores information about character sets. Static fields and methods
* are concerned with loading, storing and retrieval of all character set
* information, while non-static fields and methods describe a particular
* character set (Java charset name and whether it's a multi-byte charset).
*
* Note: Only one CharsetInfo instance exists per charset.
* This allows simple equality comparisons between instances retrieved with any
* of the get methods.
*
* @author Alin Sinpalean
* @version $Id: CharsetInfo.java,v 1.5 2007/07/08 17:28:23 bheineman Exp $
*/
public final class CharsetInfo {
//
// Static fields and methods
//
/** Name of the Charsets.properties resource. */
private static final String CHARSETS_RESOURCE_NAME
= "net/sourceforge/jtds/jdbc/Charsets.properties";
/** Server charset to Java charset map. */
private static final HashMap charsets = new HashMap();
/** Locale id to Java charset map. */
private static final HashMap lcidToCharsetMap = new HashMap();
/** Sort order to Java charset map. */
private static final CharsetInfo[] sortToCharsetMap = new CharsetInfo[256];
static {
// Load character set mappings
try {
InputStream stream = null;
// getContextClassLoader needed to ensure driver
// works with Tomcat class loading rules.
ClassLoader classLoader =
Thread.currentThread().getContextClassLoader();
if (classLoader != null) {
stream = classLoader.getResourceAsStream(
CHARSETS_RESOURCE_NAME);
}
if (stream == null) {
// The doPrivileged() call stops the SecurityManager from
// checking further in the stack trace whether all callers have
// the permission to load Charsets.properties
stream = (InputStream) java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
ClassLoader loader = CharsetInfo.class.getClassLoader();
// getClassLoader() may return null if the class was loaded by
// the bootstrap ClassLoader
if (loader == null) {
loader = ClassLoader.getSystemClassLoader();
}
return loader.getResourceAsStream(
CHARSETS_RESOURCE_NAME);
}
}
);
}
if (stream != null) {
Properties tmp = new Properties();
tmp.load(stream);
HashMap instances = new HashMap();
for (Enumeration e = tmp.propertyNames(); e.hasMoreElements();) {
String key = (String) e.nextElement();
CharsetInfo value = new CharsetInfo(tmp.getProperty(key));
// Ensure only one CharsetInfo instance exists per charset
CharsetInfo prevInstance = (CharsetInfo) instances.get(
value.getCharset());
if (prevInstance != null) {
if (prevInstance.isWideChars() != value.isWideChars()) {
throw new IllegalStateException(
"Inconsistent Charsets.properties");
}
value = prevInstance;
}
if (key.startsWith("LCID_")) {
Integer lcid = new Integer(key.substring(5));
lcidToCharsetMap.put(lcid, value);
} else if (key.startsWith("SORT_")) {
sortToCharsetMap[Integer.parseInt(key.substring(5))] = value;
} else {
charsets.put(key, value);
}
}
} else {
Logger.println("Can't load Charsets.properties");
}
} catch (IOException e) {
// Can't load properties file for some reason
Logger.logException(e);
}
}
/**
* Retrieves the CharsetInfo instance asociated with the
* specified server charset.
*
* @param serverCharset the server-specific character set name
* @return the associated CharsetInfo
*/
public static CharsetInfo getCharset(String serverCharset) {
return (CharsetInfo) charsets.get(serverCharset.toUpperCase());
}
/**
* Retrieves the CharsetInfo instance asociated with the
* specified LCID.
*
* @param lcid the server LCID
* @return the associated CharsetInfo
*/
public static CharsetInfo getCharsetForLCID(int lcid) {
return (CharsetInfo) lcidToCharsetMap.get(new Integer(lcid));
}
/**
* Retrieves the CharsetInfo instance asociated with the
* specified sort order.
*
* @param sortOrder the server sort order
* @return the associated CharsetInfo
*/
public static CharsetInfo getCharsetForSortOrder(int sortOrder) {
return sortToCharsetMap[sortOrder];
}
/**
* Retrieves the CharsetInfo instance asociated with the
* specified collation.
*
* @param collation the server LCID
* @return the associated CharsetInfo
*/
public static CharsetInfo getCharset(byte[] collation)
throws SQLException {
CharsetInfo charset;
if (collation[4] != 0) {
// The charset is determined by the sort order
charset = getCharsetForSortOrder((int) collation[4] & 0xFF);
} else {
// The charset is determined by the LCID
charset = getCharsetForLCID(
((int) collation[2] & 0x0F) << 16
| ((int) collation[1] & 0xFF) << 8
| ((int) collation[0] & 0xFF));
}
if (charset == null) {
throw new SQLException(
Messages.get("error.charset.nocollation", Support.toHex(collation)),
"2C000");
}
return charset;
}
//
// Non-static fields and methods
//
/** The Java character set name. */
private final String charset;
/** Indicates whether current charset is wide (ie multi-byte). */
private final boolean wideChars;
/**
* Constructs a CharsetInfo object from a character set
* descriptor of the form: charset preceded by a numeric value indicating
* whether it's a multibyte character set (>1) or not (1) and a vertical
* bar (|), eg "1|Cp1252" or "2|MS936".
*
* @param descriptor the charset descriptor
*/
public CharsetInfo(String descriptor) {
wideChars = !"1".equals(descriptor.substring(0, 1));
charset = descriptor.substring(2);
}
/**
* Retrieves the charset name.
*/
public String getCharset() {
return charset;
}
/**
* Retrieves whether the caracter set is wide (ie multi-byte).
*/
public boolean isWideChars() {
return wideChars;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof CharsetInfo)) {
return false;
}
final CharsetInfo charsetInfo = (CharsetInfo) o;
if (!charset.equals(charsetInfo.charset)) {
return false;
}
return true;
}
public int hashCode() {
return charset.hashCode();
}
public String toString() {
return charset;
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/util/ 0000755 0001750 0001750 00000000000 11316672660 023153 5 ustar martin martin libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/util/DESEngine.java 0000644 0001750 0001750 00000043613 11316672660 025566 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.util;
/**
* a class that provides a basic DES engine.
* Modified by Matt Brinkley (mdb) ... mainly just removed depends on external classes.
*
* @author Matt Brinkley
* @version $Id: DESEngine.java,v 1.3.6.1 2009/08/04 10:33:54 ickzon Exp $
*/
public class DESEngine
{
protected static final int BLOCK_SIZE = 8;
private int[] workingKey = null;
/**
* standard constructor.
*/
public DESEngine()
{
}
/**
* mdb: convenient constructor
*/
public DESEngine( boolean encrypting, byte[] key )
{
init( encrypting, key );
}
/**
* initialise a DES cipher.
*
* @param encrypting whether or not we are for encryption.
* @param key the parameters required to set up the cipher.
* @exception IllegalArgumentException if the params argument is
* inappropriate.
*/
public void init(boolean encrypting, byte[] key)
{
workingKey = generateWorkingKey(encrypting, key);
}
public String getAlgorithmName()
{
return "DES";
}
public int getBlockSize()
{
return BLOCK_SIZE;
}
public int processBlock(
byte[] in,
int inOff,
byte[] out,
int outOff)
{
if (workingKey == null)
{
throw new IllegalStateException("DES engine not initialised");
}
if ((inOff + BLOCK_SIZE) > in.length)
{
//mdb: used to be DataLengthException
throw new IllegalArgumentException("input buffer too short");
}
if ((outOff + BLOCK_SIZE) > out.length)
{
//mdb: used to be DataLengthException
throw new IllegalArgumentException("output buffer too short");
}
desFunc(workingKey, in, inOff, out, outOff);
return BLOCK_SIZE;
}
public void reset()
{
}
/**
* what follows is mainly taken from "Applied Cryptography", by
* Bruce Schneier, however it also bears great resemblance to Richard
* Outerbridge's D3DES...
*/
static short[] Df_Key =
{
0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,
0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10,
0x89,0xab,0xcd,0xef,0x01,0x23,0x45,0x67
};
static short[] bytebit =
{
0200, 0100, 040, 020, 010, 04, 02, 01
};
static int[] bigbyte =
{
0x800000, 0x400000, 0x200000, 0x100000,
0x80000, 0x40000, 0x20000, 0x10000,
0x8000, 0x4000, 0x2000, 0x1000,
0x800, 0x400, 0x200, 0x100,
0x80, 0x40, 0x20, 0x10,
0x8, 0x4, 0x2, 0x1
};
/*
* Use the key schedule specified in the Standard (ANSI X3.92-1981).
*/
static byte[] pc1 =
{
56, 48, 40, 32, 24, 16, 8, 0, 57, 49, 41, 33, 25, 17,
9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35,
62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21,
13, 5, 60, 52, 44, 36, 28, 20, 12, 4, 27, 19, 11, 3
};
static byte[] totrot =
{
1, 2, 4, 6, 8, 10, 12, 14,
15, 17, 19, 21, 23, 25, 27, 28
};
static byte[] pc2 =
{
13, 16, 10, 23, 0, 4, 2, 27, 14, 5, 20, 9,
22, 18, 11, 3, 25, 7, 15, 6, 26, 19, 12, 1,
40, 51, 30, 36, 46, 54, 29, 39, 50, 44, 32, 47,
43, 48, 38, 55, 33, 52, 45, 41, 49, 35, 28, 31
};
static int[] SP1 = {
0x01010400, 0x00000000, 0x00010000, 0x01010404,
0x01010004, 0x00010404, 0x00000004, 0x00010000,
0x00000400, 0x01010400, 0x01010404, 0x00000400,
0x01000404, 0x01010004, 0x01000000, 0x00000004,
0x00000404, 0x01000400, 0x01000400, 0x00010400,
0x00010400, 0x01010000, 0x01010000, 0x01000404,
0x00010004, 0x01000004, 0x01000004, 0x00010004,
0x00000000, 0x00000404, 0x00010404, 0x01000000,
0x00010000, 0x01010404, 0x00000004, 0x01010000,
0x01010400, 0x01000000, 0x01000000, 0x00000400,
0x01010004, 0x00010000, 0x00010400, 0x01000004,
0x00000400, 0x00000004, 0x01000404, 0x00010404,
0x01010404, 0x00010004, 0x01010000, 0x01000404,
0x01000004, 0x00000404, 0x00010404, 0x01010400,
0x00000404, 0x01000400, 0x01000400, 0x00000000,
0x00010004, 0x00010400, 0x00000000, 0x01010004
};
static int[] SP2 = {
0x80108020, 0x80008000, 0x00008000, 0x00108020,
0x00100000, 0x00000020, 0x80100020, 0x80008020,
0x80000020, 0x80108020, 0x80108000, 0x80000000,
0x80008000, 0x00100000, 0x00000020, 0x80100020,
0x00108000, 0x00100020, 0x80008020, 0x00000000,
0x80000000, 0x00008000, 0x00108020, 0x80100000,
0x00100020, 0x80000020, 0x00000000, 0x00108000,
0x00008020, 0x80108000, 0x80100000, 0x00008020,
0x00000000, 0x00108020, 0x80100020, 0x00100000,
0x80008020, 0x80100000, 0x80108000, 0x00008000,
0x80100000, 0x80008000, 0x00000020, 0x80108020,
0x00108020, 0x00000020, 0x00008000, 0x80000000,
0x00008020, 0x80108000, 0x00100000, 0x80000020,
0x00100020, 0x80008020, 0x80000020, 0x00100020,
0x00108000, 0x00000000, 0x80008000, 0x00008020,
0x80000000, 0x80100020, 0x80108020, 0x00108000
};
static int[] SP3 = {
0x00000208, 0x08020200, 0x00000000, 0x08020008,
0x08000200, 0x00000000, 0x00020208, 0x08000200,
0x00020008, 0x08000008, 0x08000008, 0x00020000,
0x08020208, 0x00020008, 0x08020000, 0x00000208,
0x08000000, 0x00000008, 0x08020200, 0x00000200,
0x00020200, 0x08020000, 0x08020008, 0x00020208,
0x08000208, 0x00020200, 0x00020000, 0x08000208,
0x00000008, 0x08020208, 0x00000200, 0x08000000,
0x08020200, 0x08000000, 0x00020008, 0x00000208,
0x00020000, 0x08020200, 0x08000200, 0x00000000,
0x00000200, 0x00020008, 0x08020208, 0x08000200,
0x08000008, 0x00000200, 0x00000000, 0x08020008,
0x08000208, 0x00020000, 0x08000000, 0x08020208,
0x00000008, 0x00020208, 0x00020200, 0x08000008,
0x08020000, 0x08000208, 0x00000208, 0x08020000,
0x00020208, 0x00000008, 0x08020008, 0x00020200
};
static int[] SP4 = {
0x00802001, 0x00002081, 0x00002081, 0x00000080,
0x00802080, 0x00800081, 0x00800001, 0x00002001,
0x00000000, 0x00802000, 0x00802000, 0x00802081,
0x00000081, 0x00000000, 0x00800080, 0x00800001,
0x00000001, 0x00002000, 0x00800000, 0x00802001,
0x00000080, 0x00800000, 0x00002001, 0x00002080,
0x00800081, 0x00000001, 0x00002080, 0x00800080,
0x00002000, 0x00802080, 0x00802081, 0x00000081,
0x00800080, 0x00800001, 0x00802000, 0x00802081,
0x00000081, 0x00000000, 0x00000000, 0x00802000,
0x00002080, 0x00800080, 0x00800081, 0x00000001,
0x00802001, 0x00002081, 0x00002081, 0x00000080,
0x00802081, 0x00000081, 0x00000001, 0x00002000,
0x00800001, 0x00002001, 0x00802080, 0x00800081,
0x00002001, 0x00002080, 0x00800000, 0x00802001,
0x00000080, 0x00800000, 0x00002000, 0x00802080
};
static int[] SP5 = {
0x00000100, 0x02080100, 0x02080000, 0x42000100,
0x00080000, 0x00000100, 0x40000000, 0x02080000,
0x40080100, 0x00080000, 0x02000100, 0x40080100,
0x42000100, 0x42080000, 0x00080100, 0x40000000,
0x02000000, 0x40080000, 0x40080000, 0x00000000,
0x40000100, 0x42080100, 0x42080100, 0x02000100,
0x42080000, 0x40000100, 0x00000000, 0x42000000,
0x02080100, 0x02000000, 0x42000000, 0x00080100,
0x00080000, 0x42000100, 0x00000100, 0x02000000,
0x40000000, 0x02080000, 0x42000100, 0x40080100,
0x02000100, 0x40000000, 0x42080000, 0x02080100,
0x40080100, 0x00000100, 0x02000000, 0x42080000,
0x42080100, 0x00080100, 0x42000000, 0x42080100,
0x02080000, 0x00000000, 0x40080000, 0x42000000,
0x00080100, 0x02000100, 0x40000100, 0x00080000,
0x00000000, 0x40080000, 0x02080100, 0x40000100
};
static int[] SP6 = {
0x20000010, 0x20400000, 0x00004000, 0x20404010,
0x20400000, 0x00000010, 0x20404010, 0x00400000,
0x20004000, 0x00404010, 0x00400000, 0x20000010,
0x00400010, 0x20004000, 0x20000000, 0x00004010,
0x00000000, 0x00400010, 0x20004010, 0x00004000,
0x00404000, 0x20004010, 0x00000010, 0x20400010,
0x20400010, 0x00000000, 0x00404010, 0x20404000,
0x00004010, 0x00404000, 0x20404000, 0x20000000,
0x20004000, 0x00000010, 0x20400010, 0x00404000,
0x20404010, 0x00400000, 0x00004010, 0x20000010,
0x00400000, 0x20004000, 0x20000000, 0x00004010,
0x20000010, 0x20404010, 0x00404000, 0x20400000,
0x00404010, 0x20404000, 0x00000000, 0x20400010,
0x00000010, 0x00004000, 0x20400000, 0x00404010,
0x00004000, 0x00400010, 0x20004010, 0x00000000,
0x20404000, 0x20000000, 0x00400010, 0x20004010
};
static int[] SP7 = {
0x00200000, 0x04200002, 0x04000802, 0x00000000,
0x00000800, 0x04000802, 0x00200802, 0x04200800,
0x04200802, 0x00200000, 0x00000000, 0x04000002,
0x00000002, 0x04000000, 0x04200002, 0x00000802,
0x04000800, 0x00200802, 0x00200002, 0x04000800,
0x04000002, 0x04200000, 0x04200800, 0x00200002,
0x04200000, 0x00000800, 0x00000802, 0x04200802,
0x00200800, 0x00000002, 0x04000000, 0x00200800,
0x04000000, 0x00200800, 0x00200000, 0x04000802,
0x04000802, 0x04200002, 0x04200002, 0x00000002,
0x00200002, 0x04000000, 0x04000800, 0x00200000,
0x04200800, 0x00000802, 0x00200802, 0x04200800,
0x00000802, 0x04000002, 0x04200802, 0x04200000,
0x00200800, 0x00000000, 0x00000002, 0x04200802,
0x00000000, 0x00200802, 0x04200000, 0x00000800,
0x04000002, 0x04000800, 0x00000800, 0x00200002
};
static int[] SP8 = {
0x10001040, 0x00001000, 0x00040000, 0x10041040,
0x10000000, 0x10001040, 0x00000040, 0x10000000,
0x00040040, 0x10040000, 0x10041040, 0x00041000,
0x10041000, 0x00041040, 0x00001000, 0x00000040,
0x10040000, 0x10000040, 0x10001000, 0x00001040,
0x00041000, 0x00040040, 0x10040040, 0x10041000,
0x00001040, 0x00000000, 0x00000000, 0x10040040,
0x10000040, 0x10001000, 0x00041040, 0x00040000,
0x00041040, 0x00040000, 0x10041000, 0x00001000,
0x00000040, 0x10040040, 0x00001000, 0x00041040,
0x10001000, 0x00000040, 0x10000040, 0x10040000,
0x10040040, 0x10000000, 0x00040000, 0x10001040,
0x00000000, 0x10041040, 0x00040040, 0x10000040,
0x10040000, 0x10001000, 0x10001040, 0x00000000,
0x10041040, 0x00041000, 0x00041000, 0x00001040,
0x00001040, 0x00040040, 0x10000000, 0x10041000
};
/**
* generate an integer based working key based on our secret key
* and what we processing we are planning to do.
*
* Acknowledgements for this routine go to James Gillogly & Phil Karn.
* (whoever, and wherever they are!).
*/
protected int[] generateWorkingKey(
boolean encrypting,
byte[] key)
{
int[] newKey = new int[32];
boolean[] pc1m = new boolean[56],
pcr = new boolean[56];
for (int j = 0; j < 56; j++ )
{
int l = pc1[j];
pc1m[j] = ((key[l >>> 3] & bytebit[l & 07]) != 0);
}
for (int i = 0; i < 16; i++)
{
int l, m, n;
if (encrypting)
{
m = i << 1;
}
else
{
m = (15 - i) << 1;
}
n = m + 1;
newKey[m] = newKey[n] = 0;
for (int j = 0; j < 28; j++)
{
l = j + totrot[i];
if ( l < 28 )
{
pcr[j] = pc1m[l];
}
else
{
pcr[j] = pc1m[l - 28];
}
}
for (int j = 28; j < 56; j++)
{
l = j + totrot[i];
if (l < 56 )
{
pcr[j] = pc1m[l];
}
else
{
pcr[j] = pc1m[l - 28];
}
}
for (int j = 0; j < 24; j++)
{
if (pcr[pc2[j]])
{
newKey[m] |= bigbyte[j];
}
if (pcr[pc2[j + 24]])
{
newKey[n] |= bigbyte[j];
}
}
}
//
// store the processed key
//
for (int i = 0; i != 32; i += 2)
{
int i1, i2;
i1 = newKey[i];
i2 = newKey[i + 1];
newKey[i] = ((i1 & 0x00fc0000) << 6) | ((i1 & 0x00000fc0) << 10)
| ((i2 & 0x00fc0000) >>> 10) | ((i2 & 0x00000fc0) >>> 6);
newKey[i + 1] = ((i1 & 0x0003f000) << 12) | ((i1 & 0x0000003f) << 16)
| ((i2 & 0x0003f000) >>> 4) | (i2 & 0x0000003f);
}
return newKey;
}
/**
* the DES engine.
*/
protected void desFunc(
int[] wKey,
byte[] in,
int inOff,
byte[] out,
int outOff)
{
int work, right, left;
left = (in[inOff + 0] & 0xff) << 24;
left |= (in[inOff + 1] & 0xff) << 16;
left |= (in[inOff + 2] & 0xff) << 8;
left |= (in[inOff + 3] & 0xff);
right = (in[inOff + 4] & 0xff) << 24;
right |= (in[inOff + 5] & 0xff) << 16;
right |= (in[inOff + 6] & 0xff) << 8;
right |= (in[inOff + 7] & 0xff);
work = ((left >>> 4) ^ right) & 0x0f0f0f0f;
right ^= work;
left ^= (work << 4);
work = ((left >>> 16) ^ right) & 0x0000ffff;
right ^= work;
left ^= (work << 16);
work = ((right >>> 2) ^ left) & 0x33333333;
left ^= work;
right ^= (work << 2);
work = ((right >>> 8) ^ left) & 0x00ff00ff;
left ^= work;
right ^= (work << 8);
right = ((right << 1) | ((right >>> 31) & 1)) & 0xffffffff;
work = (left ^ right) & 0xaaaaaaaa;
left ^= work;
right ^= work;
left = ((left << 1) | ((left >>> 31) & 1)) & 0xffffffff;
for (int round = 0; round < 8; round++)
{
int fval;
work = (right << 28) | (right >>> 4);
work ^= wKey[round * 4 + 0];
fval = SP7[ work & 0x3f];
fval |= SP5[(work >>> 8) & 0x3f];
fval |= SP3[(work >>> 16) & 0x3f];
fval |= SP1[(work >>> 24) & 0x3f];
work = right ^ wKey[round * 4 + 1];
fval |= SP8[ work & 0x3f];
fval |= SP6[(work >>> 8) & 0x3f];
fval |= SP4[(work >>> 16) & 0x3f];
fval |= SP2[(work >>> 24) & 0x3f];
left ^= fval;
work = (left << 28) | (left >>> 4);
work ^= wKey[round * 4 + 2];
fval = SP7[ work & 0x3f];
fval |= SP5[(work >>> 8) & 0x3f];
fval |= SP3[(work >>> 16) & 0x3f];
fval |= SP1[(work >>> 24) & 0x3f];
work = left ^ wKey[round * 4 + 3];
fval |= SP8[ work & 0x3f];
fval |= SP6[(work >>> 8) & 0x3f];
fval |= SP4[(work >>> 16) & 0x3f];
fval |= SP2[(work >>> 24) & 0x3f];
right ^= fval;
}
right = (right << 31) | (right >>> 1);
work = (left ^ right) & 0xaaaaaaaa;
left ^= work;
right ^= work;
left = (left << 31) | (left >>> 1);
work = ((left >>> 8) ^ right) & 0x00ff00ff;
right ^= work;
left ^= (work << 8);
work = ((left >>> 2) ^ right) & 0x33333333;
right ^= work;
left ^= (work << 2);
work = ((right >>> 16) ^ left) & 0x0000ffff;
left ^= work;
right ^= (work << 16);
work = ((right >>> 4) ^ left) & 0x0f0f0f0f;
left ^= work;
right ^= (work << 4);
out[outOff + 0] = (byte)((right >>> 24) & 0xff);
out[outOff + 1] = (byte)((right >>> 16) & 0xff);
out[outOff + 2] = (byte)((right >>> 8) & 0xff);
out[outOff + 3] = (byte)( right & 0xff);
out[outOff + 4] = (byte)((left >>> 24) & 0xff);
out[outOff + 5] = (byte)((left >>> 16) & 0xff);
out[outOff + 6] = (byte)((left >>> 8) & 0xff);
out[outOff + 7] = (byte)( left & 0xff);
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/util/MD5Digest.java 0000644 0001750 0001750 00000024565 11316672660 025557 0 ustar martin martin /******************************************************************************
* Copyright (c) 2000 The Legion Of The Bouncy Castle (http://www.bouncycastle.org)
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
******************************************************************************/
package net.sourceforge.jtds.util;
/**
* implementation of MD5 as outlined in "Handbook of Applied Cryptography", pages 346 - 347.
*/
public class MD5Digest
extends GeneralDigest
{
private static final int DIGEST_LENGTH = 16;
private int H1, H2, H3, H4; // IV's
private int[] X = new int[16];
private int xOff;
/**
* Standard constructor
*/
public MD5Digest()
{
reset();
}
/**
* Copy constructor. This will copy the state of the provided
* message digest.
*/
public MD5Digest(MD5Digest t)
{
super(t);
H1 = t.H1;
H2 = t.H2;
H3 = t.H3;
H4 = t.H4;
System.arraycopy(t.X, 0, X, 0, t.X.length);
xOff = t.xOff;
}
public String getAlgorithmName()
{
return "MD5";
}
public int getDigestSize()
{
return DIGEST_LENGTH;
}
protected void processWord(
byte[] in,
int inOff)
{
X[xOff++] = (in[inOff] & 0xff) | ((in[inOff + 1] & 0xff) << 8)
| ((in[inOff + 2] & 0xff) << 16) | ((in[inOff + 3] & 0xff) << 24);
if (xOff == 16)
{
processBlock();
}
}
protected void processLength(
long bitLength)
{
if (xOff > 14)
{
processBlock();
}
X[14] = (int)(bitLength & 0xffffffff);
X[15] = (int)(bitLength >>> 32);
}
private void unpackWord(
int word,
byte[] out,
int outOff)
{
out[outOff] = (byte)word;
out[outOff + 1] = (byte)(word >>> 8);
out[outOff + 2] = (byte)(word >>> 16);
out[outOff + 3] = (byte)(word >>> 24);
}
public int doFinal(
byte[] out,
int outOff)
{
finish();
unpackWord(H1, out, outOff);
unpackWord(H2, out, outOff + 4);
unpackWord(H3, out, outOff + 8);
unpackWord(H4, out, outOff + 12);
reset();
return DIGEST_LENGTH;
}
/**
* reset the chaining variables to the IV values.
*/
public void reset()
{
super.reset();
H1 = 0x67452301;
H2 = 0xefcdab89;
H3 = 0x98badcfe;
H4 = 0x10325476;
xOff = 0;
for (int i = 0; i != X.length; i++)
{
X[i] = 0;
}
}
//
// round 1 left rotates
//
private static final int S11 = 7;
private static final int S12 = 12;
private static final int S13 = 17;
private static final int S14 = 22;
//
// round 2 left rotates
//
private static final int S21 = 5;
private static final int S22 = 9;
private static final int S23 = 14;
private static final int S24 = 20;
//
// round 3 left rotates
//
private static final int S31 = 4;
private static final int S32 = 11;
private static final int S33 = 16;
private static final int S34 = 23;
//
// round 4 left rotates
//
private static final int S41 = 6;
private static final int S42 = 10;
private static final int S43 = 15;
private static final int S44 = 21;
/*
* rotate int x left n bits.
*/
private int rotateLeft(
int x,
int n)
{
return (x << n) | (x >>> (32 - n));
}
/*
* F, G, H and I are the basic MD5 functions.
*/
private int F(
int u,
int v,
int w)
{
return (u & v) | (~u & w);
}
private int G(
int u,
int v,
int w)
{
return (u & w) | (v & ~w);
}
private int H(
int u,
int v,
int w)
{
return u ^ v ^ w;
}
private int K(
int u,
int v,
int w)
{
return v ^ (u | ~w);
}
protected void processBlock()
{
int a = H1;
int b = H2;
int c = H3;
int d = H4;
//
// Round 1 - F cycle, 16 times.
//
a = rotateLeft(a + F(b, c, d) + X[ 0] + 0xd76aa478, S11) + b;
d = rotateLeft(d + F(a, b, c) + X[ 1] + 0xe8c7b756, S12) + a;
c = rotateLeft(c + F(d, a, b) + X[ 2] + 0x242070db, S13) + d;
b = rotateLeft(b + F(c, d, a) + X[ 3] + 0xc1bdceee, S14) + c;
a = rotateLeft(a + F(b, c, d) + X[ 4] + 0xf57c0faf, S11) + b;
d = rotateLeft(d + F(a, b, c) + X[ 5] + 0x4787c62a, S12) + a;
c = rotateLeft(c + F(d, a, b) + X[ 6] + 0xa8304613, S13) + d;
b = rotateLeft(b + F(c, d, a) + X[ 7] + 0xfd469501, S14) + c;
a = rotateLeft(a + F(b, c, d) + X[ 8] + 0x698098d8, S11) + b;
d = rotateLeft(d + F(a, b, c) + X[ 9] + 0x8b44f7af, S12) + a;
c = rotateLeft(c + F(d, a, b) + X[10] + 0xffff5bb1, S13) + d;
b = rotateLeft(b + F(c, d, a) + X[11] + 0x895cd7be, S14) + c;
a = rotateLeft(a + F(b, c, d) + X[12] + 0x6b901122, S11) + b;
d = rotateLeft(d + F(a, b, c) + X[13] + 0xfd987193, S12) + a;
c = rotateLeft(c + F(d, a, b) + X[14] + 0xa679438e, S13) + d;
b = rotateLeft(b + F(c, d, a) + X[15] + 0x49b40821, S14) + c;
//
// Round 2 - G cycle, 16 times.
//
a = rotateLeft(a + G(b, c, d) + X[ 1] + 0xf61e2562, S21) + b;
d = rotateLeft(d + G(a, b, c) + X[ 6] + 0xc040b340, S22) + a;
c = rotateLeft(c + G(d, a, b) + X[11] + 0x265e5a51, S23) + d;
b = rotateLeft(b + G(c, d, a) + X[ 0] + 0xe9b6c7aa, S24) + c;
a = rotateLeft(a + G(b, c, d) + X[ 5] + 0xd62f105d, S21) + b;
d = rotateLeft(d + G(a, b, c) + X[10] + 0x02441453, S22) + a;
c = rotateLeft(c + G(d, a, b) + X[15] + 0xd8a1e681, S23) + d;
b = rotateLeft(b + G(c, d, a) + X[ 4] + 0xe7d3fbc8, S24) + c;
a = rotateLeft(a + G(b, c, d) + X[ 9] + 0x21e1cde6, S21) + b;
d = rotateLeft(d + G(a, b, c) + X[14] + 0xc33707d6, S22) + a;
c = rotateLeft(c + G(d, a, b) + X[ 3] + 0xf4d50d87, S23) + d;
b = rotateLeft(b + G(c, d, a) + X[ 8] + 0x455a14ed, S24) + c;
a = rotateLeft(a + G(b, c, d) + X[13] + 0xa9e3e905, S21) + b;
d = rotateLeft(d + G(a, b, c) + X[ 2] + 0xfcefa3f8, S22) + a;
c = rotateLeft(c + G(d, a, b) + X[ 7] + 0x676f02d9, S23) + d;
b = rotateLeft(b + G(c, d, a) + X[12] + 0x8d2a4c8a, S24) + c;
//
// Round 3 - H cycle, 16 times.
//
a = rotateLeft(a + H(b, c, d) + X[ 5] + 0xfffa3942, S31) + b;
d = rotateLeft(d + H(a, b, c) + X[ 8] + 0x8771f681, S32) + a;
c = rotateLeft(c + H(d, a, b) + X[11] + 0x6d9d6122, S33) + d;
b = rotateLeft(b + H(c, d, a) + X[14] + 0xfde5380c, S34) + c;
a = rotateLeft(a + H(b, c, d) + X[ 1] + 0xa4beea44, S31) + b;
d = rotateLeft(d + H(a, b, c) + X[ 4] + 0x4bdecfa9, S32) + a;
c = rotateLeft(c + H(d, a, b) + X[ 7] + 0xf6bb4b60, S33) + d;
b = rotateLeft(b + H(c, d, a) + X[10] + 0xbebfbc70, S34) + c;
a = rotateLeft(a + H(b, c, d) + X[13] + 0x289b7ec6, S31) + b;
d = rotateLeft(d + H(a, b, c) + X[ 0] + 0xeaa127fa, S32) + a;
c = rotateLeft(c + H(d, a, b) + X[ 3] + 0xd4ef3085, S33) + d;
b = rotateLeft(b + H(c, d, a) + X[ 6] + 0x04881d05, S34) + c;
a = rotateLeft(a + H(b, c, d) + X[ 9] + 0xd9d4d039, S31) + b;
d = rotateLeft(d + H(a, b, c) + X[12] + 0xe6db99e5, S32) + a;
c = rotateLeft(c + H(d, a, b) + X[15] + 0x1fa27cf8, S33) + d;
b = rotateLeft(b + H(c, d, a) + X[ 2] + 0xc4ac5665, S34) + c;
//
// Round 4 - K cycle, 16 times.
//
a = rotateLeft(a + K(b, c, d) + X[ 0] + 0xf4292244, S41) + b;
d = rotateLeft(d + K(a, b, c) + X[ 7] + 0x432aff97, S42) + a;
c = rotateLeft(c + K(d, a, b) + X[14] + 0xab9423a7, S43) + d;
b = rotateLeft(b + K(c, d, a) + X[ 5] + 0xfc93a039, S44) + c;
a = rotateLeft(a + K(b, c, d) + X[12] + 0x655b59c3, S41) + b;
d = rotateLeft(d + K(a, b, c) + X[ 3] + 0x8f0ccc92, S42) + a;
c = rotateLeft(c + K(d, a, b) + X[10] + 0xffeff47d, S43) + d;
b = rotateLeft(b + K(c, d, a) + X[ 1] + 0x85845dd1, S44) + c;
a = rotateLeft(a + K(b, c, d) + X[ 8] + 0x6fa87e4f, S41) + b;
d = rotateLeft(d + K(a, b, c) + X[15] + 0xfe2ce6e0, S42) + a;
c = rotateLeft(c + K(d, a, b) + X[ 6] + 0xa3014314, S43) + d;
b = rotateLeft(b + K(c, d, a) + X[13] + 0x4e0811a1, S44) + c;
a = rotateLeft(a + K(b, c, d) + X[ 4] + 0xf7537e82, S41) + b;
d = rotateLeft(d + K(a, b, c) + X[11] + 0xbd3af235, S42) + a;
c = rotateLeft(c + K(d, a, b) + X[ 2] + 0x2ad7d2bb, S43) + d;
b = rotateLeft(b + K(c, d, a) + X[ 9] + 0xeb86d391, S44) + c;
H1 += a;
H2 += b;
H3 += c;
H4 += d;
//
// reset the offset and clean out the word buffer.
//
xOff = 0;
for (int i = 0; i != X.length; i++)
{
X[i] = 0;
}
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/util/SSPIJNIClient.java 0000644 0001750 0001750 00000011011 11316672660 026266 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.util;
import java.sql.SQLException;
/**
* A JNI client to SSPI based CPP program (DLL) that returns the user
* credentials for NTLM authentication.
*
byte[].
*/
private native byte[] prepareSSORequest();
/**
* Prepares the NTLM TYPE-3 message using the current user's credentials.
*
* It needs the challenge BLOB and it's size as input. The challenge BLOB
* is nothig but the TYPE-2 message that is received from the SQL Server.
*
* @param buf challenge BLOB
* @param size challenge BLOB size
* @return NTLM TYPE-3 message
*/
private native byte[] prepareSSOSubmit(byte[] buf, long size);
static {
try {
System.loadLibrary("ntlmauth");
SSPIJNIClient.libraryLoaded = true;
} catch (UnsatisfiedLinkError err) {
Logger.println("Unable to load library: " + err);
}
}
/**
* Private constructor for singleton.
*/
private SSPIJNIClient() {
//empty constructor
}
/**
* Returns the singleton SSPIJNIClient instance.
*
* @throws SQLException if an error occurs during initialization
*/
public static SSPIJNIClient getInstance() throws Exception {
if (thisInstance == null) {
if (!libraryLoaded) {
throw new Exception("Native SSPI library not loaded. "
+ "Check the java.library.path system property.");
}
thisInstance = new SSPIJNIClient();
thisInstance.invokeInitialize();
}
return thisInstance;
}
/**
* Calls #initialize() if the SSPI client is not already inited.
*/
public void invokeInitialize() {
if (!initialized) {
initialize();
initialized = true;
}
}
/**
* Calls #unInitialize() if the SSPI client is inited.
*/
public void invokeUnInitialize() {
if (initialized) {
unInitialize();
initialized = false;
}
}
/**
* Calls #prepareSSORequest() to prepare the NTLM TYPE-1 message.
*
* @throws Exception if an error occurs during the call or the SSPI client
* is uninitialized
*/
public byte[] invokePrepareSSORequest() throws Exception {
if (!initialized) {
throw new Exception("SSPI Not Initialized");
}
return prepareSSORequest();
}
/**
* Calls #prepareSSOSubmit(byte[], long) to prepare the NTLM TYPE-3
* message.
*
* @throws Exception if an error occurs during the call or the SSPI client
* is uninitialized
*/
public byte[] invokePrepareSSOSubmit(byte[] buf) throws Exception {
if (!initialized) {
throw new Exception("SSPI Not Initialized");
}
return prepareSSOSubmit(buf, buf.length);
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/util/BlobBuffer.java 0000644 0001750 0001750 00000125575 11316672660 026045 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.util;
import java.io.*;
import java.sql.SQLException;
import net.sourceforge.jtds.jdbc.Messages;
/**
* Manages a buffer (backed by optional disk storage) for use as a data store
* by the CLOB and BLOB objects.
*
lobBuffer URL property after which it will be
* written to disk. The disk array is accessed randomly one page (1024 bytes)
* at a time.
*
* This class is not synchronized and concurrent open input and output
* streams can conflict.
*
* Tuning hints:
* PAGE_SIZE governs how much data is buffered when
* reading or writing data a byte at a time. 1024 bytes seems to work well
* but if very large objects are being written a byte at a time 4096 may be
* better. NB. ensure that the PAGE_MASK and
* BYTE_MASK fields are also adjusted to match.
* MAX_BUF_INC value. Every time the buffer is
* expanded the existing contents are copied and this may get expensive
* with very large BLOBs.
* int or -1 if at EOF
* @throws IOException if an I/O error occurs
*/
public int read(int readPtr) throws IOException {
if (readPtr >= length) {
// At end of file.
return -1;
}
if (raFile != null) {
// Paged storage as a file exists
if (currentPage != (readPtr & PAGE_MASK)) {
// Requested page not in memory so read it
readPage(readPtr);
}
// Use the byte offset to return the correct
// byte from the page.
return buffer[readPtr & BYTE_MASK] & 0xFF;
} else {
// In memory buffer just return byte.
return buffer[readPtr] & 0xFF;
}
}
/**
* Reads bytes from the BLOB buffer at the specified location.
*
* @param readPtr the offset in the buffer of the required byte
* @param bytes the byte array to fill
* @param offset the start position in the byte array
* @param len the number of bytes to read
* @return the number of bytes read or -1 if at end of file
* @throws IOException if an I/O error occurs
*/
public int read(int readPtr, byte[] bytes, int offset, int len)
throws IOException {
// Validate parameters
if (bytes == null) {
throw new NullPointerException();
} else if ((offset < 0) || (offset > bytes.length) || (len < 0)
|| ((offset + len) > bytes.length) || ((offset + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;
}
if (readPtr >= length) {
// At end of file
return -1;
}
if (raFile != null) {
// Need to read from disk file
len = Math.min(length - readPtr, len);
if (len >= PAGE_SIZE) {
// This is a big write so we optimize by reading directly
// from the RA File.
if (bufferDirty) {
writePage(currentPage);
}
currentPage = INVALID_PAGE;
raFile.seek(readPtr);
raFile.readFully(bytes, offset, len);
} else {
//
// Partial read so buffer locally
//
int count = len;
while (count > 0) {
if (currentPage != (readPtr & PAGE_MASK)) {
// Requested page not in memory so read it
readPage(readPtr);
}
int inBuffer = Math.min(PAGE_SIZE - (readPtr & BYTE_MASK), count);
System.arraycopy(buffer, readPtr & BYTE_MASK, bytes, offset, inBuffer);
offset += inBuffer;
readPtr += inBuffer;
count -= inBuffer;
}
}
} else {
// In memory buffer
len = Math.min(length - readPtr, len);
System.arraycopy(buffer, readPtr, bytes, offset, len);
}
return len;
}
/**
* Inserts a byte into the buffer at the specified location.
*
* The write pointer is partitioned into a page number and an offset within
* the page. This routine will write new pages as required. The page size
* must be a power of 2 and is currently set to 1024 bytes.
*
* @param writePtr the offset in the buffer of the required byte
* @param b the byte value to write
* @throws IOException if an I/O error occurs
*/
public void write(int writePtr, int b) throws IOException {
if (writePtr >= length) {
if (writePtr > length) {
// Probably because the user called truncate at
// the same time as writing to the blob!
throw new IOException("BLOB buffer has been truncated");
}
// We are writing beyond the current length
// of the buffer and need to update the total length.
if (++length < 0) {
// We have wrapped 31 bits!
// This should ensure that the disk file is limited to 2GB.
// If in memory JVM will probably have failed by now anyway.
throw new IOException("BLOB may not exceed 2GB in size");
}
}
if (raFile != null) {
// OK we have a disk based buffer
if (currentPage != (writePtr & PAGE_MASK)) {
// The page we need is not in memory
readPage(writePtr);
}
buffer[writePtr & BYTE_MASK] = (byte) b;
// Ensure change will saved if buffer is replaced
bufferDirty = true;
} else {
// In memory buffer only (only used here if disk unavailable
if (writePtr >= buffer.length) {
growBuffer(writePtr + 1);
}
buffer[writePtr] = (byte) b;
}
}
/**
* Inserts bytes into the buffer at the specified location.
*
* @param writePtr the offset in the buffer of the required byte
* @param bytes the byte array value to write
* @param offset the start position in the byte array
* @param len the number of bytes to write
* @throws IOException if an I/O error occurs
*/
void write(int writePtr, byte[] bytes, int offset, int len)
throws IOException {
// Validate parameters
if (bytes == null) {
throw new NullPointerException();
} else if ((offset < 0) || (offset > bytes.length) || (len < 0) ||
((offset + len) > bytes.length) || ((offset + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return;
}
if ((long) writePtr + len > (long) Integer.MAX_VALUE) {
throw new IOException("BLOB may not exceed 2GB in size");
}
if (writePtr > length) {
// Probably because the user called truncate at
// the same time as writing to the blob!
throw new IOException("BLOB buffer has been truncated");
}
if (raFile != null) {
// dealing with disk storage (normal case)
//
if (len >= PAGE_SIZE) {
// This is a big write so we optimize by writing directly
// to the RA File.
if (bufferDirty) {
writePage(currentPage);
}
currentPage = INVALID_PAGE;
raFile.seek(writePtr);
raFile.write(bytes, offset, len);
writePtr += len;
} else {
// Small writes so use the page buffer for
// effeciency.
int count = len;
while (count > 0) {
// Paged storage as a file exists
if (currentPage != (writePtr & PAGE_MASK)) {
// Requested page not in memory so read it
readPage(writePtr);
}
int inBuffer = Math.min(
PAGE_SIZE - (writePtr & BYTE_MASK), count);
System.arraycopy(bytes, offset, buffer,
writePtr & BYTE_MASK, inBuffer);
bufferDirty = true;
offset += inBuffer;
writePtr += inBuffer;
count -= inBuffer;
}
}
} else {
// In memory (only used here if disk not available)
if (writePtr + len > buffer.length) {
growBuffer(writePtr + len);
}
System.arraycopy(bytes, offset, buffer, writePtr, len);
writePtr += len;
}
if (writePtr > length) {
length = writePtr;
}
}
/**
* Reads in the specified page from the disk buffer.
*
* Any existing dirty page is first saved to disk.
*
* @param page the page number
* @throws IOException if an I/O error occurs
*/
public void readPage(int page) throws IOException {
page = page & PAGE_MASK;
if (bufferDirty) {
writePage(currentPage);
}
if (page > raFile.length()) {
throw new IOException("readPage: Invalid page number " + page);
}
currentPage = page;
// Locate and read requested page
// NB. Page may not be completely filled.
raFile.seek(currentPage);
// Repeat reading until buffer is filled or EOF is reached
int count = 0, res;
do {
res = raFile.read(buffer, count, buffer.length - count);
count += (res == -1) ? 0 : res;
} while (count < PAGE_SIZE && res != -1);
}
/**
* Writes the specified page to the disk buffer.
*
* @param page the page number
* @throws IOException if an I/O error occurs
*/
public void writePage(int page) throws IOException {
page = page & PAGE_MASK;
if (page > raFile.length()) {
throw new IOException("writePage: Invalid page number " + page);
}
if (buffer.length != PAGE_SIZE) {
throw new IllegalStateException("writePage: buffer size invalid");
}
raFile.seek(page);
raFile.write(buffer);
bufferDirty = false;
}
/**
* Logically closes the file or physically close it if the open count is
* now zero.
*
* Any updated buffer in memory is flushed to disk before the file is
* closed.
*
* @throws IOException if an I/O error occurs
*/
public void close() throws IOException {
if (openCount > 0) {
if (--openCount == 0 && raFile != null) {
if (bufferDirty) {
writePage(currentPage);
}
raFile.close();
raFile = null;
// Allow buffer to be garbage collected
buffer = EMPTY_BUFFER;
currentPage = INVALID_PAGE;
}
}
}
/**
* Increases the size of the in memory buffer for situations where disk
* storage of BLOB is not possible.
*
* @param minSize the minimum size of buffer required
*/
public void growBuffer(int minSize) {
if (buffer.length == 0) {
// Assign initial buffer
buffer = new byte[Math.max(PAGE_SIZE, minSize)];
} else {
byte[] tmp;
if (buffer.length * 2 > minSize && buffer.length <= MAX_BUF_INC) {
tmp = new byte[buffer.length * 2];
} else {
tmp = new byte[minSize + MAX_BUF_INC];
}
// Copy over existing data
System.arraycopy(buffer, 0, tmp, 0, buffer.length);
buffer = tmp; // Assign new buffer.
}
}
/**
* Sets the initial buffer to an existing byte array.
*
* @param bytes the byte array containing the BLOB data
* @param copy true if a local copy of the data is required
*/
public void setBuffer(byte[] bytes, boolean copy) {
if (copy) {
this.buffer = new byte[bytes.length];
System.arraycopy(bytes, 0, this.buffer, 0, buffer.length);
} else {
this.buffer = bytes;
}
this.length = buffer.length;
}
//
// ---- Inner classes implementing the various input/output stream classes ---
//
/**
* An InputStream over the BLOB buffer.
*/
private class BlobInputStream extends InputStream {
private int readPtr;
private boolean open;
/**
* Costructs an InputStream object over the BLOB buffer.
*
* @param pos the starting position (from 0)
* @throws IOException if an I/O error occurs
*/
public BlobInputStream(long pos) throws IOException {
BlobBuffer.this.open();
open = true;
readPtr = (int) pos;
}
/**
* Ensures underlying BLOB file can be closed even if user does not
* close this stream.
*/
protected void finalize() throws Throwable {
if (open) {
try {
close();
} catch (IOException e) {
// Ignore closing anyway
} finally {
super.finalize();
}
}
}
/**
* Returns the number of bytes available to read.
*
* @throws IOException if an I/O error occurs
*/
public int available() throws IOException {
return (int) BlobBuffer.this.getLength() - readPtr;
}
/**
* Reads the next byte from the stream.
*
* @return the next byte as an int or -1 if at EOF
* @throws IOException if an I/O error occurs
*/
public int read() throws IOException {
int b = BlobBuffer.this.read(readPtr);
if (b >= 0) {
readPtr++;
}
return b;
}
/**
* Reads a bytes from the stream.
*
* @param bytes the byte array to fill
* @param offset the start position in the byte array
* @param len the number of bytes to read
* @return the number of bytes read or -1 if at end of file
* @throws IOException if an I/O error occurs
*/
public int read(byte[] bytes, int offset, int len) throws IOException {
int b = BlobBuffer.this.read(readPtr, bytes, offset, len);
if (b > 0) {
readPtr += b;
}
return b;
}
/**
* Closes the output stream.
*
* @throws IOException if an I/O error occurs
*/
public void close() throws IOException {
if (open) {
BlobBuffer.this.close();
open = false;
}
}
}
/**
* A Big Endian Unicode InputStream over the CLOB buffer.
*/
private class UnicodeInputStream extends InputStream {
private int readPtr;
private boolean open;
/**
* Costructs an InputStream object over the BLOB buffer.
*
* @param pos the starting position (from 0)
* @throws IOException if an I/O error occurs
*/
public UnicodeInputStream(long pos) throws IOException {
BlobBuffer.this.open();
open = true;
readPtr = (int) pos;
}
/**
* Ensures underlying BLOB file can be closed even if user does not
* close this stream.
*/
protected void finalize() throws Throwable {
if (open) {
try {
close();
} catch (IOException e) {
// Ignore closing anyway
} finally {
super.finalize();
}
}
}
/**
* Returns the number of bytes available to read.
*
* @throws IOException if an I/O error occurs
*/
public int available() throws IOException {
return (int) BlobBuffer.this.getLength() - readPtr;
}
/**
* Reads the next byte from the stream.
*
* @return the next byte as an int or -1 if at EOF
* @throws IOException if an I/O error occurs
*/
public int read() throws IOException {
//
// The XOR of 1 with the readPtr forces the bytes to be returned
// in big endian order.
//
int b = BlobBuffer.this.read(readPtr ^ 1);
if (b >= 0) {
readPtr++;
}
return b;
}
/**
* Close the output stream.
*
* @throws IOException if an I/O error occurs
*/
public void close() throws IOException {
if (open) {
BlobBuffer.this.close();
open = false;
}
}
}
/**
* An ASCII InputStream over the CLOB buffer.
*
* This class interprets ASCII as anything which has a value below 0x80.
* This is more rigid than other drivers which allow any character below
* 0x100 to be converted to returned. The more relaxed coding is useful
* when dealing with most single byte character sets and if this behaviour
* is desired, comment out the line indicated in the read method.
*/
private class AsciiInputStream extends InputStream {
private int readPtr;
private boolean open;
/**
* Costructs an InputStream object over the BLOB buffer.
*
* @param pos the starting position (from 0)
* @throws IOException if an I/O error occurs
*/
public AsciiInputStream(long pos) throws IOException {
BlobBuffer.this.open();
open = true;
readPtr = (int) pos;
}
/**
* Ensures underlying BLOB file can be closed even if user does not
* close this stream.
*/
protected void finalize() throws Throwable {
if (open) {
try {
close();
} catch (IOException e) {
// Ignore closing anyway
} finally {
super.finalize();
}
}
}
/**
* Returns the number of bytes available to read.
*
* @throws IOException if an I/O error occurs
*/
public int available() throws IOException {
return ((int) BlobBuffer.this.getLength() - readPtr) / 2;
}
/**
* Read the next byte from the stream.
*
* @return the next byte as an int or -1 if at EOF
* @throws IOException if an I/O error occurs
*/
public int read() throws IOException {
int b1 = BlobBuffer.this.read(readPtr);
if (b1 >= 0) {
readPtr++;
int b2 = BlobBuffer.this.read(readPtr);
if (b2 >= 0) {
readPtr++;
if (b2 != 0
|| b1 > 0x7F // Comment out this line for a more
// permissive interpretation of 'ASCII'.
) {
b1 = '?'; // Not ASCII set to '?'
}
return b1;
}
}
return -1;
}
/**
* Closes the output stream.
*
* @throws IOException if an I/O error occurs
*/
public void close() throws IOException {
if (open) {
BlobBuffer.this.close();
open = false;
}
}
}
/**
* Implements an OutputStream for BLOB data.
*/
private class BlobOutputStream extends OutputStream {
private int writePtr;
private boolean open;
/**
* Costructs an OutputStream object over the BLOB buffer.
*
* @param pos the starting position (from 0)
* @throws IOException if an I/O error occurs
*/
BlobOutputStream(long pos) throws IOException {
BlobBuffer.this.open();
open = true;
writePtr = (int) pos;
}
/**
* Ensures underlying BLOB file can be closed even if user does not
* close this stream.
*/
protected void finalize() throws Throwable {
if (open) {
try {
close();
} catch (IOException e) {
// Ignore closing anyway
} finally {
super.finalize();
}
}
}
/**
* Write a byte to the BLOB buffer.
*
* @param b the byte value to write
* @throws IOException if an I/O error occurs
*/
public void write(int b) throws IOException {
BlobBuffer.this.write(writePtr++, b);
}
/**
* Write bytes to the BLOB buffer.
*
* @param bytes the byte array value to write
* @param offset the start position in the byte array
* @param len the number of bytes to write
* @throws IOException if an I/O error occurs
*/
public void write(byte[] bytes, int offset, int len) throws IOException {
BlobBuffer.this.write(writePtr, bytes, offset, len);
writePtr += len;
}
/**
* Close the output stream.
*
* @throws IOException if an I/O error occurs
*/
public void close() throws IOException {
if (open) {
BlobBuffer.this.close();
open = false;
}
}
}
/**
* Implements an ASCII OutputStream for CLOB data.
*/
private class AsciiOutputStream extends OutputStream {
private int writePtr;
private boolean open;
/**
* Costructs an ASCII OutputStream object over the BLOB
* buffer.
*
* @param pos the starting position (from 0)
* @throws IOException if an I/O error occurs
*/
AsciiOutputStream(long pos) throws IOException {
BlobBuffer.this.open();
open = true;
writePtr = (int) pos;
}
/**
* Ensures underlying BLOB file can be closed even if user does not
* close this stream.
*/
protected void finalize() throws Throwable {
if (open) {
try {
close();
} catch (IOException e) {
// Ignore closing anyway
} finally {
super.finalize();
}
}
}
/**
* Writes a byte to the BLOB buffer.
*
* @param b the byte value to write
* @throws IOException if an I/O error occurs
*/
public void write(int b) throws IOException {
BlobBuffer.this.write(writePtr++, b);
BlobBuffer.this.write(writePtr++, 0);
}
/**
* Closes the output stream.
*
* @throws IOException if an I/O error occurs
*/
public void close() throws IOException {
if (open) {
BlobBuffer.this.close();
open = false;
}
}
}
//
// ---- Support methods for CLOB/BLOB ----
//
/**
* Returns the BLOB data as a byte array.
*
* @param pos the start position in the BLOB buffer (from 1)
* @param len the number of bytes to copy
* @return the requested data as a byte[]
*/
public byte[] getBytes(long pos, int len) throws SQLException {
pos--;
if (pos < 0) {
throw new SQLException(Messages.get("error.blobclob.badpos"), "HY090");
}
if (pos > this.length) {
throw new SQLException(Messages.get("error.blobclob.badposlen"), "HY090");
}
if (len < 0) {
throw new SQLException(Messages.get("error.blobclob.badlen"), "HY090");
}
if (pos + len > this.length) {
// Don't throw an exception, just return as much data as available
len = (int) (this.length - pos);
}
try {
// Should not do this. It could cause trouble.
// if (pos == 0 && len == buffer.length && blobFile == null) {
// // There is no file and we do not need a subset of the data.
// // We should copy the buffer as the user may modify its
// // contents but this would be wasteful in most cases.
// return buffer;
// }
// We do need a subset or we are reading from the file
byte[] data = new byte[len];
if (blobFile == null) {
// Just copy subset from memory buffer
System.arraycopy(buffer, (int) (pos), data, 0, len);
} else {
// Copy data from disk buffer
InputStream is = new BlobInputStream(pos);
int bc = is.read(data);
is.close();
if (bc != data.length) {
throw new IOException("Unexpected EOF on BLOB data file bc=" +
bc + " data.len=" + data.length);
}
}
return data;
} catch (IOException e) {
throw new SQLException(Messages.get("error.generic.ioerror", e.getMessage()),
"HY000");
}
}
/**
* Retrieve the BLOB data as an InputStream.
*
* @param ascii true if an ASCII input stream should be returned
* @return the InputStream built over the BLOB data
* @throws SQLException if an error occurs
*/
public InputStream getBinaryStream(boolean ascii) throws SQLException {
try {
if (ascii) {
return new AsciiInputStream(0);
} else {
return new BlobInputStream(0);
}
} catch (IOException e) {
throw new SQLException(Messages.get("error.generic.ioerror",
e.getMessage()),
"HY000");
}
}
/**
* Retrieve the BLOB data as an Big Endian Unicode
* InputStream.
*
* @return the InputStream built over the BLOB data
* @throws SQLException if an error occurs
*/
public InputStream getUnicodeStream() throws SQLException {
try {
return new UnicodeInputStream(0);
} catch (IOException e) {
throw new SQLException(Messages.get("error.generic.ioerror",
e.getMessage()),
"HY000");
}
}
/**
* Creates an OutputStream that can be used to update the
* BLOB.
*
* Given that we cannot know the final size of a BLOB created by the caller
* of this method, we assume the worst and create a disk BLOB by default.
*
* @param pos the start position in the buffer (from 1)
* @param ascii true if an ASCII output stream is required
* @return the OutputStream to be used to update the BLOB
* @throws SQLException if an error occurs
*/
public OutputStream setBinaryStream(long pos, boolean ascii)
throws SQLException {
pos--;
if (pos < 0) {
throw new SQLException(Messages.get("error.blobclob.badpos"),
"HY090");
}
if (pos > this.length) {
throw new SQLException(Messages.get("error.blobclob.badposlen"),
"HY090");
}
try {
if (!isMemOnly && blobFile == null) {
createBlobFile();
}
if (ascii) {
return new AsciiOutputStream(pos);
} else {
return new BlobOutputStream(pos);
}
} catch (IOException e) {
throw new SQLException(Messages.get("error.generic.ioerror",
e.getMessage()),
"HY000");
}
}
/**
* Sets the content of the BLOB to the supplied byte array value.
*
* If the following conditions are met:
* int start index for the pattern (from 1) or -1
* if the pattern is not found.
* @throws SQLException if an error occurs
*/
public int position(byte[] pattern, long start) throws SQLException {
try {
start--;
if (start < 0) {
throw new SQLException(Messages.get("error.blobclob.badpos"),
"HY090");
}
if (start >= this.length) {
throw new SQLException(Messages.get("error.blobclob.badposlen"),
"HY090");
}
if (pattern == null) {
throw new SQLException(Messages.get("error.blob.badpattern"),
"HY009");
}
if (pattern.length == 0 || length == 0 || pattern.length > length) {
// Impossible for there to be a match
return -1;
}
// FIXME Implement a better (O(n)) search algorithm
int limit = (int) length - pattern.length;
if (blobFile == null) {
for (int i = (int) start; i <= limit; i++) {
int p;
for (p = 0;
p < pattern.length && buffer[i + p] == pattern[p];
p++);
if (p == pattern.length) {
return i + 1;
}
}
} else {
open();
for (int i = (int) start; i <= limit; i++) {
int p;
for (p = 0;
p < pattern.length && read(i + p) == (pattern[p] & 0xFF);
p++);
if (p == pattern.length) {
close();
return i + 1;
}
}
close();
}
return -1;
} catch (IOException e) {
throw new SQLException(Messages.get("error.generic.ioerror",
e.getMessage()),
"HY000");
}
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/util/Logger.java 0000644 0001750 0001750 00000014721 11316672660 025242 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.util;
import java.sql.*;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Class providing static methods to log diagnostics.
* * There are three ways to enable logging: *
PrintWriter
*/
public static PrintWriter getLogWriter() {
return log;
}
/**
* Retrieve the active status of the logger.
*
* @return boolean true if logging enabled
*/
public static boolean isActive() {
return(log != null || DriverManager.getLogWriter() != null);
}
/**
* Print a diagnostic message to the output stream provided by
* the DataSource or the DriverManager.
*
* @param message the diagnostic message to print
*/
public static void println(String message) {
if (log != null) {
log.println(message);
} else {
DriverManager.println(message);
}
}
private static final char hex[] =
{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
/**
* Print a dump of the current input or output network packet.
*
* @param streamId the owner of this packet
* @param in true if this is an input packet
* @param pkt the packet data
*/
public static void logPacket(int streamId, boolean in, byte[] pkt) {
int len = ((pkt[2] & 0xFF) << 8)| (pkt[3] & 0xFF);
StringBuffer line = new StringBuffer(80);
line.append("----- Stream #");
line.append(streamId);
line.append(in ? " read" : " send");
line.append((pkt[1] != 0) ? " last " : " ");
switch (pkt[0]) {
case 1:
line.append("Request packet ");
break;
case 2:
line.append("Login packet ");
break;
case 3:
line.append("RPC packet ");
break;
case 4:
line.append("Reply packet ");
break;
case 6:
line.append("Cancel packet ");
break;
case 14:
line.append("XA control packet ");
break;
case 15:
line.append("TDS5 Request packet ");
break;
case 16:
line.append("MS Login packet ");
break;
case 17:
line.append("NTLM Authentication packet ");
break;
case 18:
line.append("MS Prelogin packet ");
break;
default:
line.append("Invalid packet ");
break;
}
println(line.toString());
println("");
line.setLength(0);
for (int i = 0; i < len; i += 16) {
if (i < 1000) {
line.append(' ');
}
if (i < 100) {
line.append(' ');
}
if (i < 10) {
line.append(' ');
}
line.append(i);
line.append(':').append(' ');
int j = 0;
for (; j < 16 && i + j < len; j++) {
int val = pkt[i+j] & 0xFF;
line.append(hex[val >> 4]);
line.append(hex[val & 0x0F]);
line.append(' ');
}
for (; j < 16 ; j++) {
line.append(" ");
}
line.append('|');
for (j = 0; j < 16 && i + j < len; j++) {
int val = pkt[i + j] & 0xFF;
if (val > 31 && val < 127) {
line.append((char) val);
} else {
line.append(' ');
}
}
line.append('|');
println(line.toString());
line.setLength(0);
}
println("");
}
/**
* Print an Exception stack trace to the log.
*
* @param e the exception to log
*/
public static void logException(Exception e) {
if (log != null) {
e.printStackTrace(log);
} else if (DriverManager.getLogWriter() != null) {
e.printStackTrace(DriverManager.getLogWriter());
}
}
//
// Backward compatibility method
//
/**
* Turn the logging on or off.
*
* @deprecated Use the JDBC standard mechanisms to enable logging.
* @param value true to turn on logging
*/
public static void setActive(boolean value) {
if (value && log == null) {
try {
log = new PrintWriter(new FileOutputStream("log.out"), true);
} catch (IOException e) {
log = null; // Sorry no logging!
}
}
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/util/GeneralDigest.java 0000644 0001750 0001750 00000007521 11316672660 026540 0 ustar martin martin /******************************************************************************
* Copyright (c) 2000 The Legion Of The Bouncy Castle (http://www.bouncycastle.org)
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
******************************************************************************/
package net.sourceforge.jtds.util;
/**
* base implementation of MD4 family style digest as outlined in
* "Handbook of Applied Cryptography", pages 344 - 347.
*
* @version $Id: GeneralDigest.java,v 1.2 2004/06/27 17:00:55 bheineman Exp $
*/
public abstract class GeneralDigest
// implements Digest - mdb: we don't care about this interface
{
private byte[] xBuf;
private int xBufOff;
private long byteCount;
/**
* Standard constructor
*/
protected GeneralDigest()
{
xBuf = new byte[4];
xBufOff = 0;
}
/**
* Copy constructor. We are using copy constructors in place
* of the Object.clone() interface as this interface is not
* supported by J2ME.
*/
protected GeneralDigest(GeneralDigest t)
{
xBuf = new byte[t.xBuf.length];
System.arraycopy(t.xBuf, 0, xBuf, 0, t.xBuf.length);
xBufOff = t.xBufOff;
byteCount = t.byteCount;
}
public void update(
byte in)
{
xBuf[xBufOff++] = in;
if (xBufOff == xBuf.length)
{
processWord(xBuf, 0);
xBufOff = 0;
}
byteCount++;
}
public void update(
byte[] in,
int inOff,
int len)
{
//
// fill the current word
//
while ((xBufOff != 0) && (len > 0))
{
update(in[inOff]);
inOff++;
len--;
}
//
// process whole words.
//
while (len > xBuf.length)
{
processWord(in, inOff);
inOff += xBuf.length;
len -= xBuf.length;
byteCount += xBuf.length;
}
//
// load in the remainder.
//
while (len > 0)
{
update(in[inOff]);
inOff++;
len--;
}
}
public void finish()
{
long bitLength = (byteCount << 3);
//
// add the pad bytes.
//
update((byte)128);
while (xBufOff != 0)
{
update((byte)0);
}
processLength(bitLength);
processBlock();
}
public void reset()
{
byteCount = 0;
xBufOff = 0;
for ( int i = 0; i < xBuf.length; i++ ) {
xBuf[i] = 0;
}
}
protected abstract void processWord(byte[] in, int inOff);
protected abstract void processLength(long bitLength);
protected abstract void processBlock();
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/util/MD4Digest.java 0000644 0001750 0001750 00000021044 11316672660 025543 0 ustar martin martin /******************************************************************************
* Copyright (c) 2000 The Legion Of The Bouncy Castle (http://www.bouncycastle.org)
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
******************************************************************************/
package net.sourceforge.jtds.util;
/**
* implementation of MD4 as RFC 1320 by R. Rivest, MIT Laboratory for
* Computer Science and RSA Data Security, Inc.
* * NOTE: This algorithm is only included for backwards compatability * with legacy applications, it's not secure, don't use it for anything new! * * @version $Id: MD4Digest.java,v 1.2 2004/06/27 17:00:55 bheineman Exp $ */ public class MD4Digest extends GeneralDigest { private static final int DIGEST_LENGTH = 16; // // round 1 left rotates // private static final int S11 = 3; private static final int S12 = 7; private static final int S13 = 11; private static final int S14 = 19; // // round 2 left rotates // private static final int S21 = 3; private static final int S22 = 5; private static final int S23 = 9; private static final int S24 = 13; // // round 3 left rotates // private static final int S31 = 3; private static final int S32 = 9; private static final int S33 = 11; private static final int S34 = 15; private int H1, H2, H3, H4; // IV's private int[] X = new int[16]; private int xOff; /** * Standard constructor */ public MD4Digest() { reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public MD4Digest(MD4Digest t) { super(t); H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; System.arraycopy(t.X, 0, X, 0, t.X.length); xOff = t.xOff; } public String getAlgorithmName() { return "MD4"; } public int getDigestSize() { return DIGEST_LENGTH; } protected void processWord(byte[] in, int inOff) { X[xOff++] = (in[inOff] & 0xff) | ((in[inOff + 1] & 0xff) << 8) | ((in[inOff + 2] & 0xff) << 16) | ((in[inOff + 3] & 0xff) << 24); if (xOff == 16) { processBlock(); } } protected void processLength(long bitLength) { if (xOff > 14) { processBlock(); } X[14] = (int)(bitLength & 0xffffffff); X[15] = (int)(bitLength >>> 32); } private void unpackWord(int word, byte[] out, int outOff) { out[outOff] = (byte)word; out[outOff + 1] = (byte)(word >>> 8); out[outOff + 2] = (byte)(word >>> 16); out[outOff + 3] = (byte)(word >>> 24); } public int doFinal(byte[] out, int outOff) { finish(); unpackWord(H1, out, outOff); unpackWord(H2, out, outOff + 4); unpackWord(H3, out, outOff + 8); unpackWord(H4, out, outOff + 12); reset(); return DIGEST_LENGTH; } /** * reset the chaining variables to the IV values. */ public void reset() { super.reset(); H1 = 0x67452301; H2 = 0xefcdab89; H3 = 0x98badcfe; H4 = 0x10325476; xOff = 0; for (int i = 0; i != X.length; i++) { X[i] = 0; } } /* * rotate int x left n bits. */ private int rotateLeft(int x, int n) { return(x << n) | (x >>> (32 - n)); } /* * F, G, H and I are the basic MD4 functions. */ private int F(int u, int v, int w) { return(u & v) | (~u & w); } private int G(int u, int v, int w) { return(u & v) | (u & w) | (v & w); } private int H(int u, int v, int w) { return u ^ v ^ w; } protected void processBlock() { int a = H1; int b = H2; int c = H3; int d = H4; // // Round 1 - F cycle, 16 times. // a = rotateLeft((a + F(b, c, d) + X[ 0]), S11); d = rotateLeft((d + F(a, b, c) + X[ 1]), S12); c = rotateLeft((c + F(d, a, b) + X[ 2]), S13); b = rotateLeft((b + F(c, d, a) + X[ 3]), S14); a = rotateLeft((a + F(b, c, d) + X[ 4]), S11); d = rotateLeft((d + F(a, b, c) + X[ 5]), S12); c = rotateLeft((c + F(d, a, b) + X[ 6]), S13); b = rotateLeft((b + F(c, d, a) + X[ 7]), S14); a = rotateLeft((a + F(b, c, d) + X[ 8]), S11); d = rotateLeft((d + F(a, b, c) + X[ 9]), S12); c = rotateLeft((c + F(d, a, b) + X[10]), S13); b = rotateLeft((b + F(c, d, a) + X[11]), S14); a = rotateLeft((a + F(b, c, d) + X[12]), S11); d = rotateLeft((d + F(a, b, c) + X[13]), S12); c = rotateLeft((c + F(d, a, b) + X[14]), S13); b = rotateLeft((b + F(c, d, a) + X[15]), S14); // // Round 2 - G cycle, 16 times. // a = rotateLeft((a + G(b, c, d) + X[ 0] + 0x5a827999), S21); d = rotateLeft((d + G(a, b, c) + X[ 4] + 0x5a827999), S22); c = rotateLeft((c + G(d, a, b) + X[ 8] + 0x5a827999), S23); b = rotateLeft((b + G(c, d, a) + X[12] + 0x5a827999), S24); a = rotateLeft((a + G(b, c, d) + X[ 1] + 0x5a827999), S21); d = rotateLeft((d + G(a, b, c) + X[ 5] + 0x5a827999), S22); c = rotateLeft((c + G(d, a, b) + X[ 9] + 0x5a827999), S23); b = rotateLeft((b + G(c, d, a) + X[13] + 0x5a827999), S24); a = rotateLeft((a + G(b, c, d) + X[ 2] + 0x5a827999), S21); d = rotateLeft((d + G(a, b, c) + X[ 6] + 0x5a827999), S22); c = rotateLeft((c + G(d, a, b) + X[10] + 0x5a827999), S23); b = rotateLeft((b + G(c, d, a) + X[14] + 0x5a827999), S24); a = rotateLeft((a + G(b, c, d) + X[ 3] + 0x5a827999), S21); d = rotateLeft((d + G(a, b, c) + X[ 7] + 0x5a827999), S22); c = rotateLeft((c + G(d, a, b) + X[11] + 0x5a827999), S23); b = rotateLeft((b + G(c, d, a) + X[15] + 0x5a827999), S24); // // Round 3 - H cycle, 16 times. // a = rotateLeft((a + H(b, c, d) + X[ 0] + 0x6ed9eba1), S31); d = rotateLeft((d + H(a, b, c) + X[ 8] + 0x6ed9eba1), S32); c = rotateLeft((c + H(d, a, b) + X[ 4] + 0x6ed9eba1), S33); b = rotateLeft((b + H(c, d, a) + X[12] + 0x6ed9eba1), S34); a = rotateLeft((a + H(b, c, d) + X[ 2] + 0x6ed9eba1), S31); d = rotateLeft((d + H(a, b, c) + X[10] + 0x6ed9eba1), S32); c = rotateLeft((c + H(d, a, b) + X[ 6] + 0x6ed9eba1), S33); b = rotateLeft((b + H(c, d, a) + X[14] + 0x6ed9eba1), S34); a = rotateLeft((a + H(b, c, d) + X[ 1] + 0x6ed9eba1), S31); d = rotateLeft((d + H(a, b, c) + X[ 9] + 0x6ed9eba1), S32); c = rotateLeft((c + H(d, a, b) + X[ 5] + 0x6ed9eba1), S33); b = rotateLeft((b + H(c, d, a) + X[13] + 0x6ed9eba1), S34); a = rotateLeft((a + H(b, c, d) + X[ 3] + 0x6ed9eba1), S31); d = rotateLeft((d + H(a, b, c) + X[11] + 0x6ed9eba1), S32); c = rotateLeft((c + H(d, a, b) + X[ 7] + 0x6ed9eba1), S33); b = rotateLeft((b + H(c, d, a) + X[15] + 0x6ed9eba1), S34); H1 += a; H2 += b; H3 += c; H4 += d; // // reset the offset and clean out the word buffer. // xOff = 0; for (int i = 0; i != X.length; i++) { X[i] = 0; } } } libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/util/TimerThread.java 0000644 0001750 0001750 00000021031 11316672660 026223 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase // Copyright (C) 2004 The jTDS Project // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // package net.sourceforge.jtds.util; import java.util.LinkedList; import java.util.ListIterator; /** * Simple timer class used to implement login and query timeouts. *
* This thread runs as a Daemon thread to ensure that the java VM will exit * correctly when normal execution is complete. * * It provides both a singleton implementation and a default constructor for * the case when more than one timer thread is desired. * * @author Alin Sinpalean * @author Mike Hutchinson * @version $Id: TimerThread.java,v 1.5.2.2 2009/10/17 13:21:27 ickzon Exp $ */ public class TimerThread extends Thread { /** * Interface to be implemented by classes that request timer services. */ public interface TimerListener { /** * Event to be fired when the timeout expires. */ void timerExpired(); } /** * Internal class associating a login or query timeout value with a target *TimerListener.
*/
private static class TimerRequest {
/** The time when this timeout will expire. */
final long time;
/** Target to notify when the timeout expires. */
final TimerListener target;
/**
* Create a TimerRequest.
*
* @param timeout the desired timeout in milliseconds
* @param target the target object; one of SharedSocket or
* TdsCore
* @throws IllegalArgumentException if the timeout is negative or 0
*/
TimerRequest(int timeout, TimerListener target) {
if (timeout <= 0) {
throw new IllegalArgumentException("Invalid timeout parameter "
+ timeout);
}
this.time = System.currentTimeMillis() + (timeout);
this.target = target;
}
}
/** Singleton instance. */
private static TimerThread instance;
/** List of TimerRequests to execute, ordered by time. */
private final LinkedList timerList = new LinkedList();
/** Time when the first request time out should occur. */
private long nextTimeout;
/**
* Singleton getter.
*/
public static synchronized TimerThread getInstance() {
if (instance == null) {
instance = new TimerThread();
instance.start();
}
return instance;
}
/**
* Construct a new TimerThread instance.
*/
public TimerThread() {
// Set the thread name
super("jTDS TimerThread");
// Ensure that this thread does not prevent the VM from exiting
this.setDaemon(true);
}
/**
* Execute the TimerThread main loop.
*/
public void run() {
synchronized (timerList) {
boolean run = true;
while (run) {
try {
long ms;
while ((ms = nextTimeout - System.currentTimeMillis()) > 0 || nextTimeout == 0) {
// positive timeout, wait appropriately
timerList.wait(nextTimeout==0 ? 0 : ms);
}
// Fire expired timeout requests
long time = System.currentTimeMillis();
while (!timerList.isEmpty()) {
// Examine the head of the list and see
// if the timer has expired.
TimerRequest t = (TimerRequest) timerList.getFirst();
if (t.time > time) {
break; // No timers have expired
}
// Notify target of timeout
t.target.timerExpired();
// Remove the fired timeout request
timerList.removeFirst();
}
// Determine next timeout
updateNextTimeout();
} catch (InterruptedException e) {
// stopThread() called, or thread interrupted externally
run = false;
timerList.clear();
}
}
}
}
/**
* Add a timer request to the queue.
*
* The queue is ordered by time so that the head of the list is always the
* first timer to expire.
*
* @param timeout the interval in milliseconds after which the timer will
* expire
* @param l TimerListener to be notified on timeout
* @return a handle to the timer request, that can later be used with
* cancelTimer
*/
public Object setTimer(int timeout, TimerListener l) {
// Create a new timer request
TimerRequest t = new TimerRequest(timeout, l);
synchronized (timerList) {
if (timerList.isEmpty()) {
// List was empty, just add new request
timerList.add(t);
} else {
// Tiny optimization; new requests will usually go to the end
TimerRequest crt = (TimerRequest) timerList.getLast();
if (t.time >= crt.time) {
timerList.addLast(t);
} else {
// Iterate the list and insert it into the right place
for (ListIterator li = timerList.listIterator(); li.hasNext(); ) {
crt = (TimerRequest) li.next();
if (t.time < crt.time) {
li.previous();
li.add(t);
break;
}
}
}
}
// If this request is now the first in the list, interrupt timer
if (timerList.getFirst() == t) {
nextTimeout = t.time;
timerList.notifyAll();
}
}
// Return the created request as timer handle
return t;
}
/**
* Remove a redundant timer before it expires.
*
* @param handle handle to the request to be removed from the queue (a
* TimerRequest instance)
* @return true if timer had not expired
*/
public boolean cancelTimer(Object handle) {
TimerRequest t = (TimerRequest) handle;
synchronized (timerList) {
boolean result = timerList.remove(t);
if (nextTimeout == t.time) {
updateNextTimeout();
}
return result;
}
}
/**
* Completely stops the timer and its underlying Java thread, discarding all
* pending timeouts. Any subsequent invocation of {@link #getInstance()}
* will restart the timer.
*/
public synchronized void stopTimer() {
interrupt();
instance = null;
}
/**
* Check whether a timer has expired.
*
* @param handle handle to the request to be checked for expiry (a
* TimerRequest instance)
* @return true if timer has expired
*/
public boolean hasExpired(Object handle) {
TimerRequest t = (TimerRequest) handle;
synchronized (timerList) {
return !timerList.contains(t);
}
}
/** Internal method that updates the value of {@link #nextTimeout}. */
private void updateNextTimeout() {
nextTimeout = timerList.isEmpty() ? 0
: ((TimerRequest) timerList.getFirst()).time;
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbcx/ 0000755 0001750 0001750 00000000000 11316672660 023270 5 ustar martin martin libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbcx/JtdsXid.java 0000644 0001750 0001750 00000011427 11316672660 025511 0 ustar martin martin //jTDS JDBC Driver for Microsoft SQL Server and Sybase
//Copyright (C) 2004 The jTDS Project
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbcx;
import javax.transaction.xa.Xid;
import net.sourceforge.jtds.jdbc.Support;
/**
* jTDS implementation of the Xid interface.
*
* @version $Id: JtdsXid.java,v 1.3 2005/04/28 14:29:30 alin_sinpalean Exp $
*/
public class JtdsXid implements Xid {
/** The size of an XID in bytes. */
public static final int XID_SIZE = 140;
/** The global transaction ID. */
private final byte gtran[];
/** The branch qualifier ID. */
private final byte bqual[];
/** The format ID. */
public final int fmtId;
/** Precalculated hash value. */
public int hash;
/**
* Construct an XID using an offset into a byte buffer.
*
* @param buf the byte buffer
* @param pos the offset
*/
public JtdsXid(byte[] buf, int pos) {
fmtId = (buf[pos] & 0xFF) |
((buf[pos+1] & 0xFF) << 8) |
((buf[pos+2] & 0xFF) << 16) |
((buf[pos+3] & 0xFF) << 24);
int t = buf[pos+4];
int b = buf[pos+8];
gtran = new byte[t];
bqual = new byte[b];
System.arraycopy(buf, 12+pos, gtran, 0, t);
System.arraycopy(buf, 12+t+pos, bqual, 0, b);
calculateHash();
}
/**
* Construct an XID using two byte arrays.
*
* @param global the global transaction id
* @param branch the transaction branch
*/
public JtdsXid(byte[] global, byte[] branch) {
fmtId = 0;
gtran = global;
bqual = branch;
calculateHash();
}
/**
* Construct an XID as a clone of another XID.
*/
public JtdsXid(Xid xid) {
fmtId = xid.getFormatId();
gtran = new byte[xid.getGlobalTransactionId().length];
System.arraycopy(xid.getGlobalTransactionId(), 0, gtran, 0, gtran.length);
bqual = new byte[xid.getBranchQualifier().length];
System.arraycopy(xid.getBranchQualifier(), 0, bqual, 0, bqual.length);
calculateHash();
}
private void calculateHash() {
String x = Integer.toString(fmtId)+ new String(gtran) + new String(bqual);
hash = x.hashCode();
}
/**
* Get the hash code for this object.
*
* @return the hash value of this object as a int
*/
public int hashCode() {
return hash;
}
/**
* Test for equality.
*
* @param obj the object to test for equality with this
* @return boolean true if the parameter equals this
*/
public boolean equals(Object obj) {
if (obj == this)
return true;
if (obj instanceof JtdsXid) {
JtdsXid xobj = (JtdsXid)obj;
if (gtran.length + bqual.length == xobj.gtran.length + xobj.bqual.length
&& fmtId == xobj.fmtId) {
for (int i = 0; i < gtran.length; ++i) {
if (gtran[i] != xobj.gtran[i]) {
return false;
}
}
for (int i = 0; i < bqual.length; ++i) {
if (bqual[i] != xobj.bqual[i]) {
return false;
}
}
return true;
}
}
return false;
}
//
// ------------------- javax.transaction.xa.Xid interface methods -------------------
//
public int getFormatId() {
return fmtId;
}
public byte[] getBranchQualifier() {
return bqual;
}
public byte[] getGlobalTransactionId() {
return gtran;
}
public String toString() {
StringBuffer txt = new StringBuffer(256);
txt.append("XID[Format=").append(fmtId).append(", Global=0x");
txt.append(Support.toHex(gtran)).append(", Branch=0x");
txt.append(Support.toHex(bqual)).append(']');
return txt.toString();
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbcx/PooledConnection.java 0000644 0001750 0001750 00000013302 11316672660 027374 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbcx;
import java.sql.*;
import java.util.*;
import javax.sql.*;
import net.sourceforge.jtds.jdbc.*;
import net.sourceforge.jtds.jdbcx.proxy.*;
/**
* jTDS implementation of the PooledConnection interface.
*
* @version $Id: PooledConnection.java,v 1.11.6.3 2009/12/30 08:45:34 ickzon Exp $
*/
public class PooledConnection implements javax.sql.PooledConnection {
private ArrayList listeners = new ArrayList();
protected Connection connection;
public PooledConnection(Connection connection) {
this.connection = connection;
}
/**
* Adds the specified listener to the list.
*
* @see #fireConnectionEvent
* @see #removeConnectionEventListener
*/
public synchronized void addConnectionEventListener(ConnectionEventListener listener) {
// Clone the list of listeners to avoid concurrent modifications. See
// bug [1113040] Small bug in net.sourceforge.jtds.jdbcx.PooledConnection
// for a description of how these can occur. The method still needs to
// be synchronized to prevent race conditions.
listeners = (ArrayList) listeners.clone();
// Now add the listener to the new, cloned list
listeners.add(listener);
}
/**
* Closes the database connection.
*
* @throws SQLException if an error occurs
*/
public synchronized void close() throws SQLException {
connection.close();
connection = null; // Garbage collect the connection
}
/**
* Fires a new connection event on all listeners.
*
* @param closed true if close has been called on the
* connection; false if the sqlException represents
* an error where the connection may not longer be used.
* @param sqlException the SQLException to pass to the listeners
*/
public synchronized void fireConnectionEvent(boolean closed, SQLException sqlException) {
if (listeners.size() > 0) {
ConnectionEvent connectionEvent = new ConnectionEvent(this, sqlException);
Iterator iterator = listeners.iterator();
while (iterator.hasNext()) {
ConnectionEventListener listener = (ConnectionEventListener) iterator.next();
if (closed) {
listener.connectionClosed(connectionEvent);
} else {
try {
if (connection == null || connection.isClosed()) {
listener.connectionErrorOccurred(connectionEvent);
}
} catch (SQLException ex) {
// Will never occur
}
}
}
}
}
/**
* Returns a ConnectionProxy.
*
* @throws SQLException if an error occurs
*/
public synchronized Connection getConnection() throws SQLException {
if (connection == null) {
fireConnectionEvent(false,
new SQLException(Messages.get("error.jdbcx.conclosed"),
"08003"));
return null;
}
// Should the SQLException be captured here for safety in the future even though
// no SQLException is being thrown by the ConnectionProxy at the moment???
return new ConnectionProxy(this, connection);
}
/**
* Removes the specified listener from the list.
*
* @see #addConnectionEventListener
* @see #fireConnectionEvent
*/
public synchronized void removeConnectionEventListener(ConnectionEventListener listener) {
// Clone the list of listeners to avoid concurrent modifications. See
// bug [1113040] Small bug in net.sourceforge.jtds.jdbcx.PooledConnection
// for a description of how these can occur. The method still needs to
// be synchronized to prevent race conditions.
listeners = (ArrayList) listeners.clone();
// Now remove the listener from the new, cloned list
listeners.remove(listener);
}
/////// JDBC4 demarcation, do NOT put any JDBC3 code below this line ///////
/* (non-Javadoc)
* @see javax.sql.PooledConnection#addStatementEventListener(javax.sql.StatementEventListener)
*/
public void addStatementEventListener(StatementEventListener listener) {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see javax.sql.PooledConnection#removeStatementEventListener(javax.sql.StatementEventListener)
*/
public void removeStatementEventListener(StatementEventListener listener) {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbcx/JtdsXAConnection.java 0000644 0001750 0001750 00000005370 11316672660 027315 0 ustar martin martin //jTDS JDBC Driver for Microsoft SQL Server and Sybase
//Copyright (C) 2004 The jTDS Project
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbcx;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.XAConnection;
import javax.transaction.xa.XAResource;
import net.sourceforge.jtds.jdbc.XASupport;
/**
* jTDS implementation of the XAConnection interface.
*
* @version $Id: JtdsXAConnection.java,v 1.4 2005/04/28 14:29:30 alin_sinpalean Exp $
*/
public class JtdsXAConnection extends PooledConnection implements XAConnection {
/** The XAResource used by the transaction manager to control this connection.*/
private final XAResource resource;
private final JtdsDataSource dataSource;
private final int xaConnectionId;
/**
* Construct a new XAConnection object.
*
* @param dataSource the parent DataSource object
* @param connection the real database connection
*/
public JtdsXAConnection(JtdsDataSource dataSource, Connection connection)
throws SQLException {
super(connection);
this.resource = new JtdsXAResource(this, connection);
this.dataSource = dataSource;
xaConnectionId = XASupport.xa_open(connection);
}
/**
* Retrieves the XA Connection ID to pass to server.
*
* @return the XA connection ID as an Integer
*/
int getXAConnectionID() {
return this.xaConnectionId;
}
//
// ------------------- javax.sql.XAConnection interface methods -------------------
//
public XAResource getXAResource() throws SQLException {
return resource;
}
public synchronized void close() throws SQLException {
try {
XASupport.xa_close(connection, xaConnectionId);
} catch (SQLException e) {
// Ignore close errors
}
super.close();
}
protected JtdsDataSource getXADataSource() {
return this.dataSource;
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbcx/JtdsObjectFactory.java 0000644 0001750 0001750 00000020662 11316672660 027524 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbcx;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;
import net.sourceforge.jtds.jdbc.Driver;
import net.sourceforge.jtds.jdbc.Messages;
/**
* Description
*
* @author Alin Sinplean
* @since 0.3
* @version $Id: JtdsObjectFactory.java,v 1.25.2.1 2009/08/07 14:02:11 ickzon Exp $
*/
public class JtdsObjectFactory implements ObjectFactory {
public Object getObjectInstance(Object refObj,
Name name,
Context nameCtx,
Hashtable env)
throws Exception {
Reference ref = (Reference) refObj;
if (ref.getClassName().equals(JtdsDataSource.class.getName())) {
JtdsDataSource ds = new JtdsDataSource();
ds.setServerName((String) ref.get(Messages.get(Driver.SERVERNAME)).getContent());
final Object portNumber = ref.get(Messages.get(Driver.PORTNUMBER)).getContent();
if (portNumber != null) {
ds.setPortNumber(Integer.parseInt((String) portNumber));
}
ds.setDatabaseName((String) ref.get(Messages.get(Driver.DATABASENAME)).getContent());
ds.setUser((String) ref.get(Messages.get(Driver.USER)).getContent());
ds.setPassword((String) ref.get(Messages.get(Driver.PASSWORD)).getContent());
ds.setCharset((String) ref.get(Messages.get(Driver.CHARSET)).getContent());
ds.setLanguage((String) ref.get(Messages.get(Driver.LANGUAGE)).getContent());
ds.setTds((String) ref.get(Messages.get(Driver.TDS)).getContent());
ds.setBindAddress((String) ref.get(Messages.get(Driver.BINDADDRESS)).getContent());
final Object serverType = ref.get(Messages.get(Driver.SERVERTYPE)).getContent();
if (serverType != null) {
ds.setServerType(Integer.parseInt((String) serverType));
}
ds.setDomain((String) ref.get(Messages.get(Driver.DOMAIN)).getContent());
ds.setUseNTLMV2((String) ref.get(Messages.get(Driver.USENTLMV2)).getContent());
ds.setInstance((String) ref.get(Messages.get(Driver.INSTANCE)).getContent());
final Object lastUpdateCount = ref.get(Messages.get(Driver.LASTUPDATECOUNT)).getContent();
if (lastUpdateCount != null) {
ds.setLastUpdateCount("true".equals(lastUpdateCount));
}
final Object sendStringParametersAsUnicode =
ref.get(Messages.get(Driver.SENDSTRINGPARAMETERSASUNICODE)).getContent();
if (sendStringParametersAsUnicode != null) {
ds.setSendStringParametersAsUnicode("true".equals(sendStringParametersAsUnicode));
}
final Object namedPipe = ref.get(Messages.get(Driver.NAMEDPIPE)).getContent();
if (namedPipe != null) {
ds.setNamedPipe("true".equals(namedPipe));
}
ds.setMacAddress((String) ref.get(Messages.get(Driver.MACADDRESS)).getContent());
final Object maxStatements = ref.get(Messages.get(Driver.MAXSTATEMENTS)).getContent();
if (maxStatements != null) {
ds.setMaxStatements(Integer.parseInt((String) maxStatements));
}
final Object packetSize = ref.get(Messages.get(Driver.PACKETSIZE)).getContent();
if (packetSize != null) {
ds.setPacketSize(Integer.parseInt((String) packetSize));
}
final Object prepareSql = ref.get(Messages.get(Driver.PREPARESQL)).getContent();
if (prepareSql != null) {
ds.setPrepareSql(Integer.parseInt((String) prepareSql));
}
final Object lobBuffer = ref.get(Messages.get(Driver.LOBBUFFER)).getContent();
if (lobBuffer != null) {
ds.setLobBuffer(Long.parseLong((String) lobBuffer));
}
final Object loginTimeout = ref.get(Messages.get(Driver.LOGINTIMEOUT)).getContent();
if (loginTimeout != null) {
ds.setLoginTimeout(Integer.parseInt((String) loginTimeout));
}
final Object socketTimeout = ref.get(Messages.get(Driver.SOTIMEOUT)).getContent();
if (socketTimeout != null) {
ds.setSocketTimeout(Integer.parseInt((String) socketTimeout));
}
final Object socketKeepAlive = ref.get(Messages.get(Driver.SOKEEPALIVE)).getContent();
if (socketKeepAlive != null) {
ds.setSocketKeepAlive("true".equalsIgnoreCase((String) socketKeepAlive));
}
final Object processId = ref.get(Messages.get(Driver.PROCESSID)).getContent();
if (processId != null) {
ds.setProcessId((String) processId);
}
ds.setAppName((String) ref.get(Messages.get(Driver.APPNAME)).getContent());
ds.setProgName((String) ref.get(Messages.get(Driver.PROGNAME)).getContent());
ds.setWsid((String) ref.get(Messages.get(Driver.WSID)).getContent());
final Object tcpNoDelay = ref.get(Messages.get(Driver.TCPNODELAY)).getContent();
if (tcpNoDelay != null) {
ds.setTcpNoDelay("true".equals(tcpNoDelay));
}
final Object xaEmulation = ref.get(Messages.get(Driver.XAEMULATION)).getContent();
if (xaEmulation != null) {
ds.setXaEmulation("true".equals(xaEmulation));
}
ds.setLogFile((String) ref.get(Messages.get(Driver.LOGFILE)).getContent());
ds.setSsl((String) ref.get(Messages.get(Driver.SSL)).getContent());
final Object batchSize = ref.get(Messages.get(Driver.BATCHSIZE)).getContent();
if (batchSize != null) {
ds.setBatchSize(Integer.parseInt((String) batchSize));
}
final Object bufferDir = ref.get(Messages.get(Driver.BUFFERDIR)).getContent();
if (bufferDir != null) {
ds.setBufferDir((String) bufferDir);
}
final Object bufferMaxMemory = ref.get(Messages.get(Driver.BUFFERMAXMEMORY)).getContent();
if (bufferMaxMemory != null) {
ds.setBufferMaxMemory(Integer.parseInt((String) bufferMaxMemory));
}
final Object bufferMinPackets = ref.get(Messages.get(Driver.BUFFERMINPACKETS)).getContent();
if (bufferMinPackets != null) {
ds.setBufferMinPackets(Integer.parseInt((String) bufferMinPackets));
}
final Object cacheMetaData = ref.get(Messages.get(Driver.CACHEMETA)).getContent();
if (cacheMetaData != null) {
ds.setCacheMetaData("true".equals(cacheMetaData));
}
final Object useCursors = ref.get(Messages.get(Driver.USECURSORS)).getContent();
if (useCursors != null) {
ds.setUseCursors("true".equals(useCursors));
}
final Object useJCIFS = ref.get(Messages.get(Driver.USEJCIFS)).getContent();
if (useJCIFS != null) {
ds.setUseJCIFS("true".equals(useJCIFS));
}
final Object useLOBs = ref.get(Messages.get(Driver.USELOBS)).getContent();
if (useLOBs != null) {
ds.setUseLOBs("true".equals(useLOBs));
}
ds.setDescription((String) ref.get("description").getContent());
return ds;
}
return null;
}
}
libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbcx/proxy/ 0000755 0001750 0001750 00000000000 11316672660 024451 5 ustar martin martin libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbcx/proxy/CallableStatementProxy.java 0000644 0001750 0001750 00000176116 11316672660 031756 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbcx.proxy;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.sql.*;
import java.util.Calendar;
import net.sourceforge.jtds.jdbc.*;
/**
* This class would be better implemented as a java.lang.reflect.Proxy. However, this
* feature was not added until 1.3 and reflection performance was not improved until 1.4.
* Since the driver still needs to be compatible with 1.2 and 1.3 this class is used
* to delegate the calls to a callable statement with minimal overhead.
*
* @version $Id: CallableStatementProxy.java,v 1.3.4.3 2009/12/30 08:45:34 ickzon Exp $
*/
public class CallableStatementProxy
extends PreparedStatementProxy
implements CallableStatement {
private JtdsCallableStatement _callableStatement;
CallableStatementProxy(ConnectionProxy connection, JtdsCallableStatement callableStatement) {
super(connection, callableStatement);
_callableStatement = callableStatement;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException {
validateConnection();
try {
_callableStatement.registerOutParameter(parameterIndex, sqlType);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException {
validateConnection();
try {
_callableStatement.registerOutParameter(parameterIndex, sqlType, scale);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public boolean wasNull() throws SQLException {
validateConnection();
try {
return _callableStatement.wasNull();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return false;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public String getString(int parameterIndex) throws SQLException {
validateConnection();
try {
return _callableStatement.getString(parameterIndex);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public boolean getBoolean(int parameterIndex) throws SQLException {
validateConnection();
try {
return _callableStatement.getBoolean(parameterIndex);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return false;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public byte getByte(int parameterIndex) throws SQLException {
validateConnection();
try {
return _callableStatement.getByte(parameterIndex);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Byte.MIN_VALUE;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public short getShort(int parameterIndex) throws SQLException {
validateConnection();
try {
return _callableStatement.getShort(parameterIndex);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Short.MIN_VALUE;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public int getInt(int parameterIndex) throws SQLException {
validateConnection();
try {
return _callableStatement.getInt(parameterIndex);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Integer.MIN_VALUE;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public long getLong(int parameterIndex) throws SQLException {
validateConnection();
try {
return _callableStatement.getLong(parameterIndex);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Long.MIN_VALUE;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public float getFloat(int parameterIndex) throws SQLException {
validateConnection();
try {
return _callableStatement.getFloat(parameterIndex);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Float.MIN_VALUE;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public double getDouble(int parameterIndex) throws SQLException {
validateConnection();
try {
return _callableStatement.getDouble(parameterIndex);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Double.MIN_VALUE;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException {
validateConnection();
try {
return _callableStatement.getBigDecimal(parameterIndex, scale);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public byte[] getBytes(int parameterIndex) throws SQLException {
validateConnection();
try {
return _callableStatement.getBytes(parameterIndex);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Date getDate(int parameterIndex) throws SQLException {
validateConnection();
try {
return _callableStatement.getDate(parameterIndex);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Time getTime(int parameterIndex) throws SQLException {
validateConnection();
try {
return _callableStatement.getTime(parameterIndex);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Timestamp getTimestamp(int parameterIndex) throws SQLException {
validateConnection();
try {
return _callableStatement.getTimestamp(parameterIndex);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Object getObject(int parameterIndex) throws SQLException {
validateConnection();
try {
return _callableStatement.getObject(parameterIndex);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public BigDecimal getBigDecimal(int parameterIndex) throws SQLException {
validateConnection();
try {
return _callableStatement.getBigDecimal(parameterIndex);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Object getObject(int parameterIndex, java.util.Map map) throws SQLException {
validateConnection();
try {
return _callableStatement.getObject(parameterIndex, map);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Ref getRef(int parameterIndex) throws SQLException {
validateConnection();
try {
return _callableStatement.getRef(parameterIndex);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Blob getBlob(int parameterIndex) throws SQLException {
validateConnection();
try {
return _callableStatement.getBlob(parameterIndex);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Clob getClob(int parameterIndex) throws SQLException {
validateConnection();
try {
return _callableStatement.getClob(parameterIndex);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Array getArray(int parameterIndex) throws SQLException {
validateConnection();
try {
return _callableStatement.getArray(parameterIndex);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Date getDate(int parameterIndex, Calendar cal) throws SQLException {
validateConnection();
try {
return _callableStatement.getDate(parameterIndex, cal);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Time getTime(int parameterIndex, Calendar cal) throws SQLException {
validateConnection();
try {
return _callableStatement.getTime(parameterIndex, cal);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException {
validateConnection();
try {
return _callableStatement.getTimestamp(parameterIndex, cal);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException {
validateConnection();
try {
_callableStatement.registerOutParameter(parameterIndex, sqlType, typeName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void registerOutParameter(String parameterName, int sqlType) throws SQLException {
validateConnection();
try {
_callableStatement.registerOutParameter(parameterName, sqlType);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException {
validateConnection();
try {
_callableStatement.registerOutParameter(parameterName, sqlType, scale);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException {
validateConnection();
try {
_callableStatement.registerOutParameter(parameterName, sqlType, typeName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public java.net.URL getURL(int parameterIndex) throws SQLException {
validateConnection();
try {
return _callableStatement.getURL(parameterIndex);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setURL(String parameterName, java.net.URL val) throws SQLException {
validateConnection();
try {
_callableStatement.setURL(parameterName, val);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setNull(String parameterName, int sqlType) throws SQLException {
validateConnection();
try {
_callableStatement.setNull(parameterName, sqlType);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setBoolean(String parameterName, boolean x) throws SQLException {
validateConnection();
try {
_callableStatement.setBoolean(parameterName, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setByte(String parameterName, byte x) throws SQLException {
validateConnection();
try {
_callableStatement.setByte(parameterName, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setShort(String parameterName, short x) throws SQLException {
validateConnection();
try {
_callableStatement.setShort(parameterName, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setInt(String parameterName, int x) throws SQLException {
validateConnection();
try {
_callableStatement.setInt(parameterName, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setLong(String parameterName, long x) throws SQLException {
validateConnection();
try {
_callableStatement.setLong(parameterName, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setFloat(String parameterName, float x) throws SQLException {
validateConnection();
try {
_callableStatement.setFloat(parameterName, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setDouble(String parameterName, double x) throws SQLException {
validateConnection();
try {
_callableStatement.setDouble(parameterName, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException {
validateConnection();
try {
_callableStatement.setBigDecimal(parameterName, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setString(String parameterName, String x) throws SQLException {
validateConnection();
try {
_callableStatement.setString(parameterName, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setBytes(String parameterName, byte[] x) throws SQLException {
validateConnection();
try {
_callableStatement.setBytes(parameterName, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setDate(String parameterName, Date x) throws SQLException {
validateConnection();
try {
_callableStatement.setDate(parameterName, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setTime(String parameterName, Time x) throws SQLException {
validateConnection();
try {
_callableStatement.setTime(parameterName, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setTimestamp(String parameterName, Timestamp x) throws SQLException {
validateConnection();
try {
_callableStatement.setTimestamp(parameterName, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setAsciiStream(String parameterName, java.io.InputStream x, int length) throws SQLException {
validateConnection();
try {
_callableStatement.setAsciiStream(parameterName, x, length);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setBinaryStream(String parameterName, java.io.InputStream x, int length) throws SQLException {
validateConnection();
try {
_callableStatement.setBinaryStream(parameterName, x, length);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setObject(String parameterName, Object x, int targetSqlType, int scale) throws SQLException {
validateConnection();
try {
_callableStatement.setObject(parameterName, x, targetSqlType, scale);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setObject(String parameterName, Object x, int targetSqlType) throws SQLException {
validateConnection();
try {
_callableStatement.setObject(parameterName, x, targetSqlType);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setObject(String parameterName, Object x) throws SQLException {
validateConnection();
try {
_callableStatement.setObject(parameterName, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setCharacterStream(String parameterName, java.io.Reader x, int length) throws SQLException {
validateConnection();
try {
_callableStatement.setCharacterStream(parameterName, x, length);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setDate(String parameterName, Date x, Calendar cal) throws SQLException {
validateConnection();
try {
_callableStatement.setDate(parameterName, x, cal);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setTime(String parameterName, Time x, Calendar cal) throws SQLException {
validateConnection();
try {
_callableStatement.setTime(parameterName, x, cal);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setTimestamp(String parameterName, Timestamp x, Calendar cal) throws SQLException {
validateConnection();
try {
_callableStatement.setTimestamp(parameterName, x, cal);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setNull(String parameterName, int sqlType, String typeName) throws SQLException {
validateConnection();
try {
_callableStatement.setNull(parameterName, sqlType, typeName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public String getString(String parameterName) throws SQLException {
validateConnection();
try {
return _callableStatement.getString(parameterName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public boolean getBoolean(String parameterName) throws SQLException {
validateConnection();
try {
return _callableStatement.getBoolean(parameterName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return false;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public byte getByte(String parameterName) throws SQLException {
validateConnection();
try {
return _callableStatement.getByte(parameterName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Byte.MIN_VALUE;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public short getShort(String parameterName) throws SQLException {
validateConnection();
try {
return _callableStatement.getShort(parameterName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Short.MIN_VALUE;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public int getInt(String parameterName) throws SQLException {
validateConnection();
try {
return _callableStatement.getInt(parameterName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Integer.MIN_VALUE;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public long getLong(String parameterName) throws SQLException {
validateConnection();
try {
return _callableStatement.getLong(parameterName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Long.MIN_VALUE;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public float getFloat(String parameterName) throws SQLException {
validateConnection();
try {
return _callableStatement.getFloat(parameterName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Float.MIN_VALUE;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public double getDouble(String parameterName) throws SQLException {
validateConnection();
try {
return _callableStatement.getDouble(parameterName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Double.MIN_VALUE;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public byte[] getBytes(String parameterName) throws SQLException {
validateConnection();
try {
return _callableStatement.getBytes(parameterName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Date getDate(String parameterName) throws SQLException {
validateConnection();
try {
return _callableStatement.getDate(parameterName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Time getTime(String parameterName) throws SQLException {
validateConnection();
try {
return _callableStatement.getTime(parameterName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Timestamp getTimestamp(String parameterName) throws SQLException {
validateConnection();
try {
return _callableStatement.getTimestamp(parameterName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Object getObject(String parameterName) throws SQLException {
validateConnection();
try {
return _callableStatement.getObject(parameterName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public BigDecimal getBigDecimal(String parameterName) throws SQLException {
validateConnection();
try {
return _callableStatement.getBigDecimal(parameterName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Object getObject(String parameterName, java.util.Map map) throws SQLException {
validateConnection();
try {
return _callableStatement.getObject(parameterName, map);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Ref getRef(String parameterName) throws SQLException {
validateConnection();
try {
return _callableStatement.getRef(parameterName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Blob getBlob(String parameterName) throws SQLException {
validateConnection();
try {
return _callableStatement.getBlob(parameterName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Clob getClob(String parameterName) throws SQLException {
validateConnection();
try {
return _callableStatement.getClob(parameterName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Array getArray(String parameterName) throws SQLException {
validateConnection();
try {
return _callableStatement.getArray(parameterName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Date getDate(String parameterName, Calendar cal) throws SQLException {
validateConnection();
try {
return _callableStatement.getDate(parameterName, cal);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Time getTime(String parameterName, Calendar cal) throws SQLException {
validateConnection();
try {
return _callableStatement.getTime(parameterName, cal);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException {
validateConnection();
try {
return _callableStatement.getTimestamp(parameterName, cal);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the callable statement; SQLExceptions thrown from the
* callable statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public java.net.URL getURL(String parameterName) throws SQLException {
validateConnection();
try {
return _callableStatement.getURL(parameterName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/////// JDBC4 demarcation, do NOT put any JDBC3 code below this line ///////
/* (non-Javadoc)
* @see java.sql.CallableStatement#getCharacterStream(int)
*/
public Reader getCharacterStream(int parameterIndex) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getCharacterStream(java.lang.String)
*/
public Reader getCharacterStream(String parameterName) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getNCharacterStream(int)
*/
public Reader getNCharacterStream(int parameterIndex) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getNCharacterStream(java.lang.String)
*/
public Reader getNCharacterStream(String parameterName) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getNClob(int)
*/
public NClob getNClob(int parameterIndex) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getNClob(java.lang.String)
*/
public NClob getNClob(String parameterName) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getNString(int)
*/
public String getNString(int parameterIndex) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getNString(java.lang.String)
*/
public String getNString(String parameterName) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getRowId(int)
*/
public RowId getRowId(int parameterIndex) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getRowId(java.lang.String)
*/
public RowId getRowId(String parameterName) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getSQLXML(int)
*/
public SQLXML getSQLXML(int parameterIndex) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#getSQLXML(java.lang.String)
*/
public SQLXML getSQLXML(String parameterName) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setAsciiStream(java.lang.String, java.io.InputStream)
*/
public void setAsciiStream(String parameterName, InputStream x)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setAsciiStream(java.lang.String, java.io.InputStream, long)
*/
public void setAsciiStream(String parameterName, InputStream x, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setBinaryStream(java.lang.String, java.io.InputStream)
*/
public void setBinaryStream(String parameterName, InputStream x)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setBinaryStream(java.lang.String, java.io.InputStream, long)
*/
public void setBinaryStream(String parameterName, InputStream x, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setBlob(java.lang.String, java.sql.Blob)
*/
public void setBlob(String parameterName, Blob x) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setBlob(java.lang.String, java.io.InputStream)
*/
public void setBlob(String parameterName, InputStream inputStream)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setBlob(java.lang.String, java.io.InputStream, long)
*/
public void setBlob(String parameterName, InputStream inputStream,
long length) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setCharacterStream(java.lang.String, java.io.Reader)
*/
public void setCharacterStream(String parameterName, Reader reader)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setCharacterStream(java.lang.String, java.io.Reader, long)
*/
public void setCharacterStream(String parameterName, Reader reader,
long length) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setClob(java.lang.String, java.sql.Clob)
*/
public void setClob(String parameterName, Clob x) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setClob(java.lang.String, java.io.Reader)
*/
public void setClob(String parameterName, Reader reader)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setClob(java.lang.String, java.io.Reader, long)
*/
public void setClob(String parameterName, Reader reader, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setNCharacterStream(java.lang.String, java.io.Reader)
*/
public void setNCharacterStream(String parameterName, Reader value)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setNCharacterStream(java.lang.String, java.io.Reader, long)
*/
public void setNCharacterStream(String parameterName, Reader value,
long length) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setNClob(java.lang.String, java.sql.NClob)
*/
public void setNClob(String parameterName, NClob value) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setNClob(java.lang.String, java.io.Reader)
*/
public void setNClob(String parameterName, Reader reader)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setNClob(java.lang.String, java.io.Reader, long)
*/
public void setNClob(String parameterName, Reader reader, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setNString(java.lang.String, java.lang.String)
*/
public void setNString(String parameterName, String value)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setRowId(java.lang.String, java.sql.RowId)
*/
public void setRowId(String parameterName, RowId x) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.CallableStatement#setSQLXML(java.lang.String, java.sql.SQLXML)
*/
public void setSQLXML(String parameterName, SQLXML xmlObject)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setAsciiStream(int, java.io.InputStream)
*/
public void setAsciiStream(int parameterIndex, InputStream x)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setAsciiStream(int, java.io.InputStream, long)
*/
public void setAsciiStream(int parameterIndex, InputStream x, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setBinaryStream(int, java.io.InputStream)
*/
public void setBinaryStream(int parameterIndex, InputStream x)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setBinaryStream(int, java.io.InputStream, long)
*/
public void setBinaryStream(int parameterIndex, InputStream x, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setBlob(int, java.io.InputStream)
*/
public void setBlob(int parameterIndex, InputStream inputStream)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setBlob(int, java.io.InputStream, long)
*/
public void setBlob(int parameterIndex, InputStream inputStream, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setCharacterStream(int, java.io.Reader)
*/
public void setCharacterStream(int parameterIndex, Reader reader)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setCharacterStream(int, java.io.Reader, long)
*/
public void setCharacterStream(int parameterIndex, Reader reader,
long length) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setClob(int, java.io.Reader)
*/
public void setClob(int parameterIndex, Reader reader) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setClob(int, java.io.Reader, long)
*/
public void setClob(int parameterIndex, Reader reader, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNCharacterStream(int, java.io.Reader)
*/
public void setNCharacterStream(int parameterIndex, Reader value)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNCharacterStream(int, java.io.Reader, long)
*/
public void setNCharacterStream(int parameterIndex, Reader value,
long length) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNClob(int, java.sql.NClob)
*/
public void setNClob(int parameterIndex, NClob value) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNClob(int, java.io.Reader)
*/
public void setNClob(int parameterIndex, Reader reader) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNClob(int, java.io.Reader, long)
*/
public void setNClob(int parameterIndex, Reader reader, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNString(int, java.lang.String)
*/
public void setNString(int parameterIndex, String value)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setRowId(int, java.sql.RowId)
*/
public void setRowId(int parameterIndex, RowId x) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setSQLXML(int, java.sql.SQLXML)
*/
public void setSQLXML(int parameterIndex, SQLXML xmlObject)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Statement#isClosed()
*/
public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Statement#isPoolable()
*/
public boolean isPoolable() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Statement#setPoolable(boolean)
*/
public void setPoolable(boolean poolable) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#isWrapperFor(java.lang.Class)
*/
public boolean isWrapperFor(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#unwrap(java.lang.Class)
*/
public Object unwrap(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbcx/proxy/ConnectionProxy.java 0000644 0001750 0001750 00000063156 11316672660 030470 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbcx.proxy;
import java.sql.*;
import java.util.Map;
import java.util.Properties;
import net.sourceforge.jtds.jdbc.*;
import net.sourceforge.jtds.jdbcx.*;
/**
* This class would be better implemented as a java.lang.reflect.Proxy. However, this
* feature was not added until 1.3 and reflection performance was not improved until 1.4.
* Since the driver still needs to be compatible with 1.2 and 1.3 this class is used
* to delegate the calls to the connection with minimal overhead.
*
* @version $Id: ConnectionProxy.java,v 1.7.2.3 2009/12/30 08:45:34 ickzon Exp $
*/
public class ConnectionProxy implements Connection {
private PooledConnection _pooledConnection;
private ConnectionJDBC2 _connection;
private boolean _closed;
/**
* Constructs a new connection proxy.
*/
public ConnectionProxy(PooledConnection pooledConnection,
Connection connection) {
_pooledConnection = pooledConnection;
_connection = (ConnectionJDBC2) connection;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void clearWarnings() throws SQLException {
validateConnection();
try {
_connection.clearWarnings();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*/
public void close() {
if (_closed) {
return;
}
_pooledConnection.fireConnectionEvent(true, null);
_closed = true;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void commit() throws SQLException {
validateConnection();
try {
_connection.commit();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public Statement createStatement() throws SQLException {
validateConnection();
try {
return new StatementProxy(this, (JtdsStatement) _connection.createStatement());
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
validateConnection();
try {
return new StatementProxy(this, (JtdsStatement) _connection.createStatement(resultSetType, resultSetConcurrency));
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
validateConnection();
try {
return new StatementProxy(this, (JtdsStatement) _connection.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability));
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public boolean getAutoCommit() throws SQLException {
validateConnection();
try {
return _connection.getAutoCommit();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return false;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public String getCatalog() throws SQLException {
validateConnection();
try {
return _connection.getCatalog();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public int getHoldability() throws SQLException {
validateConnection();
try {
return _connection.getHoldability();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Integer.MIN_VALUE;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public int getTransactionIsolation() throws SQLException {
validateConnection();
try {
return _connection.getTransactionIsolation();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Integer.MIN_VALUE;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public Map getTypeMap() throws SQLException {
validateConnection();
try {
return _connection.getTypeMap();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public SQLWarning getWarnings() throws SQLException {
validateConnection();
try {
return _connection.getWarnings();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public DatabaseMetaData getMetaData() throws SQLException {
validateConnection();
try {
return _connection.getMetaData();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public boolean isClosed() throws SQLException {
if (_closed) {
return true;
}
try {
return _connection.isClosed();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return _closed;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public boolean isReadOnly() throws SQLException {
validateConnection();
try {
return _connection.isReadOnly();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return false;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public String nativeSQL(String sql) throws SQLException {
validateConnection();
try {
return _connection.nativeSQL(sql);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public CallableStatement prepareCall(String sql) throws SQLException {
validateConnection();
try {
return new CallableStatementProxy(this, (JtdsCallableStatement) _connection.prepareCall(sql));
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
validateConnection();
try {
return new CallableStatementProxy(this, (JtdsCallableStatement) _connection.prepareCall(sql, resultSetType, resultSetConcurrency));
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
validateConnection();
try {
return new CallableStatementProxy(this, (JtdsCallableStatement) _connection.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability));
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public PreparedStatement prepareStatement(String sql) throws SQLException {
validateConnection();
try {
return new PreparedStatementProxy(this, (JtdsPreparedStatement) _connection.prepareStatement(sql));
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
validateConnection();
try {
return new PreparedStatementProxy(this, (JtdsPreparedStatement) _connection.prepareStatement(sql, autoGeneratedKeys));
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
validateConnection();
try {
return new PreparedStatementProxy(this, (JtdsPreparedStatement) _connection.prepareStatement(sql, columnIndexes));
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
validateConnection();
try {
return new PreparedStatementProxy(this, (JtdsPreparedStatement) _connection.prepareStatement(sql, columnNames));
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
validateConnection();
try {
return new PreparedStatementProxy(this, (JtdsPreparedStatement) _connection.prepareStatement(sql, resultSetType, resultSetConcurrency));
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
validateConnection();
try {
return new PreparedStatementProxy(this, (JtdsPreparedStatement) _connection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability));
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
validateConnection();
try {
_connection.releaseSavepoint(savepoint);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void rollback() throws SQLException {
validateConnection();
try {
_connection.rollback();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void rollback(Savepoint savepoint) throws SQLException {
validateConnection();
try {
_connection.rollback(savepoint);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setAutoCommit(boolean autoCommit) throws SQLException {
validateConnection();
try {
_connection.setAutoCommit(autoCommit);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setCatalog(String catalog) throws SQLException {
validateConnection();
try {
_connection.setCatalog(catalog);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setHoldability(int holdability) throws SQLException {
validateConnection();
try {
_connection.setHoldability(holdability);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setReadOnly(boolean readOnly) throws SQLException {
validateConnection();
try {
_connection.setReadOnly(readOnly);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public Savepoint setSavepoint() throws SQLException {
validateConnection();
try {
return _connection.setSavepoint();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public Savepoint setSavepoint(String name) throws SQLException {
validateConnection();
try {
return _connection.setSavepoint(name);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setTransactionIsolation(int level) throws SQLException {
validateConnection();
try {
_connection.setTransactionIsolation(level);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the connection; SQLExceptions thrown from the connection
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setTypeMap(Map map) throws SQLException {
validateConnection();
try {
_connection.setTypeMap(map);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Validates the connection state.
*/
private void validateConnection() throws SQLException {
if (_closed) {
throw new SQLException(Messages.get("error.conproxy.noconn"), "HY010");
}
}
/**
* Processes SQLExceptions.
*/
void processSQLException(SQLException sqlException) throws SQLException {
_pooledConnection.fireConnectionEvent(false, sqlException);
throw sqlException;
}
/**
* Closes the proxy, releasing the connection.
*/
protected void finalize() {
close();
}
/////// JDBC4 demarcation, do NOT put any JDBC3 code below this line ///////
/* (non-Javadoc)
* @see java.sql.Connection#createArrayOf(java.lang.String, java.lang.Object[])
*/
public Array createArrayOf(String typeName, Object[] elements)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Connection#createBlob()
*/
public Blob createBlob() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Connection#createClob()
*/
public Clob createClob() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Connection#createNClob()
*/
public NClob createNClob() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Connection#createSQLXML()
*/
public SQLXML createSQLXML() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Connection#createStruct(java.lang.String, java.lang.Object[])
*/
public Struct createStruct(String typeName, Object[] attributes)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Connection#getClientInfo()
*/
public Properties getClientInfo() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Connection#getClientInfo(java.lang.String)
*/
public String getClientInfo(String name) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Connection#isValid(int)
*/
public boolean isValid(int timeout) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Connection#setClientInfo(java.util.Properties)
*/
public void setClientInfo(Properties properties)
throws SQLClientInfoException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Connection#setClientInfo(java.lang.String, java.lang.String)
*/
public void setClientInfo(String name, String value)
throws SQLClientInfoException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#isWrapperFor(java.lang.Class)
*/
public boolean isWrapperFor(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#unwrap(java.lang.Class)
*/
public Object unwrap(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbcx/proxy/StatementProxy.java 0000644 0001750 0001750 00000055177 11316672660 030341 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbcx.proxy;
import java.sql.*;
import net.sourceforge.jtds.jdbc.*;
/**
* This class would be better implemented as a java.lang.reflect.Proxy. However, this
* feature was not added until 1.3 and reflection performance was not improved until 1.4.
* Since the driver still needs to be compatible with 1.2 and 1.3 this class is used
* to delegate the calls to a statement with minimal overhead.
*
* @version $Id: StatementProxy.java,v 1.4.4.3 2009/12/30 08:45:34 ickzon Exp $
*/
public class StatementProxy implements Statement {
private ConnectionProxy _connection;
private JtdsStatement _statement;
StatementProxy(ConnectionProxy connection, JtdsStatement statement) {
_connection = connection;
_statement = statement;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public ResultSet executeQuery(String sql) throws SQLException {
validateConnection();
try {
return _statement.executeQuery(sql);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public int executeUpdate(String sql) throws SQLException {
validateConnection();
try {
return _statement.executeUpdate(sql);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Integer.MIN_VALUE;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void close() throws SQLException {
validateConnection();
try {
_statement.close();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public int getMaxFieldSize() throws SQLException {
validateConnection();
try {
return _statement.getMaxFieldSize();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Integer.MIN_VALUE;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setMaxFieldSize(int max) throws SQLException {
validateConnection();
try {
_statement.setMaxFieldSize(max);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public int getMaxRows() throws SQLException {
validateConnection();
try {
return _statement.getMaxRows();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Integer.MIN_VALUE;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setMaxRows(int max) throws SQLException {
validateConnection();
try {
_statement.setMaxRows(max);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setEscapeProcessing(boolean enable) throws SQLException {
validateConnection();
try {
_statement.setEscapeProcessing(enable);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public int getQueryTimeout() throws SQLException {
validateConnection();
try {
return _statement.getQueryTimeout();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Integer.MIN_VALUE;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setQueryTimeout(int seconds) throws SQLException {
validateConnection();
try {
_statement.setQueryTimeout(seconds);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void cancel() throws SQLException {
validateConnection();
try {
_statement.cancel();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public SQLWarning getWarnings() throws SQLException {
validateConnection();
try {
return _statement.getWarnings();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void clearWarnings() throws SQLException {
validateConnection();
try {
_statement.clearWarnings();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setCursorName(String name) throws SQLException {
validateConnection();
try {
_statement.setCursorName(name);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public boolean execute(String sql) throws SQLException {
validateConnection();
try {
return _statement.execute(sql);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return false;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public ResultSet getResultSet() throws SQLException {
validateConnection();
try {
return _statement.getResultSet();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public int getUpdateCount() throws SQLException {
validateConnection();
try {
return _statement.getUpdateCount();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Integer.MIN_VALUE;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public boolean getMoreResults() throws SQLException {
validateConnection();
try {
return _statement.getMoreResults();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return false;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setFetchDirection(int direction) throws SQLException {
validateConnection();
try {
_statement.setFetchDirection(direction);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public int getFetchDirection() throws SQLException {
validateConnection();
try {
return _statement.getFetchDirection();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Integer.MIN_VALUE;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setFetchSize(int rows) throws SQLException {
validateConnection();
try {
_statement.setFetchSize(rows);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public int getFetchSize() throws SQLException {
validateConnection();
try {
return _statement.getFetchSize();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Integer.MIN_VALUE;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public int getResultSetConcurrency() throws SQLException {
validateConnection();
try {
return _statement.getResultSetConcurrency();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Integer.MIN_VALUE;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public int getResultSetType() throws SQLException {
validateConnection();
try {
return _statement.getResultSetType();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Integer.MIN_VALUE;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void addBatch(String sql) throws SQLException {
validateConnection();
try {
_statement.addBatch(sql);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public void clearBatch() throws SQLException {
validateConnection();
try {
_statement.clearBatch();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public int[] executeBatch() throws SQLException {
validateConnection();
try {
return _statement.executeBatch();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public Connection getConnection() throws SQLException {
validateConnection();
try {
return _statement.getConnection();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public boolean getMoreResults(int current) throws SQLException {
validateConnection();
try {
return _statement.getMoreResults(current);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return false;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public ResultSet getGeneratedKeys() throws SQLException {
validateConnection();
try {
return _statement.getGeneratedKeys();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
validateConnection();
try {
return _statement.executeUpdate(sql, autoGeneratedKeys);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Integer.MIN_VALUE;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
validateConnection();
try {
return _statement.executeUpdate(sql, columnIndexes);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Integer.MIN_VALUE;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public int executeUpdate(String sql, String[] columnNames) throws SQLException {
validateConnection();
try {
return _statement.executeUpdate(sql, columnNames);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Integer.MIN_VALUE;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
validateConnection();
try {
return _statement.execute(sql, autoGeneratedKeys);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return false;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public boolean execute(String sql, int[] columnIndexes) throws SQLException {
validateConnection();
try {
return _statement.execute(sql, columnIndexes);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return false;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public boolean execute(String sql, String[] columnNames) throws SQLException {
validateConnection();
try {
return _statement.execute(sql, columnNames);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return false;
}
/**
* Delgates calls to the statement; SQLExceptions thrown from the statement
* will cause an event to be fired on the connection pool listeners.
*
* @throws SQLException if an error occurs
*/
public int getResultSetHoldability() throws SQLException {
validateConnection();
try {
return _statement.getResultSetHoldability();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Integer.MIN_VALUE;
}
/**
* Validates the connection state.
*/
protected void validateConnection() throws SQLException {
if (_connection.isClosed()) {
throw new SQLException(Messages.get("error.conproxy.noconn"), "HY010");
}
}
/**
* Processes SQLExceptions.
*/
protected void processSQLException(SQLException sqlException) throws SQLException {
_connection.processSQLException(sqlException);
throw sqlException;
}
/////// JDBC4 demarcation, do NOT put any JDBC3 code below this line ///////
/* (non-Javadoc)
* @see java.sql.Statement#isClosed()
*/
public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Statement#isPoolable()
*/
public boolean isPoolable() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Statement#setPoolable(boolean)
*/
public void setPoolable(boolean poolable) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#isWrapperFor(java.lang.Class)
*/
public boolean isWrapperFor(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#unwrap(java.lang.Class)
*/
public Object unwrap(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbcx/proxy/PreparedStatementProxy.java 0000644 0001750 0001750 00000072002 11316672660 032006 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbcx.proxy;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.sql.*;
import java.util.Calendar;
import net.sourceforge.jtds.jdbc.*;
/**
* This class would be better implemented as a java.lang.reflect.Proxy. However, this
* feature was not added until 1.3 and reflection performance was not improved until 1.4.
* Since the driver still needs to be compatible with 1.2 and 1.3 this class is used
* to delegate the calls to a prepared statement with minimal overhead.
*
* @version $Id: PreparedStatementProxy.java,v 1.3.4.3 2009/12/30 08:45:34 ickzon Exp $
*/
public class PreparedStatementProxy
extends StatementProxy
implements PreparedStatement {
private JtdsPreparedStatement _preparedStatement;
PreparedStatementProxy(ConnectionProxy connection, JtdsPreparedStatement preparedStatement) {
super(connection, preparedStatement);
_preparedStatement = preparedStatement;
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public ResultSet executeQuery() throws SQLException {
validateConnection();
try {
return _preparedStatement.executeQuery();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public int executeUpdate() throws SQLException {
validateConnection();
try {
return _preparedStatement.executeUpdate();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return Integer.MIN_VALUE;
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setNull(int parameterIndex, int sqlType) throws SQLException {
validateConnection();
try {
_preparedStatement.setNull(parameterIndex, sqlType);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setBoolean(int parameterIndex, boolean x) throws SQLException {
validateConnection();
try {
_preparedStatement.setBoolean(parameterIndex, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setByte(int parameterIndex, byte x) throws SQLException {
validateConnection();
try {
_preparedStatement.setByte(parameterIndex, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setShort(int parameterIndex, short x) throws SQLException {
validateConnection();
try {
_preparedStatement.setShort(parameterIndex, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setInt(int parameterIndex, int x) throws SQLException {
validateConnection();
try {
_preparedStatement.setInt(parameterIndex, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setLong(int parameterIndex, long x) throws SQLException {
validateConnection();
try {
_preparedStatement.setLong(parameterIndex, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setFloat(int parameterIndex, float x) throws SQLException {
validateConnection();
try {
_preparedStatement.setFloat(parameterIndex, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setDouble(int parameterIndex, double x) throws SQLException {
validateConnection();
try {
_preparedStatement.setDouble(parameterIndex, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException {
validateConnection();
try {
_preparedStatement.setBigDecimal(parameterIndex, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setString(int parameterIndex, String x) throws SQLException {
validateConnection();
try {
_preparedStatement.setString(parameterIndex, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setBytes(int parameterIndex, byte[] x) throws SQLException {
validateConnection();
try {
_preparedStatement.setBytes(parameterIndex, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setDate(int parameterIndex, java.sql.Date x) throws SQLException {
validateConnection();
try {
_preparedStatement.setDate(parameterIndex, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setTime(int parameterIndex, java.sql.Time x) throws SQLException {
validateConnection();
try {
_preparedStatement.setTime(parameterIndex, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setTimestamp(int parameterIndex, java.sql.Timestamp x) throws SQLException {
validateConnection();
try {
_preparedStatement.setTimestamp(parameterIndex, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setAsciiStream(int parameterIndex, java.io.InputStream x, int length) throws SQLException {
validateConnection();
try {
_preparedStatement.setAsciiStream(parameterIndex, x, length);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setUnicodeStream(int parameterIndex, java.io.InputStream x, int length) throws SQLException {
validateConnection();
try {
_preparedStatement.setUnicodeStream(parameterIndex, x, length);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setBinaryStream(int parameterIndex, java.io.InputStream x, int length) throws SQLException {
validateConnection();
try {
_preparedStatement.setBinaryStream(parameterIndex, x, length);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void clearParameters() throws SQLException {
validateConnection();
try {
_preparedStatement.clearParameters();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setObject(int parameterIndex, Object x, int targetSqlType, int scale) throws SQLException {
validateConnection();
try {
_preparedStatement.setObject(parameterIndex, x, targetSqlType, scale);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {
validateConnection();
try {
_preparedStatement.setObject(parameterIndex, x, targetSqlType);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setObject(int parameterIndex, Object x) throws SQLException {
validateConnection();
try {
_preparedStatement.setObject(parameterIndex, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public boolean execute() throws SQLException {
validateConnection();
try {
return _preparedStatement.execute();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return false;
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void addBatch() throws SQLException {
validateConnection();
try {
_preparedStatement.addBatch();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setCharacterStream(int parameterIndex, java.io.Reader x, int length) throws SQLException {
validateConnection();
try {
_preparedStatement.setCharacterStream(parameterIndex, x, length);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setRef(int parameterIndex, Ref x) throws SQLException {
validateConnection();
try {
_preparedStatement.setRef(parameterIndex, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setBlob(int parameterIndex, Blob x) throws SQLException {
validateConnection();
try {
_preparedStatement.setBlob(parameterIndex, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setClob(int parameterIndex, Clob x) throws SQLException {
validateConnection();
try {
_preparedStatement.setClob(parameterIndex, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setArray(int parameterIndex, Array x) throws SQLException {
validateConnection();
try {
_preparedStatement.setArray(parameterIndex, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public ResultSetMetaData getMetaData() throws SQLException {
validateConnection();
try {
return _preparedStatement.getMetaData();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setDate(int parameterIndex, java.sql.Date x, Calendar cal) throws SQLException {
validateConnection();
try {
_preparedStatement.setDate(parameterIndex, x, cal);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setTime(int parameterIndex, java.sql.Time x, Calendar cal) throws SQLException {
validateConnection();
try {
_preparedStatement.setTime(parameterIndex, x, cal);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setTimestamp(int parameterIndex, java.sql.Timestamp x, Calendar cal) throws SQLException {
validateConnection();
try {
_preparedStatement.setTimestamp(parameterIndex, x, cal);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setNull (int parameterIndex, int sqlType, String typeName) throws SQLException {
validateConnection();
try {
_preparedStatement.setNull(parameterIndex, sqlType, typeName);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public void setURL(int parameterIndex, java.net.URL x) throws SQLException {
validateConnection();
try {
_preparedStatement.setURL(parameterIndex, x);
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
}
/**
* Delgates calls to the prepared statement; SQLExceptions thrown from the
* prepared statement will cause an event to be fired on the connection
* pool listeners.
*
* @throws SQLException if an error occurs
*/
public ParameterMetaData getParameterMetaData() throws SQLException {
validateConnection();
try {
return _preparedStatement.getParameterMetaData();
} catch (SQLException sqlException) {
processSQLException(sqlException);
}
return null;
}
/////// JDBC4 demarcation, do NOT put any JDBC3 code below this line ///////
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setAsciiStream(int, java.io.InputStream)
*/
public void setAsciiStream(int parameterIndex, InputStream x)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setAsciiStream(int, java.io.InputStream, long)
*/
public void setAsciiStream(int parameterIndex, InputStream x, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setBinaryStream(int, java.io.InputStream)
*/
public void setBinaryStream(int parameterIndex, InputStream x)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setBinaryStream(int, java.io.InputStream, long)
*/
public void setBinaryStream(int parameterIndex, InputStream x, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setBlob(int, java.io.InputStream)
*/
public void setBlob(int parameterIndex, InputStream inputStream)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setBlob(int, java.io.InputStream, long)
*/
public void setBlob(int parameterIndex, InputStream inputStream, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setCharacterStream(int, java.io.Reader)
*/
public void setCharacterStream(int parameterIndex, Reader reader)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setCharacterStream(int, java.io.Reader, long)
*/
public void setCharacterStream(int parameterIndex, Reader reader,
long length) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setClob(int, java.io.Reader)
*/
public void setClob(int parameterIndex, Reader reader) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setClob(int, java.io.Reader, long)
*/
public void setClob(int parameterIndex, Reader reader, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNCharacterStream(int, java.io.Reader)
*/
public void setNCharacterStream(int parameterIndex, Reader value)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNCharacterStream(int, java.io.Reader, long)
*/
public void setNCharacterStream(int parameterIndex, Reader value,
long length) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNClob(int, java.sql.NClob)
*/
public void setNClob(int parameterIndex, NClob value) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNClob(int, java.io.Reader)
*/
public void setNClob(int parameterIndex, Reader reader) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNClob(int, java.io.Reader, long)
*/
public void setNClob(int parameterIndex, Reader reader, long length)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setNString(int, java.lang.String)
*/
public void setNString(int parameterIndex, String value)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setRowId(int, java.sql.RowId)
*/
public void setRowId(int parameterIndex, RowId x) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.PreparedStatement#setSQLXML(int, java.sql.SQLXML)
*/
public void setSQLXML(int parameterIndex, SQLXML xmlObject)
throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Statement#isClosed()
*/
public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Statement#isPoolable()
*/
public boolean isPoolable() throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Statement#setPoolable(boolean)
*/
public void setPoolable(boolean poolable) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#isWrapperFor(java.lang.Class)
*/
public boolean isWrapperFor(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#unwrap(java.lang.Class)
*/
public Object unwrap(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbcx/JtdsDataSource.java 0000644 0001750 0001750 00000063220 11316672660 027015 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbcx;
import java.io.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.Referenceable;
import javax.naming.StringRefAddr;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.DataSource;
import javax.sql.XAConnection;
import javax.sql.XADataSource;
import net.sourceforge.jtds.jdbc.DefaultProperties;
import net.sourceforge.jtds.jdbc.Driver;
import net.sourceforge.jtds.jdbc.Messages;
import net.sourceforge.jtds.jdbc.Support;
import net.sourceforge.jtds.util.Logger;
/**
* The jTDS DataSource, ConnectionPoolDataSource and
* XADataSource implementation.
*
* @author Alin Sinplean
* @since jTDS 0.3
* @version $Id: JtdsDataSource.java,v 1.42.2.4 2009/12/30 08:45:34 ickzon Exp $
*/
public class JtdsDataSource
implements DataSource, ConnectionPoolDataSource, XADataSource, Referenceable, Serializable {
/** Serial version UID. */
static final long serialVersionUID = 01010000L;
protected String serverName;
protected String serverType;
protected String portNumber;
protected String databaseName;
protected String tdsVersion;
protected String charset;
protected String language;
protected String domain;
protected String useNTLMV2;
protected String instance;
protected String lastUpdateCount;
protected String sendStringParametersAsUnicode;
protected String namedPipe;
protected String macAddress;
protected String prepareSql;
protected String packetSize;
protected String tcpNoDelay;
protected String user;
protected String password;
protected String loginTimeout;
protected String lobBuffer;
protected String maxStatements;
protected String appName;
protected String progName;
protected String wsid;
protected String xaEmulation;
protected String logFile;
protected String socketTimeout;
protected String socketKeepAlive;
protected String processId;
protected String ssl;
protected String batchSize;
protected String bufferDir;
protected String bufferMaxMemory;
protected String bufferMinPackets;
protected String cacheMetaData;
protected String useCursors;
protected String useLOBs;
protected String bindAddress;
protected String useJCIFS;
protected String description;
/**
* Driver instance used for obtaining connections.
*/
private static final Driver driver = new Driver();
/**
* Constructs a new datasource.
*/
public JtdsDataSource() {
// Do not set default property values here. Properties whose default
// values depend on server type will likely be incorrect unless the
// user specified them explicitly.
}
/**
* Returns a new XA database connection.
*
* @return a new database connection
* @throws SQLException if an error occurs
*/
public XAConnection getXAConnection() throws SQLException {
return new JtdsXAConnection(this, getConnection(user, password));
}
/**
* Returns a new XA database connection for the user and password specified.
*
* @param user the user name to connect with
* @param password the password to connect with
* @return a new database connection
* @throws SQLException if an error occurs
*/
public XAConnection getXAConnection(String user, String password) throws SQLException {
return new JtdsXAConnection(this, getConnection(user, password));
}
/**
* Returns a new database connection.
*
* @return a new database connection
* @throws SQLException if an error occurs
*/
public Connection getConnection() throws SQLException {
return getConnection(user, password);
}
/**
* Returns a new database connection for the user and password specified.
*
* @param user the user name to connect with
* @param password the password to connect with
* @return a new database connection
* @throws SQLException if an error occurs
*/
public Connection getConnection(String user, String password)
throws SQLException {
if (serverName == null) {
throw new SQLException(Messages.get("error.connection.nohost"), "08001");
}
//
// This maybe the only way to initialise the logging subsystem
// with some containers such as JBOSS.
//
if (getLogWriter() == null && logFile != null && logFile.length() > 0) {
// Try to initialise a PrintWriter
try {
setLogWriter(new PrintWriter(new FileOutputStream(logFile), true));
} catch (IOException e) {
System.err.println("jTDS: Failed to set log file " + e);
}
}
Properties props = new Properties();
addNonNullProperties(props, user, password);
String url;
try {
// Determine the server type (for the URL stub) or use the default
int serverTypeDef = (serverType == null) ? 0
: Integer.parseInt(serverType);
url = "jdbc:jtds:"
+ DefaultProperties.getServerTypeWithDefault(serverTypeDef)
+ ':';
} catch (RuntimeException ex) {
SQLException sqlException = new SQLException(
Messages.get("error.connection.servertype", ex.toString()), "08001");
Support.linkException(sqlException, ex);
throw sqlException;
}
// Connect with the URL stub and set properties. The defaults will be
// filled in by connect().
return driver.connect(url, props);
}
public Reference getReference() throws NamingException {
Reference ref = new Reference(getClass().getName(),
JtdsObjectFactory.class.getName(),
null);
ref.add(new StringRefAddr(Messages.get(Driver.SERVERNAME), serverName));
ref.add(new StringRefAddr(Messages.get(Driver.SERVERTYPE), serverType));
ref.add(new StringRefAddr(Messages.get(Driver.PORTNUMBER), portNumber));
ref.add(new StringRefAddr(Messages.get(Driver.DATABASENAME), databaseName));
ref.add(new StringRefAddr(Messages.get(Driver.TDS), tdsVersion));
ref.add(new StringRefAddr(Messages.get(Driver.CHARSET), charset));
ref.add(new StringRefAddr(Messages.get(Driver.LANGUAGE), language));
ref.add(new StringRefAddr(Messages.get(Driver.DOMAIN), domain));
ref.add(new StringRefAddr(Messages.get(Driver.USENTLMV2), useNTLMV2));
ref.add(new StringRefAddr(Messages.get(Driver.INSTANCE), instance));
ref.add(new StringRefAddr(Messages.get(Driver.LASTUPDATECOUNT), lastUpdateCount));
ref.add(new StringRefAddr(Messages.get(Driver.SENDSTRINGPARAMETERSASUNICODE), sendStringParametersAsUnicode));
ref.add(new StringRefAddr(Messages.get(Driver.NAMEDPIPE), namedPipe));
ref.add(new StringRefAddr(Messages.get(Driver.MACADDRESS), macAddress));
ref.add(new StringRefAddr(Messages.get(Driver.PREPARESQL), prepareSql));
ref.add(new StringRefAddr(Messages.get(Driver.PACKETSIZE), packetSize));
ref.add(new StringRefAddr(Messages.get(Driver.TCPNODELAY), tcpNoDelay));
ref.add(new StringRefAddr(Messages.get(Driver.XAEMULATION), xaEmulation));
ref.add(new StringRefAddr(Messages.get(Driver.USER), user));
ref.add(new StringRefAddr(Messages.get(Driver.PASSWORD), password));
ref.add(new StringRefAddr(Messages.get(Driver.LOGINTIMEOUT), loginTimeout));
ref.add(new StringRefAddr(Messages.get(Driver.SOTIMEOUT), socketTimeout));
ref.add(new StringRefAddr(Messages.get(Driver.SOKEEPALIVE), socketKeepAlive));
ref.add(new StringRefAddr(Messages.get(Driver.PROCESSID), processId));
ref.add(new StringRefAddr(Messages.get(Driver.LOBBUFFER), lobBuffer));
ref.add(new StringRefAddr(Messages.get(Driver.MAXSTATEMENTS), maxStatements));
ref.add(new StringRefAddr(Messages.get(Driver.APPNAME), appName));
ref.add(new StringRefAddr(Messages.get(Driver.PROGNAME), progName));
ref.add(new StringRefAddr(Messages.get(Driver.WSID), wsid));
ref.add(new StringRefAddr(Messages.get(Driver.LOGFILE), logFile));
ref.add(new StringRefAddr(Messages.get(Driver.SSL), ssl));
ref.add(new StringRefAddr(Messages.get(Driver.BATCHSIZE), batchSize));
ref.add(new StringRefAddr(Messages.get(Driver.BUFFERDIR), bufferDir));
ref.add(new StringRefAddr(Messages.get(Driver.BUFFERMAXMEMORY), bufferMaxMemory));
ref.add(new StringRefAddr(Messages.get(Driver.BUFFERMINPACKETS), bufferMinPackets));
ref.add(new StringRefAddr(Messages.get(Driver.CACHEMETA), cacheMetaData));
ref.add(new StringRefAddr(Messages.get(Driver.USECURSORS), useCursors));
ref.add(new StringRefAddr(Messages.get(Driver.USELOBS), useLOBs));
ref.add(new StringRefAddr(Messages.get(Driver.BINDADDRESS), bindAddress));
ref.add(new StringRefAddr(Messages.get(Driver.USEJCIFS), useJCIFS));
ref.add(new StringRefAddr("description", description));
return ref;
}
//
// ConnectionPoolDataSource methods
//
/**
* Returns a new pooled database connection.
*
* @return a new pooled database connection
* @throws SQLException if an error occurs
*/
public javax.sql.PooledConnection getPooledConnection()
throws SQLException {
return getPooledConnection(user, password);
}
/**
* Returns a new pooled database connection for the user and password specified.
*
* @param user the user name to connect with
* @param password the password to connect with
* @return a new pooled database connection
* @throws SQLException if an error occurs
*/
public synchronized javax.sql.PooledConnection getPooledConnection(String user,
String password)
throws SQLException {
return new net.sourceforge.jtds.jdbcx.PooledConnection(getConnection(user, password));
}
//
// Getters and setters
//
public PrintWriter getLogWriter() throws SQLException {
return Logger.getLogWriter();
}
public void setLogWriter(PrintWriter out) throws SQLException {
Logger.setLogWriter(out);
}
public void setLoginTimeout(int loginTimeout) throws SQLException {
this.loginTimeout = String.valueOf(loginTimeout);
}
public int getLoginTimeout() throws SQLException {
if (loginTimeout == null) {
return 0;
}
return Integer.parseInt(loginTimeout);
}
public void setSocketTimeout(int socketTimeout) throws SQLException {
this.socketTimeout = String.valueOf(socketTimeout);
}
public void setSocketKeepAlive(boolean socketKeepAlive) throws SQLException {
this.socketKeepAlive = String.valueOf(socketKeepAlive);
}
public void setProcessId(String processId) throws SQLException {
this.processId = String.valueOf(processId);
}
public int getSocketTimeout() throws SQLException {
if (socketTimeout == null) {
return 0;
}
return Integer.parseInt(socketTimeout);
}
public boolean getSocketKeepAlive() throws SQLException {
return Boolean.valueOf(socketKeepAlive).booleanValue();
}
public String getProcessId() throws SQLException {
return processId;
}
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
public String getDatabaseName() {
return databaseName;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
public void setPortNumber(int portNumber) {
this.portNumber = String.valueOf(portNumber);
}
public int getPortNumber() {
if (portNumber == null) {
return 0;
}
return Integer.parseInt(portNumber);
}
public void setServerName(String serverName) {
this.serverName = serverName;
}
public String getServerName() {
return serverName;
}
public void setUser(String user) {
this.user = user;
}
public String getUser() {
return user;
}
public void setTds(String tds) {
this.tdsVersion = tds;
}
public String getTds() {
return tdsVersion;
}
// TODO Use sqlserver/sybase for this (instead of numeric values)
public void setServerType(int serverType) {
this.serverType = String.valueOf(serverType);
}
public int getServerType() {
if (serverType == null) {
return 0;
}
return Integer.parseInt(serverType);
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getUseNTLMV2() {
return useNTLMV2;
}
public void setUseNTLMV2(String usentlmv2) {
this.useNTLMV2 = usentlmv2;
}
public String getInstance() {
return instance;
}
public void setInstance(String instance) {
this.instance = instance;
}
public boolean getSendStringParametersAsUnicode() {
return Boolean.valueOf(sendStringParametersAsUnicode).booleanValue();
}
public void setSendStringParametersAsUnicode(boolean sendStringParametersAsUnicode) {
this.sendStringParametersAsUnicode = String.valueOf(sendStringParametersAsUnicode);
}
public boolean getNamedPipe() {
return Boolean.valueOf(namedPipe).booleanValue();
}
public void setNamedPipe(boolean namedPipe) {
this.namedPipe = String.valueOf(namedPipe);
}
public boolean getLastUpdateCount() {
return Boolean.valueOf(lastUpdateCount).booleanValue();
}
public void setLastUpdateCount(boolean lastUpdateCount) {
this.lastUpdateCount = String.valueOf(lastUpdateCount);
}
public boolean getXaEmulation() {
return Boolean.valueOf(xaEmulation).booleanValue();
}
public void setXaEmulation(boolean xaEmulation) {
this.xaEmulation = String.valueOf(xaEmulation);
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getMacAddress() {
return macAddress;
}
public void setMacAddress(String macAddress) {
this.macAddress = macAddress;
}
public void setPacketSize(int packetSize) {
this.packetSize = String.valueOf(packetSize);
}
public int getPacketSize() {
if (packetSize == null) {
return 0;
}
return Integer.parseInt(packetSize);
}
public boolean getTcpNoDelay() {
return Boolean.valueOf(tcpNoDelay).booleanValue();
}
public void setTcpNoDelay(boolean tcpNoDelay) {
this.tcpNoDelay = String.valueOf(tcpNoDelay);
}
public void setPrepareSql(int prepareSql) {
this.prepareSql = String.valueOf(prepareSql);
}
public int getPrepareSql() {
if (prepareSql == null) {
return 0;
}
return Integer.parseInt(prepareSql);
}
public void setLobBuffer(long lobBuffer) {
this.lobBuffer = String.valueOf(lobBuffer);
}
public long getLobBuffer() {
if (lobBuffer == null) {
return 0;
}
return Long.parseLong(lobBuffer);
}
public void setMaxStatements(int maxStatements) {
this.maxStatements = String.valueOf(maxStatements);
}
public int getMaxStatements() {
if (maxStatements == null) {
return 0;
}
return Integer.parseInt(maxStatements);
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getAppName() {
return appName;
}
public void setProgName(String progName) {
this.progName = progName;
}
public String getProgName() {
return progName;
}
public void setWsid(String wsid) {
this.wsid = wsid;
}
public String getWsid() {
return wsid;
}
public void setLogFile(String logFile) {
this.logFile = logFile;
}
public String getLogFile() {
return logFile;
}
public void setSsl(String ssl) {
this.ssl = ssl;
}
public String getSsl() {
return ssl;
}
public void setBatchSize(int batchSize) {
this.batchSize = String.valueOf(batchSize);
}
public int getBatchSize() {
if (batchSize == null) {
return 0;
}
return Integer.parseInt(batchSize);
}
public String getBufferDir() {
if (bufferDir == null) {
return System.getProperty("java.io.tmpdir");
}
return bufferDir;
}
public void setBufferDir(String bufferDir) {
this.bufferDir = bufferDir;
}
public int getBufferMaxMemory() {
if (bufferMaxMemory == null) {
return 0;
}
return Integer.parseInt(bufferMaxMemory);
}
public void setBufferMaxMemory(int bufferMaxMemory) {
this.bufferMaxMemory = String.valueOf(bufferMaxMemory);
}
public int getBufferMinPackets() {
if (bufferMinPackets == null) {
return 0;
}
return Integer.parseInt(bufferMinPackets);
}
public void setBufferMinPackets(int bufferMinPackets) {
this.bufferMinPackets = String.valueOf(bufferMinPackets);
}
public boolean getCacheMetaData() {
return Boolean.valueOf(cacheMetaData).booleanValue();
}
public void setCacheMetaData(boolean cacheMetaData) {
this.cacheMetaData = String.valueOf(cacheMetaData);
}
public boolean getUseCursors() {
return Boolean.valueOf(useCursors).booleanValue();
}
public void setUseCursors(boolean useCursors) {
this.useCursors = String.valueOf(useCursors);
}
public boolean getUseLOBs() {
return Boolean.valueOf(useLOBs).booleanValue();
}
public void setUseLOBs(boolean useLOBs) {
this.useLOBs = String.valueOf(useLOBs);
}
public String getBindAddress() {
return bindAddress;
}
public void setBindAddress(String bindAddress) {
this.bindAddress = bindAddress;
}
public boolean getUseJCIFS() {
return Boolean.valueOf(useJCIFS).booleanValue();
}
public void setUseJCIFS(boolean useJCIFS) {
this.useJCIFS = String.valueOf(useJCIFS);
}
private void addNonNullProperties(Properties props, String user, String password) {
props.setProperty(Messages.get(Driver.SERVERNAME), serverName);
if (serverType != null) {
props.setProperty(Messages.get(Driver.SERVERTYPE), serverType);
}
if (portNumber != null) {
props.setProperty(Messages.get(Driver.PORTNUMBER), portNumber);
}
if (databaseName != null) {
props.setProperty(Messages.get(Driver.DATABASENAME), databaseName);
}
if (tdsVersion != null) {
props.setProperty(Messages.get(Driver.TDS), tdsVersion);
}
if (charset != null) {
props.setProperty(Messages.get(Driver.CHARSET), charset);
}
if (language != null) {
props.setProperty(Messages.get(Driver.LANGUAGE), language);
}
if (domain != null) {
props.setProperty(Messages.get(Driver.DOMAIN), domain);
}
if(useNTLMV2 != null) {
props.setProperty(Messages.get(Driver.USENTLMV2), useNTLMV2);
}
if (instance != null) {
props.setProperty(Messages.get(Driver.INSTANCE), instance);
}
if (lastUpdateCount != null) {
props.setProperty(Messages.get(Driver.LASTUPDATECOUNT), lastUpdateCount);
}
if (sendStringParametersAsUnicode != null) {
props.setProperty(Messages.get(Driver.SENDSTRINGPARAMETERSASUNICODE), sendStringParametersAsUnicode);
}
if (namedPipe != null) {
props.setProperty(Messages.get(Driver.NAMEDPIPE), namedPipe);
}
if (macAddress != null) {
props.setProperty(Messages.get(Driver.MACADDRESS), macAddress);
}
if (prepareSql != null) {
props.setProperty(Messages.get(Driver.PREPARESQL), prepareSql);
}
if (packetSize != null) {
props.setProperty(Messages.get(Driver.PACKETSIZE), packetSize);
}
if (tcpNoDelay != null) {
props.setProperty(Messages.get(Driver.TCPNODELAY), tcpNoDelay);
}
if (xaEmulation != null) {
props.setProperty(Messages.get(Driver.XAEMULATION), xaEmulation);
}
if (user != null) {
props.setProperty(Messages.get(Driver.USER), user);
}
if (password != null) {
props.setProperty(Messages.get(Driver.PASSWORD), password);
}
if (loginTimeout != null) {
props.setProperty(Messages.get(Driver.LOGINTIMEOUT), loginTimeout);
}
if (socketTimeout != null) {
props.setProperty(Messages.get(Driver.SOTIMEOUT), socketTimeout);
}
if (socketKeepAlive != null) {
props.setProperty(Messages.get(Driver.SOKEEPALIVE), socketKeepAlive);
}
if (processId != null) {
props.setProperty(Messages.get(Driver.PROCESSID), processId);
}
if (lobBuffer != null) {
props.setProperty(Messages.get(Driver.LOBBUFFER), lobBuffer);
}
if (maxStatements != null) {
props.setProperty(Messages.get(Driver.MAXSTATEMENTS), maxStatements);
}
if (appName != null) {
props.setProperty(Messages.get(Driver.APPNAME), appName);
}
if (progName != null) {
props.setProperty(Messages.get(Driver.PROGNAME), progName);
}
if (wsid != null) {
props.setProperty(Messages.get(Driver.WSID), wsid);
}
if (ssl != null) {
props.setProperty(Messages.get(Driver.SSL), ssl);
}
if (batchSize != null) {
props.setProperty(Messages.get(Driver.BATCHSIZE), batchSize);
}
if (bufferDir != null) {
props.setProperty(Messages.get(Driver.BUFFERDIR), bufferDir);
}
if (bufferMaxMemory != null) {
props.setProperty(Messages.get(Driver.BUFFERMAXMEMORY), bufferMaxMemory);
}
if (bufferMinPackets != null) {
props.setProperty(Messages.get(Driver.BUFFERMINPACKETS), bufferMinPackets);
}
if (cacheMetaData != null) {
props.setProperty(Messages.get(Driver.CACHEMETA), cacheMetaData);
}
if (useCursors != null) {
props.setProperty(Messages.get(Driver.USECURSORS), useCursors);
}
if (useLOBs != null) {
props.setProperty(Messages.get(Driver.USELOBS), useLOBs);
}
if (bindAddress != null) {
props.setProperty(Messages.get(Driver.BINDADDRESS), bindAddress);
}
if (useJCIFS != null) {
props.setProperty(Messages.get(Driver.USEJCIFS), useJCIFS);
}
}
/////// JDBC4 demarcation, do NOT put any JDBC3 code below this line ///////
/* (non-Javadoc)
* @see java.sql.Wrapper#isWrapperFor(java.lang.Class)
*/
public boolean isWrapperFor(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
/* (non-Javadoc)
* @see java.sql.Wrapper#unwrap(java.lang.Class)
*/
public Object unwrap(Class arg0) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
} libjtds-java-1.2.5.orig/src/main/net/sourceforge/jtds/jdbcx/JtdsXAResource.java 0000644 0001750 0001750 00000010312 11316672660 026775 0 ustar martin martin //jTDS JDBC Driver for Microsoft SQL Server and Sybase
//Copyright (C) 2004 The jTDS Project
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.jdbcx;
import java.sql.Connection;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import net.sourceforge.jtds.jdbc.ConnectionJDBC2;
import net.sourceforge.jtds.jdbc.XASupport;
import net.sourceforge.jtds.util.Logger;
/**
* jTDS implementation of the XAResource interface.
*
* @version $Id: JtdsXAResource.java,v 1.4 2005/04/28 14:29:30 alin_sinpalean Exp $
*/
public class JtdsXAResource implements XAResource {
private final Connection connection;
private final JtdsXAConnection xaConnection;
private final String rmHost;
public JtdsXAResource(JtdsXAConnection xaConnection, Connection connection) {
this.xaConnection = xaConnection;
this.connection = connection;
rmHost = ((ConnectionJDBC2) connection).getRmHost();
Logger.println("JtdsXAResource created");
}
protected JtdsXAConnection getResourceManager() {
return xaConnection;
}
protected String getRmHost() {
return this.rmHost;
}
//
// ------------------- javax.transaction.xa.XAResource interface methods -------------------
//
public int getTransactionTimeout() throws XAException {
Logger.println("XAResource.getTransactionTimeout()");
return 0;
}
public boolean setTransactionTimeout(int arg0) throws XAException {
Logger.println("XAResource.setTransactionTimeout("+arg0+')');
return false;
}
public boolean isSameRM(XAResource xares) throws XAException {
Logger.println("XAResource.isSameRM("+xares.toString()+')');
if (xares instanceof JtdsXAResource) {
if (((JtdsXAResource)xares).getRmHost().equals(this.rmHost)) {
return true;
}
}
return false;
}
public Xid[] recover(int flags) throws XAException {
Logger.println("XAResource.recover("+flags+')');
return XASupport.xa_recover(connection, xaConnection.getXAConnectionID(), flags);
}
public int prepare(Xid xid) throws XAException {
Logger.println("XAResource.prepare("+xid.toString()+')');
return XASupport.xa_prepare(connection, xaConnection.getXAConnectionID(), xid);
}
public void forget(Xid xid) throws XAException {
Logger.println("XAResource.forget(" + xid + ')');
XASupport.xa_forget(connection, xaConnection.getXAConnectionID(), xid);
}
public void rollback(Xid xid) throws XAException {
Logger.println("XAResource.rollback(" +xid.toString()+')');
XASupport.xa_rollback(connection, xaConnection.getXAConnectionID(), xid);
}
public void end(Xid xid, int flags) throws XAException {
Logger.println("XAResource.end(" +xid.toString()+')');
XASupport.xa_end(connection, xaConnection.getXAConnectionID(), xid, flags);
}
public void start(Xid xid, int flags) throws XAException {
Logger.println("XAResource.start(" +xid.toString()+','+flags+')');
XASupport.xa_start(connection, xaConnection.getXAConnectionID(), xid, flags);
}
public void commit(Xid xid, boolean commit) throws XAException {
Logger.println("XAResource.commit(" +xid.toString()+','+commit+')');
XASupport.xa_commit(connection, xaConnection.getXAConnectionID(), xid, commit);
}
}
libjtds-java-1.2.5.orig/src/test/ 0000755 0001750 0001750 00000000000 11316672660 016154 5 ustar martin martin libjtds-java-1.2.5.orig/src/test/net/ 0000755 0001750 0001750 00000000000 11316672660 016742 5 ustar martin martin libjtds-java-1.2.5.orig/src/test/net/sourceforge/ 0000755 0001750 0001750 00000000000 11316672660 021265 5 ustar martin martin libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/ 0000755 0001750 0001750 00000000000 11316672660 022231 5 ustar martin martin libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/ 0000755 0001750 0001750 00000000000 11316672660 023210 5 ustar martin martin libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/SupportUnitTest.java 0000644 0001750 0001750 00000005036 11316672660 027233 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2005 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import net.sourceforge.jtds.jdbc.Support;
/**
* Unit tests for the {@link net.sourceforge.jtds.jdbc.Support} class.
*
* @author David D. Kilzer
* @version $Id: SupportUnitTest.java,v 1.1 2005/09/06 23:03:21 ddkilzer Exp $
*/
public class SupportUnitTest extends UnitTestBase {
private static final String SYSTEM_PROPRETY_OS_NAME = "os.name";
private String osName;
/**
* Constructor.
*
* @param name The name of the test.
*/
public SupportUnitTest(String name) {
super(name);
}
protected void setUp() throws Exception {
super.setUp();
this.osName = System.getProperty(SYSTEM_PROPRETY_OS_NAME);
}
protected void tearDown() throws Exception {
System.setProperty(SYSTEM_PROPRETY_OS_NAME, this.osName);
super.tearDown();
}
public void testIsWindowsOS_Linux() {
System.setProperty(SYSTEM_PROPRETY_OS_NAME, "Linux");
assertFalse(Support.isWindowsOS());
}
public void testIsWindowsOS_MacOSX() {
System.setProperty(SYSTEM_PROPRETY_OS_NAME, "MacOSX");
assertFalse(Support.isWindowsOS());
}
public void testIsWindowsOS_windows() {
System.setProperty(SYSTEM_PROPRETY_OS_NAME, "windows");
assertTrue(Support.isWindowsOS());
}
public void testIsWindowsOS_Windows() {
System.setProperty(SYSTEM_PROPRETY_OS_NAME, "Windows");
assertTrue(Support.isWindowsOS());
}
public void testIsWindowsOS_Windows_XP() {
System.setProperty(SYSTEM_PROPRETY_OS_NAME, "Windows XP");
assertTrue(Support.isWindowsOS());
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/TestBase.java 0000644 0001750 0001750 00000021233 11316672660 025566 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.io.*;
import java.sql.*;
import java.util.*;
import junit.framework.TestCase;
/**
* @author builder
* @version $Id: TestBase.java,v 1.21.2.1 2009/08/04 10:33:54 ickzon Exp $
*/
public abstract class TestBase extends TestCase {
private static final String CONNECTION_PROPERTIES = "conf/connection.properties";
public static final Properties props = loadProperties(CONNECTION_PROPERTIES);
Connection con;
public TestBase(String name) {
super(name);
}
public void setUp() throws Exception {
super.setUp();
connect();
}
public void tearDown() throws Exception {
disconnect();
super.tearDown();
}
public Connection getConnection() throws Exception {
Class.forName(props.getProperty("driver"));
String url = props.getProperty("url");
return DriverManager.getConnection(url, props);
}
public Connection getConnection(Properties override) throws Exception {
Properties newProps = new Properties(props);
for (Iterator it = override.keySet().iterator(); it.hasNext();) {
String key = (String) it.next();
newProps.setProperty(key, override.getProperty(key));
}
Class.forName(newProps.getProperty("driver"));
String url = newProps.getProperty("url");
return DriverManager.getConnection(url, newProps);
}
private void disconnect() throws Exception {
if (con != null) {
con.close();
con = null;
}
}
protected void connect() throws Exception {
disconnect();
con = getConnection();
}
public void dump(ResultSet rs) throws SQLException {
ResultSetMetaData rsm = rs.getMetaData();
int cols = rsm.getColumnCount();
for (int i = 1; i <= cols; i++) {
if (i > 1) {
System.out.print(", ");
}
System.out.print(rsm.getColumnName(i));
}
System.out.println();
while (rs.next()) {
dumpRow(rs);
}
}
public void dumpRow(ResultSet rs) throws SQLException {
ResultSetMetaData rsm = rs.getMetaData();
int cols = rsm.getColumnCount();
for (int i = 1; i <= cols; i++) {
if (i > 1) {
System.out.print(", ");
}
System.out.print(rs.getObject(i));
}
System.out.println();
}
private static Properties loadProperties(String fileName) {
File propFile = new File(fileName);
if (!propFile.exists()) {
fail("Connection properties not found (" + propFile + ").");
}
try {
Properties props = new Properties();
props.load(new FileInputStream(propFile));
return props;
}
catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
protected void makeTestTables(Statement stmt) throws SQLException {
String sql = "CREATE TABLE #test ("
+ " f_int INT,"
+ " f_varchar VARCHAR(255))";
stmt.execute(sql);
}
public void makeObjects(Statement stmt, int count) throws SQLException {
stmt.execute("TRUNCATE TABLE #test");
for (int i = 0; i < count; i++) {
String sql = "INSERT INTO #test(f_int, f_varchar)"
+ " VALUES (" + i + ", 'Row " + i + "')";
stmt.execute(sql);
}
}
public void compareInputStreams(InputStream is1, InputStream is2) throws IOException {
try {
if (is1 == null && is2 == null) {
return;
} else if (is1 == null) {
fail("is1 == null && is2 != null");
return;
} else if (is2 == null) {
fail("is1 != null && is2 == null");
return;
}
long count = 0;
int res1 = 0, res2 = 0;
byte buf1[] = new byte[1024], buf2[] = new byte[1024];
while (res1 != 0 || (res1 = is1.read(buf1)) != -1) {
if (res2 == 0) {
res2 = is2.read(buf2);
}
if (res2 == -1) {
fail("stream 2 EOF at: " + count);
}
int min = Math.min(res1, res2);
for (int i = 0; i < min; i++) {
// Do the check first rather than using assertTrue()
// assertTrue() would create a String at each iteration
if (buf1[i] != buf2[i]) {
fail("stream 1 value [" + buf1[i]
+ "] differs from stream 2 value ["
+ buf2[i] + "] at: " + (count + i));
}
}
count += min;
if (res1 != min) {
System.arraycopy(buf1, min, buf1, 0, res1 - min);
res1 -= min;
} else {
res1 = 0;
}
if (res2 != min) {
System.arraycopy(buf2, min, buf2, 0, res2 - min);
res2 -= min;
} else {
res2 = 0;
}
}
if (is2.read() != -1) {
fail("stream 1 EOF at: " + count);
}
} finally {
if (is1 != null) {
is1.close();
}
if (is2 != null) {
is2.close();
}
}
}
public void compareReaders(Reader r1, Reader r2) throws IOException {
try {
if (r1 == null && r2 == null) {
return;
} else if (r1 == null) {
fail("r1 == null && r2 != null");
return;
} else if (r2 == null) {
fail("r1 != null && r2 == null");
return;
}
long count = 0;
int res1 = 0, res2 = 0;
char buf1[] = new char[1024], buf2[] = new char[1024];
while (res1 != 0 || (res1 = r1.read(buf1)) != -1) {
if (res2 == 0) {
res2 = r2.read(buf2);
}
if (res2 == -1) {
fail("reader 2 EOF at: " + count);
}
int min = Math.min(res1, res2);
for (int i = 0; i < min; i++) {
// Do the check first rather than using assertTrue()
// assertTrue() would create a String at each iteration
if (buf1[i] != buf2[i]) {
fail("stream 1 value [" + buf1[i]
+ "] differs from stream 2 value ["
+ buf2[i] + "] at: " + (count + i));
}
}
count += min;
if (res1 != min) {
System.arraycopy(buf1, min, buf1, 0, res1 - min);
res1 -= min;
} else {
res1 = 0;
}
if (res2 != min) {
System.arraycopy(buf2, min, buf2, 0, res2 - min);
res2 -= min;
} else {
res2 = 0;
}
}
if (r2.read() != -1) {
fail("reader 1 EOF at: " + count);
}
} finally {
if (r1 != null) {
r1.close();
}
if (r2 != null) {
r2.close();
}
}
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/TimestampTest.java 0000644 0001750 0001750 00000267445 11316672660 026700 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.math.BigDecimal;
import java.sql.*;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.GregorianCalendar;
import net.sourceforge.jtds.jdbc.Driver;
import net.sourceforge.jtds.util.Logger;
import junit.framework.TestSuite;
/**
* test getting timestamps from the database.
*
* @author Alin Sinpalean
* @version $Id: TimestampTest.java,v 1.32.2.5 2009/08/20 19:44:04 ickzon Exp $
*/
public class TimestampTest extends DatabaseTestCase {
public TimestampTest(String name) {
super(name);
}
public static void main(String args[]) {
boolean loggerActive = args.length > 0;
Logger.setActive(loggerActive);
if (args.length > 0) {
junit.framework.TestSuite s = new TestSuite();
for (int i = 0; i < args.length; i++) {
s.addTest(new TimestampTest(args[i]));
}
junit.textui.TestRunner.run(s);
} else {
junit.textui.TestRunner.run(TimestampTest.class);
}
// new TimestampTest("test").testOutputParams();
}
public void testBigint0000() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0000 "
+ " (i decimal(28,10) not null, "
+ " s char(10) not null) ");
final int rowsToAdd = 20;
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
String sql = "insert into #t0000 values (" + i + ", 'row" + i + "')";
count += stmt.executeUpdate(sql);
}
stmt.close();
assertEquals(count, rowsToAdd);
PreparedStatement pstmt = con.prepareStatement("select i from #t0000 where i = ?");
pstmt.setLong(1, 7);
ResultSet rs = pstmt.executeQuery();
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getLong(1), 7);
assertTrue("Expected no result set", !rs.next());
pstmt.setLong(1, 8);
rs = pstmt.executeQuery();
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getLong(1), 8);
assertTrue("Expected no result set", !rs.next());
pstmt.close();
}
public void testTimestamps0001() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0001 "
+ " (t1 datetime not null, "
+ " t2 datetime null, "
+ " t3 smalldatetime not null, "
+ " t4 smalldatetime null)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement(
"insert into #t0001 values (?, '1998-03-09 15:35:06.4', "
+ " ?, '1998-03-09 15:35:00')");
Timestamp t0 = Timestamp.valueOf("1998-03-09 15:35:06.4");
Timestamp t1 = Timestamp.valueOf("1998-03-09 15:35:00");
pstmt.setTimestamp(1, t0);
pstmt.setTimestamp(2, t1);
int count = pstmt.executeUpdate();
assertTrue(count == 1);
pstmt.close();
pstmt = con.prepareStatement("select t1, t2, t3, t4 from #t0001");
ResultSet rs = pstmt.executeQuery();
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertEquals(t0, rs.getTimestamp(1));
assertEquals(t0, rs.getTimestamp(2));
assertEquals(t1, rs.getTimestamp(3));
assertEquals(t1, rs.getTimestamp(4));
pstmt.close();
}
public void testTimestamps0004() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0004 "
+ " (mytime datetime not null, "
+ " mytime2 datetime null, "
+ " mytime3 datetime null )");
stmt.close();
PreparedStatement pstmt = con.prepareStatement(
"insert into #t0004 values ('1964-02-14 10:00:00.0', ?, ?)");
Timestamp t0 = Timestamp.valueOf("1964-02-14 10:00:00.0");
pstmt.setTimestamp(1, t0);
pstmt.setTimestamp(2, t0);
assertEquals(1, pstmt.executeUpdate());
pstmt.setNull(2, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
pstmt = con.prepareStatement("select mytime, mytime2, mytime3 from #t0004");
ResultSet rs = pstmt.executeQuery();
assertNotNull(rs);
Timestamp t1, t2, t3;
assertTrue("Expected a result set", rs.next());
t1 = rs.getTimestamp(1);
t2 = rs.getTimestamp(2);
t3 = rs.getTimestamp(3);
assertEquals(t0, t1);
assertEquals(t0, t2);
assertEquals(t0, t3);
assertTrue("Expected a result set", rs.next());
t1 = rs.getTimestamp(1);
t2 = rs.getTimestamp(2);
t3 = rs.getTimestamp(3);
assertEquals(t0, t1);
assertEquals(t0, t2);
assertEquals(null, t3);
pstmt.close();
}
public void testEscape(String sql, String expected) throws Exception {
String tmp = con.nativeSQL(sql);
assertEquals(tmp, expected);
}
public void testEscapes0006() throws Exception {
testEscape("select * from tmp where d={d 1999-09-19}",
"select * from tmp where d='19990919'");
testEscape("select * from tmp where d={d '1999-09-19'}",
"select * from tmp where d='19990919'");
testEscape("select * from tmp where t={t 12:34:00}",
"select * from tmp where t='12:34:00'");
testEscape("select * from tmp where ts={ts 1998-12-15 12:34:00.1234}",
"select * from tmp where ts='19981215 12:34:00.123'");
testEscape("select * from tmp where ts={ts 1998-12-15 12:34:00}",
"select * from tmp where ts='19981215 12:34:00.000'");
testEscape("select * from tmp where ts={ts 1998-12-15 12:34:00.1}",
"select * from tmp where ts='19981215 12:34:00.100'");
testEscape("select * from tmp where ts={ts 1998-12-15 12:34:00}",
"select * from tmp where ts='19981215 12:34:00.000'");
testEscape("select * from tmp where d={d 1999-09-19}",
"select * from tmp where d='19990919'");
testEscape("select * from tmp where a like '\\%%'",
"select * from tmp where a like '\\%%'");
testEscape("select * from tmp where a like 'b%%' {escape 'b'}",
"select * from tmp where a like 'b%%' escape 'b'");
testEscape("select * from tmp where a like 'bbb' {escape 'b'}",
"select * from tmp where a like 'bbb' escape 'b'");
testEscape("select * from tmp where a='{fn user}'",
"select * from tmp where a='{fn user}'");
testEscape("select * from tmp where a={fn user()}",
"select * from tmp where a=user_name()");
}
public void testPreparedStatement0007() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0007 "
+ " (i integer not null, "
+ " s char(10) not null) ");
final int rowsToAdd = 20;
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
String sql = "insert into #t0007 values (" + i + ", 'row" + i + "')";
count += stmt.executeUpdate(sql);
}
stmt.close();
assertEquals(count, rowsToAdd);
PreparedStatement pstmt = con.prepareStatement("select s from #t0007 where i = ?");
pstmt.setInt(1, 7);
ResultSet rs = pstmt.executeQuery();
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getString(1).trim(), "row7");
// assertTrue("Expected no result set", !rs.next());
pstmt.setInt(1, 8);
rs = pstmt.executeQuery();
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getString(1).trim(), "row8");
assertTrue("Expected no result set", !rs.next());
pstmt.close();
}
public void testPreparedStatement0008() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0008 "
+ " (i integer not null, "
+ " s char(10) not null) ");
PreparedStatement pstmt = con.prepareStatement(
"insert into #t0008 values (?, ?)");
final int rowsToAdd = 8;
final String theString = "abcdefghijklmnopqrstuvwxyz";
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pstmt.setInt(1, i);
pstmt.setString(2, theString.substring(0, i));
count += pstmt.executeUpdate();
}
assertEquals(count, rowsToAdd);
pstmt.close();
ResultSet rs = stmt.executeQuery("select s, i from #t0008");
assertNotNull(rs);
count = 0;
while (rs.next()) {
count++;
assertEquals(rs.getString(1).trim().length(), rs.getInt(2));
}
assertTrue(count == rowsToAdd);
stmt.close();
pstmt.close();
}
public void testPreparedStatement0009() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0009 "
+ " (i integer not null, "
+ " s char(10) not null) ");
con.setAutoCommit(false);
PreparedStatement pstmt = con.prepareStatement(
"insert into #t0009 values (?, ?)");
int rowsToAdd = 8;
final String theString = "abcdefghijklmnopqrstuvwxyz";
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pstmt.setInt(1, i);
pstmt.setString(2, theString.substring(0, i));
count += pstmt.executeUpdate();
}
pstmt.close();
assertEquals(count, rowsToAdd);
con.rollback();
ResultSet rs = stmt.executeQuery("select s, i from #t0009");
assertNotNull(rs);
count = 0;
while (rs.next()) {
count++;
assertEquals(rs.getString(1).trim().length(), rs.getInt(2));
}
assertEquals(count, 0);
con.commit();
pstmt = con.prepareStatement("insert into #t0009 values (?, ?)");
rowsToAdd = 6;
count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pstmt.setInt(1, i);
pstmt.setString(2, theString.substring(0, i));
count += pstmt.executeUpdate();
}
assertEquals(count, rowsToAdd);
con.commit();
pstmt.close();
rs = stmt.executeQuery("select s, i from #t0009");
count = 0;
while (rs.next()) {
count++;
assertEquals(rs.getString(1).trim().length(), rs.getInt(2));
}
assertEquals(count, rowsToAdd);
con.commit();
stmt.close();
con.setAutoCommit(true);
}
public void testTransactions0010() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0010 "
+ " (i integer not null, "
+ " s char(10) not null) ");
con.setAutoCommit(false);
PreparedStatement pstmt = con.prepareStatement(
"insert into #t0010 values (?, ?)");
int rowsToAdd = 8;
final String theString = "abcdefghijklmnopqrstuvwxyz";
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pstmt.setInt(1, i);
pstmt.setString(2, theString.substring(0, i));
count += pstmt.executeUpdate();
}
assertEquals(count, rowsToAdd);
con.rollback();
ResultSet rs = stmt.executeQuery("select s, i from #t0010");
assertNotNull(rs);
count = 0;
while (rs.next()) {
count++;
assertEquals(rs.getString(1).trim().length(), rs.getInt(2));
}
assertEquals(count, 0);
rowsToAdd = 6;
for (int j = 1; j <= 2; j++) {
count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pstmt.setInt(1, i + ((j - 1) * rowsToAdd));
pstmt.setString(2, theString.substring(0, i));
count += pstmt.executeUpdate();
}
assertEquals(count, rowsToAdd);
con.commit();
}
rs = stmt.executeQuery("select s, i from #t0010");
count = 0;
while (rs.next()) {
count++;
int i = rs.getInt(2);
if (i > rowsToAdd) {
i -= rowsToAdd;
}
assertEquals(rs.getString(1).trim().length(), i);
}
assertEquals(count, (2 * rowsToAdd));
stmt.close();
pstmt.close();
con.setAutoCommit(true);
}
public void testEmptyResults0011() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0011 "
+ " (mytime datetime not null, "
+ " mytime2 datetime null )");
ResultSet rs = stmt.executeQuery("select mytime, mytime2 from #t0011");
assertNotNull(rs);
assertTrue("Expected no result set", !rs.next());
rs = stmt.executeQuery("select mytime, mytime2 from #t0011");
assertTrue("Expected no result set", !rs.next());
stmt.close();
}
public void testEmptyResults0012() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0012 "
+ " (mytime datetime not null, "
+ " mytime2 datetime null )");
stmt.close();
PreparedStatement pstmt = con.prepareStatement(
"select mytime, mytime2 from #t0012");
ResultSet rs = pstmt.executeQuery();
assertNotNull(rs);
assertTrue("Expected no result", !rs.next());
rs.close();
rs = pstmt.executeQuery();
assertTrue("Expected no result", !rs.next());
pstmt.close();
}
public void testEmptyResults0013() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0013 "
+ " (mytime datetime not null, "
+ " mytime2 datetime null )");
ResultSet rs1 = stmt.executeQuery("select mytime, mytime2 from #t0013");
assertNotNull(rs1);
assertTrue("Expected no result set", !rs1.next());
stmt.close();
PreparedStatement pstmt = con.prepareStatement(
"select mytime, mytime2 from #t0013");
ResultSet rs2 = pstmt.executeQuery();
assertNotNull(rs2);
assertTrue("Expected no result", !rs2.next());
pstmt.close();
}
public void testForBrowse0014() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0014 (i integer not null)");
PreparedStatement pstmt = con.prepareStatement(
"insert into #t0014 values (?)");
final int rowsToAdd = 100;
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pstmt.setInt(1, i);
count += pstmt.executeUpdate();
}
assertEquals(count, rowsToAdd);
pstmt.close();
pstmt = con.prepareStatement("select i from #t0014 for browse");
ResultSet rs = pstmt.executeQuery();
assertNotNull(rs);
count = 0;
while (rs.next()) {
rs.getInt("i");
count++;
}
assertEquals(count, rowsToAdd);
pstmt.close();
rs = stmt.executeQuery("select * from #t0014");
assertNotNull(rs);
count = 0;
while (rs.next()) {
rs.getInt("i");
count++;
}
assertEquals(count, rowsToAdd);
rs = stmt.executeQuery("select * from #t0014");
assertNotNull(rs);
count = 0;
while (rs.next() && count < 5) {
rs.getInt("i");
count++;
}
assertTrue(count == 5);
rs = stmt.executeQuery("select * from #t0014");
assertNotNull(rs);
count = 0;
while (rs.next()) {
rs.getInt("i");
count++;
}
assertEquals(count, rowsToAdd);
stmt.close();
}
public void testMultipleResults0015() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0015 "
+ " (i integer not null, "
+ " s char(10) not null) ");
PreparedStatement pstmt = con.prepareStatement(
"insert into #t0015 values (?, ?)");
int rowsToAdd = 8;
final String theString = "abcdefghijklmnopqrstuvwxyz";
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pstmt.setInt(1, i);
pstmt.setString(2, theString.substring(0, i));
count += pstmt.executeUpdate();
}
assertEquals(count, rowsToAdd);
pstmt.close();
stmt.execute("select s from #t0015 select i from #t0015");
ResultSet rs = stmt.getResultSet();
assertNotNull(rs);
count = 0;
while (rs.next()) {
count++;
}
assertEquals(count, rowsToAdd);
assertTrue(stmt.getMoreResults());
rs = stmt.getResultSet();
assertNotNull(rs);
count = 0;
while (rs.next()) {
count++;
}
assertEquals(count, rowsToAdd);
rs = stmt.executeQuery("select i, s from #t0015");
count = 0;
while (rs.next()) {
count++;
}
assertEquals(count, rowsToAdd);
stmt.close();
}
public void testMissingParameter0016() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0016 "
+ " (i integer not null, "
+ " s char(10) not null) ");
final int rowsToAdd = 20;
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
String sql = "insert into #t0016 values (" + i + ", 'row" + i + "')";
count += stmt.executeUpdate(sql);
}
stmt.close();
assertEquals(count, rowsToAdd);
PreparedStatement pstmt = con.prepareStatement(
"select s from #t0016 where i=? and s=?");
// see what happens if neither is set
try {
pstmt.executeQuery();
assertTrue("Failed to throw exception", false);
} catch (SQLException e) {
assertTrue("07000".equals(e.getSQLState())
&& (e.getMessage().indexOf('1') >= 0
|| e.getMessage().indexOf('2') >= 0));
}
pstmt.clearParameters();
try {
pstmt.setInt(1, 7);
pstmt.setString(2, "row7");
pstmt.clearParameters();
pstmt.executeQuery();
assertTrue("Failed to throw exception", false);
} catch (SQLException e) {
assertTrue("07000".equals(e.getSQLState())
&& (e.getMessage().indexOf('1') >= 0
|| e.getMessage().indexOf('2') >= 0));
}
pstmt.clearParameters();
try {
pstmt.setInt(1, 7);
pstmt.executeQuery();
assertTrue("Failed to throw exception", false);
} catch (SQLException e) {
assertTrue("07000".equals(e.getSQLState())
&& e.getMessage().indexOf('2') >= 0);
}
pstmt.clearParameters();
try {
pstmt.setString(2, "row7");
pstmt.executeQuery();
assertTrue("Failed to throw exception", false);
} catch (SQLException e) {
assertTrue("07000".equals(e.getSQLState())
&& e.getMessage().indexOf('1') >= 0);
}
pstmt.close();
}
Object[][] getDatatypes() {
return new Object[][] {
/* { "binary(272)",
"0x101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f",
new byte[] {
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
} },
*/
{"float(6)", "65.4321", new BigDecimal("65.4321")},
{"binary(5)", "0x1213141516", new byte[] { 0x12, 0x13, 0x14, 0x15, 0x16}},
{"varbinary(4)", "0x1718191A", new byte[] { 0x17, 0x18, 0x19, 0x1A}},
{"varchar(8)", "'12345678'", "12345678"},
{"datetime", "'19990815 21:29:59.01'", Timestamp.valueOf("1999-08-15 21:29:59.01")},
{"smalldatetime", "'19990215 20:45'", Timestamp.valueOf("1999-02-15 20:45:00")},
{"float(6)", "65.4321", new Float(65.4321)/* new BigDecimal("65.4321") */},
{"float(14)", "1.123456789", new Double(1.123456789) /*new BigDecimal("1.123456789") */},
{"real", "7654321.0", new Double(7654321.0)},
{"int", "4097", new Integer(4097)},
{"float(6)", "65.4321", new BigDecimal("65.4321")},
{"float(14)", "1.123456789", new BigDecimal("1.123456789")},
{"decimal(10,3)", "1234567.089", new BigDecimal("1234567.089")},
{"numeric(5,4)", "1.2345", new BigDecimal("1.2345")},
{"smallint", "4094", new Short((short) 4094)},
// {"tinyint", "127", new Byte((byte) 127)},
// {"tinyint", "-128", new Byte((byte) -128)},
{"tinyint", "127", new Byte((byte) 127)},
{"tinyint", "128", new Short((short) 128)},
{"money", "19.95", new BigDecimal("19.95")},
{"smallmoney", "9.97", new BigDecimal("9.97")},
{"bit", "1", Boolean.TRUE},
// { "text", "'abcedefg'", "abcdefg" },
/* { "char(1000)",
"'123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890'",
"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" },
*/
// { "char(1000)", "'1234567890'", "1234567890" },
// { "image", "0x0a0a0b", new byte[] { 0x0a, 0x0a, 0x0b } },
};
}
public void testOutputParams() throws Exception {
Statement stmt = con.createStatement();
dropProcedure("#jtds_outputTest");
Object[][] datatypes = getDatatypes();
for (int i = 0; i < datatypes.length; i++) {
String valueToAssign;
boolean bImage = datatypes[i][0].equals("image");
if (bImage) {
valueToAssign = "";
} else {
valueToAssign = " = " + datatypes[i][1];
}
String sql = "create procedure #jtds_outputTest "
+ "@a1 " + datatypes[i][0] + " = null out "
+ "as select @a1" + valueToAssign;
stmt.executeUpdate(sql);
for (int pass = 0; (pass < 2 && !bImage) || pass < 1; pass++) {
CallableStatement cstmt = con.prepareCall("{call #jtds_outputTest(?)}");
int jtype = getType(datatypes[i][2]);
if (pass == 1)
cstmt.setObject(1, null, jtype, 10);
if (jtype == java.sql.Types.NUMERIC || jtype == java.sql.Types.DECIMAL) {
cstmt.registerOutParameter(1, jtype, 10);
if (pass == 0) {
cstmt.setObject(1, datatypes[i][2], jtype, 10);
}
} else if (jtype == java.sql.Types.VARCHAR) {
cstmt.registerOutParameter(1, jtype);
if (pass == 0) {
cstmt.setObject(1, datatypes[i][2]);
}
} else {
cstmt.registerOutParameter(1, jtype);
if (pass == 0) {
cstmt.setObject(1, datatypes[i][2]);
}
}
assertEquals(bImage, cstmt.execute());
while (cstmt.getMoreResults() || cstmt.getUpdateCount() != -1) ;
if (jtype == java.sql.Types.VARBINARY) {
assertTrue(compareBytes(cstmt.getBytes(1), (byte[]) datatypes[i][2]) == 0);
} else if (datatypes[i][2] instanceof Number) {
Number n = (Number) cstmt.getObject(1);
if (n != null) {
assertEquals("Failed on " + datatypes[i][0], n.doubleValue(),
((Number) datatypes[i][2]).doubleValue(), 0.001);
} else {
assertEquals("Failed on " + datatypes[i][0], n, datatypes[i][2]);
}
} else {
assertEquals("Failed on " + datatypes[i][0], cstmt.getObject(1), datatypes[i][2]);
}
cstmt.close();
} // for (pass
stmt.executeUpdate(" drop procedure #jtds_outputTest");
} // for (int
stmt.close();
}
public void testStatements0020() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0020a ( " +
" i1 int not null, " +
" s1 char(10) not null " +
") " +
"");
stmt.executeUpdate("create table #t0020b ( " +
" i2a int not null, " +
" i2b int not null, " +
" s2 char(10) not null " +
") " +
"");
stmt.executeUpdate("create table #t0020c ( " +
" i3 int not null, " +
" s3 char(10) not null " +
") " +
"");
int nextB = 1;
int nextC = 1;
for (int i = 1; i < 50; i++) {
stmt.executeUpdate("insert into #t0020a " +
" values(" + i + ", " +
" 'row" + i + "') " +
"");
for (int j = nextB; (nextB % 5) != 0; j++, nextB++) {
stmt.executeUpdate("insert into #t0020b " +
" values(" + i + ", " +
" " + j + ", " +
" 'row" + i + "." + j + "' " +
" )" +
"");
for (int k = nextC; (nextC % 3) != 0; k++, nextC++) {
stmt.executeUpdate("insert into #t0020c " +
" values(" + j + ", " +
" 'row" + i + "." + j + "." + k + "' " +
" )" +
"");
}
}
}
Statement stmtA = con.createStatement();
PreparedStatement stmtB = con.prepareStatement(
"select i2b, s2 from #t0020b where i2a=?");
PreparedStatement stmtC = con.prepareStatement(
"select s3 from #t0020c where i3=?");
ResultSet rs1 = stmtA.executeQuery("select i1 from #t0020a");
assertNotNull(rs1);
while (rs1.next()) {
stmtB.setInt(1, rs1.getInt("i1"));
ResultSet rs2 = stmtB.executeQuery();
assertNotNull(rs2);
while (rs2.next()) {
stmtC.setInt(1, rs2.getInt(1));
ResultSet rs3 = stmtC.executeQuery();
assertNotNull(rs3);
rs3.next();
}
}
stmt.close();
stmtA.close();
stmtB.close();
stmtC.close();
}
public void testBlob0021() throws Exception {
byte smallarray[] = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10
};
byte array1[] = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
};
String bigtext1 =
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"";
Statement stmt = con.createStatement();
dropTable("#t0021");
stmt.executeUpdate(
"create table #t0021 ( " +
" mybinary binary(16) not null, " +
" myimage image not null, " +
" mynullimage image null, " +
" mytext text not null, " +
" mynulltext text null) ");
// Insert a row without nulls via a Statement
PreparedStatement insert = con.prepareStatement(
"insert into #t0021( " +
" mybinary, " +
" myimage, " +
" mynullimage, " +
" mytext, " +
" mynulltext " +
") " +
"values(?, ?, ?, ?, ?) ");
insert.setBytes(1, smallarray);
insert.setBytes(2, array1);
insert.setBytes(3, array1);
insert.setString(4, bigtext1);
insert.setString(5, bigtext1);
int count = insert.executeUpdate();
assertEquals(count, 1);
insert.close();
ResultSet rs = stmt.executeQuery("select * from #t0021");
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
byte[] a1 = rs.getBytes("myimage");
byte[] a2 = rs.getBytes("mynullimage");
String s1 = rs.getString("mytext");
String s2 = rs.getString("mynulltext");
assertEquals(0, compareBytes(a1, array1));
assertEquals(0, compareBytes(a2, array1));
assertEquals(bigtext1, s1);
assertEquals(bigtext1, s2);
stmt.close();
}
public void testNestedStatements0022() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0022a "
+ " (i integer not null, "
+ " str char(254) not null) ");
stmt.executeUpdate("create table #t0022b "
+ " (i integer not null, "
+ " t datetime not null) ");
PreparedStatement pStmtA = con.prepareStatement(
"insert into #t0022a values (?, ?)");
PreparedStatement pStmtB = con.prepareStatement(
"insert into #t0022b values (?, getdate())");
final int rowsToAdd = 100;
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pStmtA.setInt(1, i);
StringBuffer tmp = new StringBuffer(255);
while (tmp.length() < 240) {
tmp.append("row ").append(i).append(". ");
}
pStmtA.setString(2, tmp.toString());
count += pStmtA.executeUpdate();
pStmtB.setInt(1, i);
pStmtB.executeUpdate();
}
pStmtA.close();
pStmtB.close();
assertEquals(count, rowsToAdd);
Statement stmtA = con.createStatement();
Statement stmtB = con.createStatement();
count = 0;
ResultSet rsA = stmtA.executeQuery("select * from #t0022a");
assertNotNull(rsA);
while (rsA.next()) {
count++;
ResultSet rsB = stmtB.executeQuery(
"select * from #t0022b where i=" + rsA.getInt("i"));
assertNotNull(rsB);
assertTrue("Expected a result set", rsB.next());
assertTrue("Expected no result set", !rsB.next());
}
assertEquals(count, rowsToAdd);
stmt.close();
stmtA.close();
stmtB.close();
}
public void testPrimaryKeyFloat0023() throws Exception {
Double d[] = {
new Double(-1.0),
new Double(1234.543),
new Double(0.0),
new Double(1),
new Double(-2.0),
new Double(0.14),
new Double(0.79),
new Double(1000000.12345),
new Double(-1000000.12345),
new Double(1000000),
new Double(-1000000),
new Double(1.7E+308),
new Double(1.7E-307) // jikes 1.04 has a bug and can't handle 1.7E-308
};
Statement stmt = con.createStatement();
stmt.executeUpdate(""
+ "create table #t0023 "
+ " (pk float not null, "
+ " type char(30) not null, "
+ " b bit, "
+ " str char(30) not null, "
+ " t int identity(1,1), "
+ " primary key (pk, type)) ");
PreparedStatement pstmt = con.prepareStatement(
"insert into #t0023 (pk, type, b, str) values(?, 'prepared', 0, ?)");
for (int i = 0; i < d.length; i++) {
pstmt.setDouble(1, d[i].doubleValue());
pstmt.setString(2, (d[i]).toString());
int preparedCount = pstmt.executeUpdate();
assertEquals(preparedCount, 1);
int adhocCount = stmt.executeUpdate(""
+ "insert into #t0023 "
+ " (pk, type, b, str) "
+ " values("
+ " " + d[i] + ", "
+ " 'adhoc', "
+ " 1, "
+ " '" + d[i] + "') ");
assertEquals(adhocCount, 1);
}
int count = 0;
ResultSet rs = stmt.executeQuery("select * from #t0023 where type='prepared' order by t");
assertNotNull(rs);
while (rs.next()) {
assertEquals(d[count].toString(), "" + rs.getDouble("pk"));
count++;
}
assertEquals(count, d.length);
count = 0;
rs = stmt.executeQuery("select * from #t0023 where type='adhoc' order by t");
while (rs.next()) {
assertEquals(d[count].toString(), "" + rs.getDouble("pk"));
count++;
}
assertEquals(count, d.length);
stmt.close();
pstmt.close();
}
public void testPrimaryKeyReal0024() throws Exception {
Float d[] = {
new Float(-1.0),
new Float(1234.543),
new Float(0.0),
new Float(1),
new Float(-2.0),
new Float(0.14),
new Float(0.79),
new Float(1000000.12345),
new Float(-1000000.12345),
new Float(1000000),
new Float(-1000000),
new Float(3.4E+38),
new Float(3.4E-38)
};
Statement stmt = con.createStatement();
stmt.executeUpdate(""
+ "create table #t0024 "
+ " (pk real not null, "
+ " type char(30) not null, "
+ " b bit, "
+ " str char(30) not null, "
+ " t int identity(1,1), "
+ " primary key (pk, type)) ");
PreparedStatement pstmt = con.prepareStatement(
"insert into #t0024 (pk, type, b, str) values(?, 'prepared', 0, ?)");
for (int i=0; i < d.length; i++) {
pstmt.setFloat(1, d[i].floatValue());
pstmt.setString(2, (d[i]).toString());
int preparedCount = pstmt.executeUpdate();
assertTrue(preparedCount == 1);
int adhocCount = stmt.executeUpdate(""
+ "insert into #t0024 "
+ " (pk, type, b, str) "
+ " values("
+ " " + d[i] + ", "
+ " 'adhoc', "
+ " 1, "
+ " '" + d[i] + "') ");
assertEquals(adhocCount, 1);
}
int count = 0;
ResultSet rs = stmt.executeQuery("select * from #t0024 where type='prepared' order by t");
assertNotNull(rs);
while (rs.next()) {
String s1 = d[count].toString().trim();
String s2 = ("" + rs.getFloat("pk")).trim();
assertTrue(s1.equalsIgnoreCase(s2));
count++;
}
assertEquals(count, d.length);
count = 0;
rs = stmt.executeQuery("select * from #t0024 where type='adhoc' order by t");
while (rs.next()) {
String s1 = d[count].toString().trim();
String s2 = ("" + rs.getFloat("pk")).trim();
assertTrue(s1.equalsIgnoreCase(s2));
count++;
}
assertEquals(count, d.length);
stmt.close();
pstmt.close();
}
public void testGetBoolean0025() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0025 " +
" (i integer, " +
" b bit, " +
" s char(5), " +
" f float) ");
// @todo Check which CHAR/VARCHAR values should be true and which should be false.
assertTrue(stmt.executeUpdate("insert into #t0025 values(0, 0, 'false', 0.0)") == 1);
assertTrue(stmt.executeUpdate("insert into #t0025 values(0, 0, '0', 0.0)") == 1);
assertTrue(stmt.executeUpdate("insert into #t0025 values(1, 1, 'true', 7.0)") == 1);
assertTrue(stmt.executeUpdate("insert into #t0025 values(2, 1, '1', -5.0)") == 1);
ResultSet rs = stmt.executeQuery("select * from #t0025 order by i");
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertTrue(!rs.getBoolean("i"));
assertTrue(!rs.getBoolean("b"));
assertTrue(!rs.getBoolean("s"));
assertTrue(!rs.getBoolean("f"));
assertTrue("Expected a result set", rs.next());
assertTrue(!rs.getBoolean("i"));
assertTrue(!rs.getBoolean("b"));
assertTrue(!rs.getBoolean("s"));
assertTrue(!rs.getBoolean("f"));
assertTrue("Expected a result set", rs.next());
assertTrue(rs.getBoolean("i"));
assertTrue(rs.getBoolean("b"));
assertTrue(rs.getBoolean("s"));
assertTrue(rs.getBoolean("f"));
assertTrue("Expected a result set", rs.next());
assertTrue(rs.getBoolean("i"));
assertTrue(rs.getBoolean("b"));
assertTrue(rs.getBoolean("s"));
assertTrue(rs.getBoolean("f"));
assertTrue("Expected no result set", !rs.next());
stmt.close();
}
/**
* SAfe Tests whether cursor-based statements still work ok when
* nested. Similar to testNestedStatements0022, which tests
* the same with plain (non-cursor-based) statements (and unfortunately
* fails).
*
* @throws Exception if an Exception occurs (very relevant, huh?)
*/
public void testNestedStatements0026() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0026a "
+ " (i integer not null, "
+ " str char(254) not null) ");
stmt.executeUpdate("create table #t0026b "
+ " (i integer not null, "
+ " t datetime not null) ");
stmt.close();
PreparedStatement pstmtA = con.prepareStatement(
"insert into #t0026a values (?, ?)");
PreparedStatement pstmtB = con.prepareStatement(
"insert into #t0026b values (?, getdate())");
final int rowsToAdd = 100;
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pstmtA.setInt(1, i);
StringBuffer tmp = new StringBuffer(255);
while (tmp.length() < 240) {
tmp.append("row ").append(i).append(". ");
}
pstmtA.setString(2, tmp.toString());
count += pstmtA.executeUpdate();
pstmtB.setInt(1, i);
pstmtB.executeUpdate();
}
assertEquals(count, rowsToAdd);
pstmtA.close();
pstmtB.close();
Statement stmtA = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
Statement stmtB = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
count = 0;
ResultSet rsA = stmtA.executeQuery("select * from #t0026a");
assertNotNull(rsA);
while (rsA.next()) {
count++;
ResultSet rsB = stmtB.executeQuery(
"select * from #t0026b where i=" + rsA.getInt("i"));
assertNotNull(rsB);
assertTrue("Expected a result set", rsB.next());
assertTrue("Expected no result set", !rsB.next());
rsB.close();
}
assertEquals(count, rowsToAdd);
stmtA.close();
stmtB.close();
}
public void testErrors0036() throws Exception {
Statement stmt = con.createStatement();
final int numberToTest = 5;
for (int i = 0; i < numberToTest; i++) {
String table = "#t0036_no_create_" + i;
try {
stmt.executeUpdate("drop table " + table);
fail("Did not expect to reach here");
} catch (SQLException e) {
assertEquals("42S02", e.getSQLState());
}
}
stmt.close();
}
public void testTimestamps0037() throws Exception {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(
"select " +
" convert(smalldatetime, '1999-01-02') a, " +
" convert(smalldatetime, null) b, " +
" convert(datetime, '1999-01-02') c, " +
" convert(datetime, null) d ");
assertNotNull(rs);
assertTrue("Expected a result", rs.next());
assertNotNull(rs.getDate("a"));
assertNull(rs.getDate("b"));
assertNotNull(rs.getDate("c"));
assertNull(rs.getDate("d"));
assertNotNull(rs.getTime("a"));
assertNull(rs.getTime("b"));
assertNotNull(rs.getTime("c"));
assertNull(rs.getTime("d"));
assertNotNull(rs.getTimestamp("a"));
assertNull(rs.getTimestamp("b"));
assertNotNull(rs.getTimestamp("c"));
assertNull(rs.getTimestamp("d"));
assertTrue("Expected no more results", !rs.next());
stmt.close();
}
public void testConnection0038() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0038 ("
+ " keyField char(255) not null, "
+ " descField varchar(255) not null) ");
int count = stmt.executeUpdate("insert into #t0038 values ('value', 'test')");
assertEquals(count, 1);
con.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
con.setAutoCommit(false);
PreparedStatement ps = con.prepareStatement("update #t0038 set descField=descField where keyField=?");
ps.setString(1, "value");
ps.executeUpdate();
ps.close();
con.commit();
// conn.rollback();
ResultSet resultSet = stmt.executeQuery(
"select descField from #t0038 where keyField='value'");
assertTrue(resultSet.next());
stmt.close();
}
public void testConnection0039() throws Exception {
for (int i = 0; i < 10; i++) {
Connection conn = getConnection();
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery("select 5");
assertNotNull(resultSet);
resultSet.close();
statement.close();
conn.close();
}
}
public void testPreparedStatement0040() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0040 ("
+ " c255 char(255) not null, "
+ " v255 varchar(255) not null) ");
PreparedStatement pstmt = con.prepareStatement("insert into #t0040 values (?, ?)");
String along = getLongString('a');
String blong = getLongString('b');
pstmt.setString(1, along);
pstmt.setString(2, along);
int count = pstmt.executeUpdate();
assertEquals(count, 1);
pstmt.close();
count = stmt.executeUpdate(""
+ "insert into #t0040 values ( "
+ "'" + blong + "', "
+ "'" + blong + "')");
assertEquals(count, 1);
pstmt = con.prepareStatement("select c255, v255 from #t0040 order by c255");
ResultSet rs = pstmt.executeQuery();
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getString("c255"), along);
assertEquals(rs.getString("v255"), along);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getString("c255"), blong);
assertEquals(rs.getString("v255"), blong);
assertTrue("Expected no result set", !rs.next());
pstmt.close();
rs = stmt.executeQuery("select c255, v255 from #t0040 order by c255");
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getString("c255"), along);
assertEquals(rs.getString("v255"), along);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getString("c255"), blong);
assertEquals(rs.getString("v255"), blong);
assertTrue("Expected no result set", !rs.next());
stmt.close();
}
public void testPreparedStatement0041() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0041 "
+ " (i integer not null, "
+ " s text not null) ");
PreparedStatement pstmt = con.prepareStatement("insert into #t0041 values (?, ?)");
// TODO: Check values
final int rowsToAdd = 400;
final String theString = getLongString(400);
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pstmt.setInt(1, i);
pstmt.setString(2, theString.substring(0, i));
count += pstmt.executeUpdate();
}
assertEquals(rowsToAdd, count);
pstmt.close();
ResultSet rs = stmt.executeQuery("select s, i from #t0041");
assertNotNull(rs);
count = 0;
while (rs.next()) {
rs.getString("s");
count++;
}
assertEquals(rowsToAdd, count);
stmt.close();
}
public void testPreparedStatement0042() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0042 (s char(5) null, i integer null, j integer not null)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #t0042 (s, i, j) values (?, ?, ?)");
pstmt.setString(1, "hello");
pstmt.setNull(2, java.sql.Types.INTEGER);
pstmt.setInt(3, 1);
int count = pstmt.executeUpdate();
assertEquals(count, 1);
pstmt.setInt(2, 42);
pstmt.setInt(3, 2);
count = pstmt.executeUpdate();
assertEquals(count, 1);
pstmt.close();
pstmt = con.prepareStatement("select i from #t0042 order by j");
ResultSet rs = pstmt.executeQuery();
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
rs.getInt(1);
assertTrue(rs.wasNull());
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getInt(1), 42);
assertTrue(!rs.wasNull());
assertTrue("Expected no result set", !rs.next());
pstmt.close();
}
public void testResultSet0043() throws Exception {
Statement stmt = con.createStatement();
try {
ResultSet rs = stmt.executeQuery("select 1");
assertNotNull(rs);
rs.getInt(1);
fail("Did not expect to reach here");
} catch (SQLException e) {
assertEquals("24000", e.getSQLState());
}
stmt.close();
}
public void testResultSet0044() throws Exception {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select 1");
assertNotNull(rs);
rs.close();
try {
rs.next();
fail("Was expecting ResultSet.next() to throw an exception if the ResultSet was closed");
} catch (SQLException e) {
assertEquals("HY010", e.getSQLState());
}
stmt.close();
}
public void testResultSet0045() throws Exception {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select 1");
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
rs.getInt(1);
assertTrue("Expected no result set", !rs.next());
try {
rs.getInt(1);
fail("Did not expect to reach here");
} catch (java.sql.SQLException e) {
assertEquals("24000", e.getSQLState());
}
stmt.close();
}
public void testMetaData0046() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0046 ("
+ " i integer identity, "
+ " a integer not null, "
+ " b integer null ) ");
int count = stmt.executeUpdate("insert into #t0046 (a, b) values (-2, -3)");
assertEquals(count, 1);
ResultSet rs = stmt.executeQuery("select i, a, b, 17 c from #t0046");
assertNotNull(rs);
ResultSetMetaData md = rs.getMetaData();
assertNotNull(md);
assertTrue(md.isAutoIncrement(1));
assertTrue(!md.isAutoIncrement(2));
assertTrue(!md.isAutoIncrement(3));
assertTrue(!md.isAutoIncrement(4));
assertTrue(md.isReadOnly(1));
assertTrue(!md.isReadOnly(2));
assertTrue(!md.isReadOnly(3));
// assertTrue(md.isReadOnly(4)); SQL 6.5 does not report this one correctly!
assertEquals(md.isNullable(1),java.sql.ResultSetMetaData.columnNoNulls);
assertEquals(md.isNullable(2),java.sql.ResultSetMetaData.columnNoNulls);
assertEquals(md.isNullable(3),java.sql.ResultSetMetaData.columnNullable);
// assert(md.isNullable(4) == java.sql.ResultSetMetaData.columnNoNulls);
rs.close();
stmt.close();
}
public void testTimestamps0047() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate(
"create table #t0047 " +
"( " +
" t1 datetime not null, " +
" t2 datetime null, " +
" t3 smalldatetime not null, " +
" t4 smalldatetime null " +
")");
String query =
"insert into #t0047 (t1, t2, t3, t4) " +
" values('2000-01-02 19:35:01.333', " +
" '2000-01-02 19:35:01.333', " +
" '2000-01-02 19:35:01.333', " +
" '2000-01-02 19:35:01.333' " +
")";
int count = stmt.executeUpdate(query);
assertEquals(count, 1);
ResultSet rs = stmt.executeQuery("select t1, t2, t3, t4 from #t0047");
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
java.sql.Timestamp t1 = rs.getTimestamp("t1");
java.sql.Timestamp t2 = rs.getTimestamp("t2");
java.sql.Timestamp t3 = rs.getTimestamp("t3");
java.sql.Timestamp t4 = rs.getTimestamp("t4");
java.sql.Timestamp r1 = Timestamp.valueOf("2000-01-02 19:35:01.333");
java.sql.Timestamp r2 = Timestamp.valueOf("2000-01-02 19:35:00");
assertEquals(r1, t1);
assertEquals(r1, t2);
assertEquals(r2, t3);
assertEquals(r2, t4);
stmt.close();
}
public void testTimestamps0048() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate(
"create table #t0048 " +
"( " +
" t1 datetime not null, " +
" t2 datetime null, " +
" t3 smalldatetime not null, " +
" t4 smalldatetime null " +
")");
java.sql.Timestamp r1;
java.sql.Timestamp r2;
r1 = Timestamp.valueOf("2000-01-02 19:35:01");
r2 = Timestamp.valueOf("2000-01-02 19:35:00");
java.sql.PreparedStatement pstmt = con.prepareStatement(
"insert into #t0048 (t1, t2, t3, t4) values(?, ?, ?, ?)");
pstmt.setTimestamp(1, r1);
pstmt.setTimestamp(2, r1);
pstmt.setTimestamp(3, r1);
pstmt.setTimestamp(4, r1);
int count = pstmt.executeUpdate();
assertEquals(count, 1);
pstmt.close();
ResultSet rs = stmt.executeQuery("select t1, t2, t3, t4 from #t0048");
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
java.sql.Timestamp t1 = rs.getTimestamp("t1");
java.sql.Timestamp t2 = rs.getTimestamp("t2");
java.sql.Timestamp t3 = rs.getTimestamp("t3");
java.sql.Timestamp t4 = rs.getTimestamp("t4");
assertEquals(r1, t1);
assertEquals(r1, t2);
assertEquals(r2, t3);
assertEquals(r2, t4);
stmt.close();
}
public void testDecimalConversion0058() throws Exception {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select convert(DECIMAL(4,0), 0)");
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getInt(1), 0);
assertTrue("Expected no result set", !rs.next());
rs = stmt.executeQuery("select convert(DECIMAL(4,0), 1)");
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getInt(1), 1);
assertTrue("Expected no result set", !rs.next());
rs = stmt.executeQuery("select convert(DECIMAL(4,0), -1)");
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getInt(1), -1);
assertTrue("Expected no result set", !rs.next());
stmt.close();
}
/**
* Test for bug [994916] datetime decoding in TdsData.java
*/
public void testDatetimeRounding1() throws Exception {
// Per the SQL Server documentation
// Send: 01/01/98 23:59:59.990
// Receive: 01/01/98 23:59:59.990
Calendar sendValue = Calendar.getInstance();
Calendar receiveValue = Calendar.getInstance();
sendValue.set(Calendar.MONTH, Calendar.JANUARY);
sendValue.set(Calendar.DAY_OF_MONTH, 1);
sendValue.set(Calendar.YEAR, 1998);
sendValue.set(Calendar.HOUR_OF_DAY, 23);
sendValue.set(Calendar.MINUTE, 59);
sendValue.set(Calendar.SECOND, 59);
sendValue.set(Calendar.MILLISECOND, 990);
receiveValue.set(Calendar.MONTH, Calendar.JANUARY);
receiveValue.set(Calendar.DAY_OF_MONTH, 1);
receiveValue.set(Calendar.YEAR, 1998);
receiveValue.set(Calendar.HOUR_OF_DAY, 23);
receiveValue.set(Calendar.MINUTE, 59);
receiveValue.set(Calendar.SECOND, 59);
receiveValue.set(Calendar.MILLISECOND, 990);
Statement stmt = con.createStatement();
stmt.execute("create table #dtr1 (data datetime)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #dtr1 (data) values (?)");
pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime()));
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #dtr1");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(receiveValue.getTime().getTime(), getTimeInMs(rs));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for bug [994916] datetime decoding in TdsData.java
*/
public void testDatetimeRounding2() throws Exception {
// Per the SQL Server documentation
// Send: 01/01/98 23:59:59.991
// Receive: 01/01/98 23:59:59.990
Calendar sendValue = Calendar.getInstance();
Calendar receiveValue = Calendar.getInstance();
sendValue.set(Calendar.MONTH, Calendar.JANUARY);
sendValue.set(Calendar.DAY_OF_MONTH, 1);
sendValue.set(Calendar.YEAR, 1998);
sendValue.set(Calendar.HOUR_OF_DAY, 23);
sendValue.set(Calendar.MINUTE, 59);
sendValue.set(Calendar.SECOND, 59);
sendValue.set(Calendar.MILLISECOND, 991);
receiveValue.set(Calendar.MONTH, Calendar.JANUARY);
receiveValue.set(Calendar.DAY_OF_MONTH, 1);
receiveValue.set(Calendar.YEAR, 1998);
receiveValue.set(Calendar.HOUR_OF_DAY, 23);
receiveValue.set(Calendar.MINUTE, 59);
receiveValue.set(Calendar.SECOND, 59);
receiveValue.set(Calendar.MILLISECOND, 990);
Statement stmt = con.createStatement();
stmt.execute("create table #dtr2 (data datetime)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #dtr2 (data) values (?)");
pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime()));
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #dtr2");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(receiveValue.getTime().getTime(), getTimeInMs(rs));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for bug [994916] datetime decoding in TdsData.java
*/
public void testDatetimeRounding3() throws Exception {
// Per the SQL Server documentation
// Send: 01/01/98 23:59:59.992
// Receive: 01/01/98 23:59:59.993
Calendar sendValue = Calendar.getInstance();
Calendar receiveValue = Calendar.getInstance();
sendValue.set(Calendar.MONTH, Calendar.JANUARY);
sendValue.set(Calendar.DAY_OF_MONTH, 1);
sendValue.set(Calendar.YEAR, 1998);
sendValue.set(Calendar.HOUR_OF_DAY, 23);
sendValue.set(Calendar.MINUTE, 59);
sendValue.set(Calendar.SECOND, 59);
sendValue.set(Calendar.MILLISECOND, 992);
receiveValue.set(Calendar.MONTH, Calendar.JANUARY);
receiveValue.set(Calendar.DAY_OF_MONTH, 1);
receiveValue.set(Calendar.YEAR, 1998);
receiveValue.set(Calendar.HOUR_OF_DAY, 23);
receiveValue.set(Calendar.MINUTE, 59);
receiveValue.set(Calendar.SECOND, 59);
receiveValue.set(Calendar.MILLISECOND, 993);
Statement stmt = con.createStatement();
stmt.execute("create table #dtr3 (data datetime)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #dtr3 (data) values (?)");
pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime()));
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #dtr3");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(receiveValue.getTime().getTime(), getTimeInMs(rs));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for bug [994916] datetime decoding in TdsData.java
*/
public void testDatetimeRounding4() throws Exception {
// Per the SQL Server documentation
// Send: 01/01/98 23:59:59.993
// Receive: 01/01/98 23:59:59.993
Calendar sendValue = Calendar.getInstance();
Calendar receiveValue = Calendar.getInstance();
sendValue.set(Calendar.MONTH, Calendar.JANUARY);
sendValue.set(Calendar.DAY_OF_MONTH, 1);
sendValue.set(Calendar.YEAR, 1998);
sendValue.set(Calendar.HOUR_OF_DAY, 23);
sendValue.set(Calendar.MINUTE, 59);
sendValue.set(Calendar.SECOND, 59);
sendValue.set(Calendar.MILLISECOND, 993);
receiveValue.set(Calendar.MONTH, Calendar.JANUARY);
receiveValue.set(Calendar.DAY_OF_MONTH, 1);
receiveValue.set(Calendar.YEAR, 1998);
receiveValue.set(Calendar.HOUR_OF_DAY, 23);
receiveValue.set(Calendar.MINUTE, 59);
receiveValue.set(Calendar.SECOND, 59);
receiveValue.set(Calendar.MILLISECOND, 993);
Statement stmt = con.createStatement();
stmt.execute("create table #dtr4 (data datetime)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #dtr4 (data) values (?)");
pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime()));
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #dtr4");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(receiveValue.getTime().getTime(), getTimeInMs(rs));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for bug [994916] datetime decoding in TdsData.java
*/
public void testDatetimeRounding5() throws Exception {
// Per the SQL Server documentation
// Send: 01/01/98 23:59:59.994
// Receive: 01/01/98 23:59:59.993
Calendar sendValue = Calendar.getInstance();
Calendar receiveValue = Calendar.getInstance();
sendValue.set(Calendar.MONTH, Calendar.JANUARY);
sendValue.set(Calendar.DAY_OF_MONTH, 1);
sendValue.set(Calendar.YEAR, 1998);
sendValue.set(Calendar.HOUR_OF_DAY, 23);
sendValue.set(Calendar.MINUTE, 59);
sendValue.set(Calendar.SECOND, 59);
sendValue.set(Calendar.MILLISECOND, 994);
receiveValue.set(Calendar.MONTH, Calendar.JANUARY);
receiveValue.set(Calendar.DAY_OF_MONTH, 1);
receiveValue.set(Calendar.YEAR, 1998);
receiveValue.set(Calendar.HOUR_OF_DAY, 23);
receiveValue.set(Calendar.MINUTE, 59);
receiveValue.set(Calendar.SECOND, 59);
receiveValue.set(Calendar.MILLISECOND, 993);
Statement stmt = con.createStatement();
stmt.execute("create table #dtr5 (data datetime)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #dtr5 (data) values (?)");
pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime()));
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #dtr5");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(receiveValue.getTime().getTime(), getTimeInMs(rs));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for bug [994916] datetime decoding in TdsData.java
*/
public void testDatetimeRounding6() throws Exception {
// Per the SQL Server documentation
// Send: 01/01/98 23:59:59.995
// Receive: 01/01/98 23:59:59.997
Calendar sendValue = Calendar.getInstance();
Calendar receiveValue = Calendar.getInstance();
sendValue.set(Calendar.MONTH, Calendar.JANUARY);
sendValue.set(Calendar.DAY_OF_MONTH, 1);
sendValue.set(Calendar.YEAR, 1998);
sendValue.set(Calendar.HOUR_OF_DAY, 23);
sendValue.set(Calendar.MINUTE, 59);
sendValue.set(Calendar.SECOND, 59);
sendValue.set(Calendar.MILLISECOND, 995);
receiveValue.set(Calendar.MONTH, Calendar.JANUARY);
receiveValue.set(Calendar.DAY_OF_MONTH, 1);
receiveValue.set(Calendar.YEAR, 1998);
receiveValue.set(Calendar.HOUR_OF_DAY, 23);
receiveValue.set(Calendar.MINUTE, 59);
receiveValue.set(Calendar.SECOND, 59);
receiveValue.set(Calendar.MILLISECOND, 997);
Statement stmt = con.createStatement();
stmt.execute("create table #dtr6 (data datetime)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #dtr6 (data) values (?)");
pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime()));
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #dtr6");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(receiveValue.getTime().getTime(), getTimeInMs(rs));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for bug [994916] datetime decoding in TdsData.java
*/
public void testDatetimeRounding7() throws Exception {
// Per the SQL Server documentation
// Send: 01/01/98 23:59:59.996
// Receive: 01/01/98 23:59:59.997
Calendar sendValue = Calendar.getInstance();
Calendar receiveValue = Calendar.getInstance();
sendValue.set(Calendar.MONTH, Calendar.JANUARY);
sendValue.set(Calendar.DAY_OF_MONTH, 1);
sendValue.set(Calendar.YEAR, 1998);
sendValue.set(Calendar.HOUR_OF_DAY, 23);
sendValue.set(Calendar.MINUTE, 59);
sendValue.set(Calendar.SECOND, 59);
sendValue.set(Calendar.MILLISECOND, 996);
receiveValue.set(Calendar.MONTH, Calendar.JANUARY);
receiveValue.set(Calendar.DAY_OF_MONTH, 1);
receiveValue.set(Calendar.YEAR, 1998);
receiveValue.set(Calendar.HOUR_OF_DAY, 23);
receiveValue.set(Calendar.MINUTE, 59);
receiveValue.set(Calendar.SECOND, 59);
receiveValue.set(Calendar.MILLISECOND, 997);
Statement stmt = con.createStatement();
stmt.execute("create table #dtr7 (data datetime)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #dtr7 (data) values (?)");
pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime()));
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #dtr7");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(receiveValue.getTime().getTime(), getTimeInMs(rs));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for bug [994916] datetime decoding in TdsData.java
*/
public void testDatetimeRounding8() throws Exception {
// Per the SQL Server documentation
// Send: 01/01/98 23:59:59.997
// Receive: 01/01/98 23:59:59.997
Calendar sendValue = Calendar.getInstance();
Calendar receiveValue = Calendar.getInstance();
sendValue.set(Calendar.MONTH, Calendar.JANUARY);
sendValue.set(Calendar.DAY_OF_MONTH, 1);
sendValue.set(Calendar.YEAR, 1998);
sendValue.set(Calendar.HOUR_OF_DAY, 23);
sendValue.set(Calendar.MINUTE, 59);
sendValue.set(Calendar.SECOND, 59);
sendValue.set(Calendar.MILLISECOND, 997);
receiveValue.set(Calendar.MONTH, Calendar.JANUARY);
receiveValue.set(Calendar.DAY_OF_MONTH, 1);
receiveValue.set(Calendar.YEAR, 1998);
receiveValue.set(Calendar.HOUR_OF_DAY, 23);
receiveValue.set(Calendar.MINUTE, 59);
receiveValue.set(Calendar.SECOND, 59);
receiveValue.set(Calendar.MILLISECOND, 997);
Statement stmt = con.createStatement();
stmt.execute("create table #dtr8 (data datetime)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #dtr8 (data) values (?)");
pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime()));
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #dtr8");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(receiveValue.getTime().getTime(), getTimeInMs(rs));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for bug [994916] datetime decoding in TdsData.java
*/
public void testDatetimeRounding9() throws Exception {
// Per the SQL Server documentation
// Send: 01/01/98 23:59:59.998
// Receive: 01/01/98 23:59:59.997
Calendar sendValue = Calendar.getInstance();
Calendar receiveValue = Calendar.getInstance();
sendValue.set(Calendar.MONTH, Calendar.JANUARY);
sendValue.set(Calendar.DAY_OF_MONTH, 1);
sendValue.set(Calendar.YEAR, 1998);
sendValue.set(Calendar.HOUR_OF_DAY, 23);
sendValue.set(Calendar.MINUTE, 59);
sendValue.set(Calendar.SECOND, 59);
sendValue.set(Calendar.MILLISECOND, 998);
receiveValue.set(Calendar.MONTH, Calendar.JANUARY);
receiveValue.set(Calendar.DAY_OF_MONTH, 1);
receiveValue.set(Calendar.YEAR, 1998);
receiveValue.set(Calendar.HOUR_OF_DAY, 23);
receiveValue.set(Calendar.MINUTE, 59);
receiveValue.set(Calendar.SECOND, 59);
receiveValue.set(Calendar.MILLISECOND, 997);
Statement stmt = con.createStatement();
stmt.execute("create table #dtr9 (data datetime)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #dtr9 (data) values (?)");
pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime()));
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #dtr9");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(receiveValue.getTime().getTime(), getTimeInMs(rs));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for bug [994916] datetime decoding in TdsData.java
*/
public void testDatetimeRounding10() throws Exception {
// Per the SQL Server documentation
// Send: 01/01/98 23:59:59.999
// Receive: 01/02/98 00:00:00.000
Calendar sendValue = Calendar.getInstance();
Calendar receiveValue = Calendar.getInstance();
sendValue.set(Calendar.MONTH, Calendar.JANUARY);
sendValue.set(Calendar.DAY_OF_MONTH, 1);
sendValue.set(Calendar.YEAR, 1998);
sendValue.set(Calendar.HOUR_OF_DAY, 23);
sendValue.set(Calendar.MINUTE, 59);
sendValue.set(Calendar.SECOND, 59);
sendValue.set(Calendar.MILLISECOND, 999);
receiveValue.set(Calendar.MONTH, Calendar.JANUARY);
receiveValue.set(Calendar.DAY_OF_MONTH, 2);
receiveValue.set(Calendar.YEAR, 1998);
receiveValue.set(Calendar.HOUR_OF_DAY, 0);
receiveValue.set(Calendar.MINUTE, 0);
receiveValue.set(Calendar.SECOND, 0);
receiveValue.set(Calendar.MILLISECOND, 0);
Statement stmt = con.createStatement();
stmt.execute("create table #dtr10 (data datetime)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #dtr10 (data) values (?)");
pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime()));
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #dtr10");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(receiveValue.getTime().getTime(), getTimeInMs(rs));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for bug [1036059] getTimestamp with Calendar applies tzone offset
* wrong way.
*/
public void testTimestampTimeZone() throws SQLException {
Statement stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE #testTimestampTimeZone ("
+ "ref INT NOT NULL, "
+ "tstamp DATETIME NOT NULL)");
stmt.close();
Calendar calNY = Calendar.getInstance
(TimeZone.getTimeZone("America/New_York"));
Timestamp tsStart = new Timestamp(System.currentTimeMillis());
PreparedStatement pstmt = con.prepareStatement(
"INSERT INTO #testTimestampTimeZone (ref, tstamp) VALUES (?, ?)");
pstmt.setInt(1, 0);
pstmt.setTimestamp(2, tsStart, calNY);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
pstmt = con.prepareStatement(
"SELECT * FROM #testTimestampTimeZone WHERE ref = ?");
pstmt.setInt(1, 0);
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
Timestamp ts = rs.getTimestamp("tstamp", calNY);
// The difference should be less than 3 milliseconds (i.e. 1 or 2)
assertTrue(Math.abs(tsStart.getTime()-ts.getTime()) < 3);
rs.close();
pstmt.close();
}
/**
* Test for bug [1040475] Possible bug when converting to and from
* datetime.
*
* jTDS seems to accept dates outside the range accepted by SQL
* Server (i.e. 1753-9999).
*/
public void testTimestampRange() throws SQLException {
Statement stmt = con.createStatement();
stmt.executeUpdate(
"CREATE TABLE #testTimestampRange (id INT, d DATETIME)");
PreparedStatement pstmt = con.prepareStatement(
"INSERT INTO #testTimestampRange VALUES (?, ?)");
pstmt.setInt(1, 1);
try {
pstmt.setDate(2, Date.valueOf("0012-03-03")); // This should fail
pstmt.executeUpdate();
fail("Expecting an exception to be thrown. Date out of range.");
} catch (SQLException ex) {
assertEquals("22003", ex.getSQLState());
}
pstmt.close();
ResultSet rs = stmt.executeQuery("SELECT * FROM #testTimestampRange");
assertFalse("Row was inserted even though date was out of range.", rs.next());
rs.close();
stmt.close();
}
/**
* Test that java.sql.Date objects are inserted and retrieved
* correctly (ie no time component).
*/
public void testWriteDate() throws SQLException {
Statement stmt = con.createStatement();
stmt.executeUpdate(
"CREATE TABLE #testWriteDate (d DATETIME)");
stmt.close();
long time = System.currentTimeMillis();
PreparedStatement pstmt = con.prepareStatement(
"INSERT INTO #testWriteDate VALUES (?)");
pstmt.setDate(1, new Date(time));
pstmt.executeUpdate();
pstmt.close();
pstmt = con.prepareStatement("SELECT * FROM #testWriteDate WHERE d=?");
pstmt.setDate(1, new Date(time + 10));
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertTrue(time - rs.getDate(1).getTime() < 24 * 60 * 60 * 1000);
Calendar c1 = new GregorianCalendar(), c2 = new GregorianCalendar();
c1.setTime(rs.getTimestamp(1));
c2.setTime(new Timestamp(time));
assertEquals(c2.get(Calendar.YEAR), c1.get(Calendar.YEAR));
assertEquals(c2.get(Calendar.MONTH), c1.get(Calendar.MONTH));
assertEquals(c2.get(Calendar.DAY_OF_MONTH), c1.get(Calendar.DAY_OF_MONTH));
assertEquals(0, c1.get(Calendar.HOUR));
assertEquals(0, c1.get(Calendar.MINUTE));
assertEquals(0, c1.get(Calendar.SECOND));
assertEquals(0, c1.get(Calendar.MILLISECOND));
rs.close();
pstmt.close();
stmt = con.createStatement();
rs = stmt.executeQuery("select datepart(hour, d), datepart(minute, d),"
+ " datepart(second, d), datepart(millisecond, d)"
+ " from #testWriteDate");
assertTrue(rs.next());
assertEquals(0, rs.getInt(1));
assertEquals(0, rs.getInt(2));
assertEquals(0, rs.getInt(3));
assertEquals(0, rs.getInt(4));
assertFalse(rs.next());
rs.close();
stmt.close();
}
/**
* Test for bug [1226210] {fn dayofweek()} depends on the language.
*/
public void testDayOfWeek() throws Exception {
PreparedStatement pstmt =
con.prepareStatement("SELECT {fn dayofweek({fn curdate()})}");
// Execute and retrieve the day of week with the default @@DATEFIRST
ResultSet rs = pstmt.executeQuery();
assertNotNull(rs);
assertTrue(rs.next());
int day = rs.getInt(1);
// Set a new (very unlikely) value for @@DATEFIRST (Thursday)
Statement stmt = con.createStatement();
assertEquals(0, stmt.executeUpdate("SET DATEFIRST 4"));
stmt.close();
// Now re-execute and compare the two values
rs = pstmt.executeQuery();
assertNotNull(rs);
assertTrue(rs.next());
assertEquals(day, rs.getInt(1));
pstmt.close();
}
/**
* Test for bug [1235845] getTimestamp() returns illegal value after
* getString().
*/
public void testGetString() throws SQLException {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select getdate()");
assertTrue(rs.next());
String stringValue = rs.getString(1);
String timestampValue = rs.getTimestamp(1).toString();
assertEquals(stringValue, timestampValue);
rs.close();
stmt.close();
}
/**
* Test for bug [1234531] Dates before 01/01/1900 broken due to DateTime
* value markers.
*/
public void test1899Date() throws Exception {
// Per the SQL Server documentation
// Send: 12/31/1899 23:59:59.990
// Receive: 12/31/1899 23:59:59.990
Calendar originalValue = Calendar.getInstance();
originalValue.set(Calendar.MONTH, Calendar.DECEMBER);
originalValue.set(Calendar.DAY_OF_MONTH, 31);
originalValue.set(Calendar.YEAR, 1899);
originalValue.set(Calendar.HOUR_OF_DAY, 23);
originalValue.set(Calendar.MINUTE, 59);
originalValue.set(Calendar.SECOND, 59);
originalValue.set(Calendar.MILLISECOND, 990);
PreparedStatement pstmt = con.prepareStatement("select ?");
pstmt.setTimestamp(1, new Timestamp(originalValue.getTime().getTime()));
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
final long expectedTime = originalValue.getTime().getTime();
final long actualTime = getTimeInMs(rs);
assertEquals(expectedTime, actualTime);
assertFalse(rs.next());
rs.close();
pstmt.close();
}
/**
* Java 1.3 Timestamp.getDate() does not add the nano seconds to
* the millisecond value returned. This causes the timestamp tests
* to fail. If running under java 1.3 we add the nanos ourselves.
*
* @param rs the result set returning the Timstamp value in column 1
* @return the millisecond date value as a long.
*/
public long getTimeInMs(ResultSet rs)
throws SQLException {
Timestamp value = rs.getTimestamp(1);
long ms = value.getTime();
if (!Driver.JDBC3) {
// Not Running under 1.4 so need to add milliseconds
ms += ((java.sql.Timestamp)value).getNanos() / 1000000;
}
return ms;
}
/**
* Test for bug [2508201], date field is changed by 3 milliseconds.
*
* Note: This test will fail for some server types due to "DATE" and "TIME"
* data types not being available.
*/
public void testDateTimeDegeneration() throws Exception {
Timestamp ts1 = Timestamp.valueOf("1970-01-01 00:00:00.000");
String[] types = new String[] {"datetime","date","time"};
for (int t = 0; t < types.length; t++) {
String type = types[t];
// create table and insert initial value
Statement stmt = con.createStatement();
stmt.execute("create table #t_" + type + " (id int,data " + type + ")");
stmt.execute("insert into #t_" + type + " values (0,'" + ts1.toString() + "')");
PreparedStatement ps1 = con.prepareStatement("update #t_" + type + " set data=? where id=0");
PreparedStatement ps2 = con.prepareStatement("select data from #t_" + type);
// read previous value
ResultSet rs = ps2.executeQuery();
rs.next();
Timestamp ts2 = rs.getTimestamp(1);
// compare current value to initial value
assertEquals(type + " value degenerated: ", ts1.toString(), ts2.toString());
rs.close();
// update DB with current value
ps1.setTimestamp(1, ts2);
ps1.executeUpdate();
ps1.close();
ps2.close();
stmt.close();
}
}
public void testEscaping() throws SQLException {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT 'a',{ts '2007-10-19 10:20:30.000'}");
assertTrue(rs.next());
assertEquals("2007-10-19 10:20:30.000", rs.getString(2).toString());
assertEquals("2007-10-19 10:20:30.000", rs.getTimestamp(2).toString());
rs.close();
st.close();
}
/**
* Test for bugs [2181003]/[2349058], an attempt to set a BC date
* invalidates driver state/DateTime allows invalid dates through.
*/
public void testEra() throws SQLException {
Statement st = con.createStatement();
st.execute("create table #testEra(data datetime)");
st.close();
String date = "2000-11-11";
Date original = Date.valueOf(date);
PreparedStatement in = con.prepareStatement("insert into #testEra values(?)");
PreparedStatement out = con.prepareStatement("select * from #testEra");
ResultSet rs = null;
// insert valid value
in.setDate(1, Date.valueOf(date));
in.execute();
// check timestamp
rs = out.executeQuery();
assertTrue(rs.next());
assertEquals(original,rs.getDate(1));
rs.close();
// attempt to set invalid BC date (January 1st, 300 BC)
try {
GregorianCalendar gc = new GregorianCalendar();
gc.set(GregorianCalendar.ERA, GregorianCalendar.BC);
gc.set(GregorianCalendar.YEAR, 300);
gc.set(GregorianCalendar.MONTH,GregorianCalendar.JANUARY);
gc.set(GregorianCalendar.DAY_OF_MONTH, 1);
in.setDate(1, new Date(gc.getTime().getTime()));
assertTrue("invalid date should cause an exception", false);
} catch( SQLException e ) {
// expected error
}
// re-check timestamp
rs = out.executeQuery();
assertTrue(rs.next());
assertEquals(original,rs.getDate(1));
rs.close();
in.close();
out.close();
}
} libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/CallableStatementTest.java 0000644 0001750 0001750 00000102365 11316672660 030306 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.sql.*;
import java.math.BigDecimal;
//
// MJH - Changes for new jTDS version
// Added registerOutParameter to testCallableStatementParsing2
//
/**
* @version 1.0
*/
public class CallableStatementTest extends TestBase {
public CallableStatementTest(String name) {
super(name);
}
public void testCallableStatement() throws Exception {
CallableStatement cstmt = con.prepareCall("{call sp_who}");
cstmt.close();
}
public void testCallableStatement1() throws Exception {
CallableStatement cstmt = con.prepareCall("sp_who");
ResultSet rs = cstmt.executeQuery();
dump(rs);
rs.close();
cstmt.close();
}
public void testCallableStatementCall1() throws Exception {
CallableStatement cstmt = con.prepareCall("{call sp_who}");
ResultSet rs = cstmt.executeQuery();
dump(rs);
rs.close();
cstmt.close();
}
public void testCallableStatementCall2() throws Exception {
CallableStatement cstmt = con.prepareCall("{CALL sp_who}");
ResultSet rs = cstmt.executeQuery();
dump(rs);
rs.close();
cstmt.close();
}
public void testCallableStatementCall3() throws Exception {
CallableStatement cstmt = con.prepareCall("{cAlL sp_who}");
ResultSet rs = cstmt.executeQuery();
dump(rs);
rs.close();
cstmt.close();
}
/**
* Test for bug [974801] stored procedure error in Northwind
*/
public void testCallableStatementCall4() throws Exception {
Statement stmt;
try {
stmt = con.createStatement();
stmt.execute("create procedure \"#test space\" as SELECT COUNT(*) FROM sysobjects");
stmt.close();
CallableStatement cstmt = con.prepareCall("{call \"#test space\"}");
ResultSet rs = cstmt.executeQuery();
dump(rs);
rs.close();
cstmt.close();
} finally {
stmt = con.createStatement();
stmt.execute("drop procedure \"#test space\"");
stmt.close();
}
}
public void testCallableStatementExec1() throws Exception {
CallableStatement cstmt = con.prepareCall("exec sp_who");
ResultSet rs = cstmt.executeQuery();
dump(rs);
rs.close();
cstmt.close();
}
public void testCallableStatementExec2() throws Exception {
CallableStatement cstmt = con.prepareCall("EXEC sp_who");
ResultSet rs = cstmt.executeQuery();
dump(rs);
rs.close();
cstmt.close();
}
public void testCallableStatementExec3() throws Exception {
CallableStatement cstmt = con.prepareCall("execute sp_who");
ResultSet rs = cstmt.executeQuery();
dump(rs);
rs.close();
cstmt.close();
}
public void testCallableStatementExec4() throws Exception {
CallableStatement cstmt = con.prepareCall("EXECUTE sp_who");
ResultSet rs = cstmt.executeQuery();
dump(rs);
rs.close();
cstmt.close();
}
public void testCallableStatementExec5() throws Exception {
CallableStatement cstmt = con.prepareCall("eXeC sp_who");
ResultSet rs = cstmt.executeQuery();
dump(rs);
rs.close();
cstmt.close();
}
public void testCallableStatementExec6() throws Exception {
CallableStatement cstmt = con.prepareCall("ExEcUtE sp_who");
ResultSet rs = cstmt.executeQuery();
dump(rs);
rs.close();
cstmt.close();
}
public void testCallableStatementExec7() throws Exception {
CallableStatement cstmt = con.prepareCall("execute \"master\"..sp_who");
ResultSet rs = cstmt.executeQuery();
dump(rs);
rs.close();
cstmt.close();
}
public void testCallableStatementExec8() throws Exception {
Statement stmt;
try {
stmt = con.createStatement();
stmt.execute("create procedure #test as SELECT COUNT(*) FROM sysobjects");
stmt.close();
CallableStatement cstmt = con.prepareCall("execute #test");
ResultSet rs = cstmt.executeQuery();
dump(rs);
rs.close();
cstmt.close();
} finally {
stmt = con.createStatement();
stmt.execute("drop procedure #test");
stmt.close();
}
}
/**
* Test for bug [978175] 0.8: Stored Procedure call doesn't work anymore
*/
public void testCallableStatementExec9() throws Exception {
CallableStatement cstmt = con.prepareCall("{call sp_who}");
assertTrue(cstmt.execute());
ResultSet rs = cstmt.getResultSet();
if (rs == null) {
fail("Null ResultSet returned");
} else {
dump(rs);
rs.close();
}
cstmt.close();
}
public void testCallableStatementParsing1() throws Exception {
String data = "New {order} plus {1} more";
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #csp1 (data VARCHAR(32))");
stmt.close();
stmt = con.createStatement();
stmt.execute("create procedure #sp_csp1 @data VARCHAR(32) as INSERT INTO #csp1 (data) VALUES(@data)");
stmt.close();
CallableStatement cstmt = con.prepareCall("{call #sp_csp1(?)}");
cstmt.setString(1, data);
cstmt.execute();
cstmt.close();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT data FROM #csp1");
assertTrue(rs.next());
assertTrue(data.equals(rs.getString(1)));
assertTrue(!rs.next());
rs.close();
stmt.close();
}
/**
* Test for bug [938632] String index out of bounds error in 0.8rc1.
*/
public void testCallableStatementParsing2() throws Exception {
try {
Statement stmt = con.createStatement();
stmt.execute("create procedure #load_smtp_in_1gr_ls804192 as SELECT name FROM sysobjects");
stmt.close();
CallableStatement cstmt = con.prepareCall("{?=call #load_smtp_in_1gr_ls804192}");
cstmt.registerOutParameter(1, java.sql.Types.INTEGER); // MJH 01/05/04
cstmt.execute();
cstmt.close();
} finally {
Statement stmt = con.createStatement();
stmt.execute("drop procedure #load_smtp_in_1gr_ls804192");
stmt.close();
}
}
/**
* Test for bug [1006845] Stored procedure with 18 parameters.
*/
public void testCallableStatementParsing3() throws Exception {
CallableStatement cstmt = con.prepareCall("{Call Test(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt.close();
}
/**
* Test for incorrect exception thrown/no exception thrown when invalid
* call escape is used.
*
} causes the parser to fail).
*/
public void testCallableStatementParsing5() throws Exception {
CallableStatement cstmt = con.prepareCall(" { Call Test(?,?) } ");
cstmt.close();
}
/**
* Test for incorrect exception thrown/no exception thrown when invalid
* call escape is used.
*
* A message containing the correct missing terminator should be generated.
*/
public void testCallableStatementParsing6() throws SQLException {
try {
con.prepareCall("{call sp_test(?, ?)");
fail("Was expecting an invalid escape error");
} catch (SQLException ex) {
assertEquals("22025", ex.getSQLState());
assertTrue(ex.getMessage().indexOf('}') != -1);
}
}
/**
* Test for incorrect exception thrown/no exception thrown when invalid
* call escape is used.
*
* A message containing the correct missing terminator should be generated.
*/
public void testCallableStatementParsing7() throws SQLException {
try {
con.prepareCall("{call sp_test(?, ?}");
fail("Was expecting an invalid escape error");
} catch (SQLException ex) {
assertEquals("22025", ex.getSQLState());
assertTrue(ex.getMessage().indexOf(')') != -1);
}
}
/**
* Test for reature request [956800] setNull(): Not implemented.
*/
public void testCallableSetNull1() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #callablesetnull1 (data CHAR(1) NULL)");
stmt.close();
try {
stmt = con.createStatement();
stmt.execute("create procedure #procCallableSetNull1 @data char(1) "
+ "as INSERT INTO #callablesetnull1 (data) VALUES (@data)");
stmt.close();
CallableStatement cstmt = con.prepareCall("{call #procCallableSetNull1(?)}");
// Test CallableStatement.setNull(int,Types.NULL)
cstmt.setNull(1, Types.NULL);
cstmt.execute();
cstmt.close();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT data FROM #callablesetnull1");
assertTrue(rs.next());
// Test ResultSet.getString()
assertNull(rs.getString(1));
assertTrue(rs.wasNull());
assertTrue(!rs.next());
stmt.close();
rs.close();
} finally {
stmt = con.createStatement();
stmt.execute("drop procedure #procCallableSetNull1");
stmt.close();
}
}
/**
* Test for bug [974284] retval on callable statement isn't handled correctly
*/
public void testCallableRegisterOutParameter1() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("create procedure #rop1 @a varchar(1), @b varchar(1) as\r\n "
+ "begin\r\n"
+ "return 1\r\n"
+ "end");
stmt.close();
CallableStatement cstmt = con.prepareCall("{? = call #rop1(?, ?)}");
cstmt.registerOutParameter(1, Types.INTEGER);
cstmt.setString(2, "a");
cstmt.setString(3, "b");
cstmt.execute();
assertEquals(1, cstmt.getInt(1));
assertEquals("1", cstmt.getString(1));
cstmt.close();
}
/**
* Test for bug [994888] Callable statement and Float output parameter
*/
public void testCallableRegisterOutParameter2() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("create procedure #rop2 @data float OUTPUT as\r\n "
+ "begin\r\n"
+ "set @data = 1.1\r\n"
+ "end");
stmt.close();
CallableStatement cstmt = con.prepareCall("{call #rop2(?)}");
cstmt.registerOutParameter(1, Types.FLOAT);
cstmt.execute();
assertTrue(cstmt.getFloat(1) == 1.1f);
cstmt.close();
}
/**
* Test for bug [994988] Network error when null is returned via int output parm
*/
public void testCallableRegisterOutParameter3() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("create procedure #rop3 @data int OUTPUT as\r\n "
+ "begin\r\n"
+ "set @data = null\r\n"
+ "end");
stmt.close();
CallableStatement cstmt = con.prepareCall("{call #rop3(?)}");
cstmt.registerOutParameter(1, Types.INTEGER);
cstmt.execute();
cstmt.getInt(1);
assertTrue(cstmt.wasNull());
cstmt.close();
}
/**
* Test for bug [983432] Prepared call doesn't work with jTDS 0.8
*/
public void testCallableRegisterOutParameter4() throws Exception {
CallableStatement cstmt = con.prepareCall("{call sp_addtype T_INTEGER, int, 'NULL'}");
Statement stmt = con.createStatement();
try {
cstmt.execute();
cstmt.close();
stmt.execute("create procedure rop4 @data T_INTEGER OUTPUT as\r\n "
+ "begin\r\n"
+ "set @data = 1\r\n"
+ "end");
stmt.close();
cstmt = con.prepareCall("{call rop4(?)}");
cstmt.registerOutParameter(1, Types.VARCHAR);
cstmt.execute();
assertEquals(cstmt.getInt(1), 1);
assertTrue(!cstmt.wasNull());
cstmt.close();
cstmt = con.prepareCall("rop4 ?");
cstmt.registerOutParameter(1, Types.VARCHAR);
cstmt.execute();
assertEquals(cstmt.getInt(1), 1);
assertTrue(!cstmt.wasNull());
cstmt.close();
} finally {
stmt = con.createStatement();
stmt.execute("drop procedure rop4");
stmt.close();
cstmt = con.prepareCall("{call sp_droptype 'T_INTEGER'}");
cstmt.execute();
cstmt.close();
}
}
/**
* Test for bug [991640] java.sql.Date error and RAISERROR problem
*/
public void testCallableError1() throws Exception {
String text = "test message";
Statement stmt = con.createStatement();
stmt.execute("create procedure #ce1 as\r\n "
+ "begin\r\n"
+ "RAISERROR('" + text + "', 16, 1 )\r\n"
+ "end");
stmt.close();
CallableStatement cstmt = con.prepareCall("{call #ce1}");
try {
cstmt.execute();
assertTrue(false);
} catch (SQLException e) {
assertTrue(e.getMessage().equals(text));
}
cstmt.close();
}
/**
* Test that procedure outputs are available immediately for procedures
* that do not return ResultSets (i.e that update counts are cached).
*/
public void testProcessUpdateCounts1() throws SQLException {
Statement stmt = con.createStatement();
assertFalse(stmt.execute("CREATE TABLE #testProcessUpdateCounts1 (val INT)"));
assertFalse(stmt.execute("CREATE PROCEDURE #procTestProcessUpdateCounts1"
+ " @res INT OUT AS"
+ " INSERT INTO #testProcessUpdateCounts1 VALUES (1)"
+ " UPDATE #testProcessUpdateCounts1 SET val = 2"
+ " INSERT INTO #testProcessUpdateCounts1 VALUES (1)"
+ " UPDATE #testProcessUpdateCounts1 SET val = 3"
+ " SET @res = 13"
+ " RETURN 14"));
stmt.close();
CallableStatement cstmt = con.prepareCall(
"{?=call #procTestProcessUpdateCounts1(?)}");
cstmt.registerOutParameter(1, Types.INTEGER);
cstmt.registerOutParameter(2, Types.INTEGER);
assertFalse(cstmt.execute());
assertEquals(14, cstmt.getInt(1));
assertEquals(13, cstmt.getInt(2));
assertEquals(1, cstmt.getUpdateCount()); // INSERT
assertFalse(cstmt.getMoreResults());
assertEquals(1, cstmt.getUpdateCount()); // UPDATE
assertFalse(cstmt.getMoreResults());
assertEquals(1, cstmt.getUpdateCount()); // INSERT
assertFalse(cstmt.getMoreResults());
assertEquals(2, cstmt.getUpdateCount()); // UPDATE
assertFalse(cstmt.getMoreResults());
assertEquals(-1, cstmt.getUpdateCount());
cstmt.close();
}
/**
* Test that procedure outputs are available immediately after processing
* the last ResultSet returned by the procedure (i.e that update counts
* are cached).
*/
public void testProcessUpdateCounts2() throws SQLException {
Statement stmt = con.createStatement();
assertFalse(stmt.execute("CREATE TABLE #testProcessUpdateCounts2 (val INT)"));
assertFalse(stmt.execute("CREATE PROCEDURE #procTestProcessUpdateCounts2"
+ " @res INT OUT AS"
+ " INSERT INTO #testProcessUpdateCounts2 VALUES (1)"
+ " UPDATE #testProcessUpdateCounts2 SET val = 2"
+ " SELECT * FROM #testProcessUpdateCounts2"
+ " INSERT INTO #testProcessUpdateCounts2 VALUES (1)"
+ " UPDATE #testProcessUpdateCounts2 SET val = 3"
+ " SET @res = 13"
+ " RETURN 14"));
stmt.close();
CallableStatement cstmt = con.prepareCall(
"{?=call #procTestProcessUpdateCounts2(?)}");
cstmt.registerOutParameter(1, Types.INTEGER);
cstmt.registerOutParameter(2, Types.INTEGER);
assertFalse(cstmt.execute());
try {
assertEquals(14, cstmt.getInt(1));
assertEquals(13, cstmt.getInt(2));
// Don't fail the test if we got here. Another driver or a future
// version could cache all the results and obtain the output
// parameter values from the beginning.
} catch (SQLException ex) {
assertEquals("HY010", ex.getSQLState());
assertTrue(ex.getMessage().indexOf("getMoreResults()") >= 0);
}
assertEquals(1, cstmt.getUpdateCount()); // INSERT
assertFalse(cstmt.getMoreResults());
assertEquals(1, cstmt.getUpdateCount()); // UPDATE
assertTrue(cstmt.getMoreResults()); // SELECT
assertFalse(cstmt.getMoreResults());
assertEquals(14, cstmt.getInt(1));
assertEquals(13, cstmt.getInt(2));
assertEquals(1, cstmt.getUpdateCount()); // INSERT
assertFalse(cstmt.getMoreResults());
assertEquals(2, cstmt.getUpdateCount()); // UPDATE
assertFalse(cstmt.getMoreResults());
assertEquals(-1, cstmt.getUpdateCount());
cstmt.close();
}
/**
* Test that procedure outputs are available immediately after processing
* the last ResultSet returned by the procedure (i.e that update counts
* are cached) even if getMoreResults() is not called.
*/
public void testProcessUpdateCounts3() throws SQLException {
Statement stmt = con.createStatement();
assertFalse(stmt.execute("CREATE TABLE #testProcessUpdateCounts3 (val INT)"));
assertFalse(stmt.execute("CREATE PROCEDURE #procTestProcessUpdateCounts3"
+ " @res INT OUT AS"
+ " INSERT INTO #testProcessUpdateCounts3 VALUES (1)"
+ " UPDATE #testProcessUpdateCounts3 SET val = 2"
+ " SELECT * FROM #testProcessUpdateCounts3"
+ " INSERT INTO #testProcessUpdateCounts3 VALUES (1)"
+ " UPDATE #testProcessUpdateCounts3 SET val = 3"
+ " SET @res = 13"
+ " RETURN 14"));
stmt.close();
CallableStatement cstmt = con.prepareCall(
"{?=call #procTestProcessUpdateCounts3(?)}");
cstmt.registerOutParameter(1, Types.INTEGER);
cstmt.registerOutParameter(2, Types.INTEGER);
assertFalse(cstmt.execute());
try {
assertEquals(14, cstmt.getInt(1));
assertEquals(13, cstmt.getInt(2));
// Don't fail the test if we got here. Another driver or a future
// version could cache all the results and obtain the output
// parameter values from the beginning.
} catch (SQLException ex) {
assertEquals("HY010", ex.getSQLState());
assertTrue(ex.getMessage().indexOf("getMoreResults()") >= 0);
}
assertEquals(1, cstmt.getUpdateCount()); // INSERT
assertFalse(cstmt.getMoreResults());
assertEquals(1, cstmt.getUpdateCount()); // UPDATE
assertTrue(cstmt.getMoreResults()); // SELECT
ResultSet rs = cstmt.getResultSet();
assertNotNull(rs);
// Close the ResultSet; this should cache the following update counts
rs.close();
assertEquals(14, cstmt.getInt(1));
assertEquals(13, cstmt.getInt(2));
assertFalse(cstmt.getMoreResults());
assertEquals(1, cstmt.getUpdateCount()); // INSERT
assertFalse(cstmt.getMoreResults());
assertEquals(2, cstmt.getUpdateCount()); // UPDATE
assertFalse(cstmt.getMoreResults());
assertEquals(-1, cstmt.getUpdateCount());
cstmt.close();
}
/**
* Test that procedure outputs are available immediately after processing
* the last ResultSet returned by the procedure (i.e that update counts
* are cached) even if getMoreResults() and ResultSet.close() are not
* called.
*/
public void testProcessUpdateCounts4() throws SQLException {
Statement stmt = con.createStatement();
assertFalse(stmt.execute("CREATE TABLE #testProcessUpdateCounts4 (val INT)"));
assertFalse(stmt.execute("CREATE PROCEDURE #procTestProcessUpdateCounts4"
+ " @res INT OUT AS"
+ " INSERT INTO #testProcessUpdateCounts4 VALUES (1)"
+ " UPDATE #testProcessUpdateCounts4 SET val = 2"
+ " SELECT * FROM #testProcessUpdateCounts4"
+ " INSERT INTO #testProcessUpdateCounts4 VALUES (1)"
+ " UPDATE #testProcessUpdateCounts4 SET val = 3"
+ " SET @res = 13"
+ " RETURN 14"));
stmt.close();
CallableStatement cstmt = con.prepareCall(
"{?=call #procTestProcessUpdateCounts4(?)}");
cstmt.registerOutParameter(1, Types.INTEGER);
cstmt.registerOutParameter(2, Types.INTEGER);
assertFalse(cstmt.execute());
try {
assertEquals(14, cstmt.getInt(1));
assertEquals(13, cstmt.getInt(2));
// Don't fail the test if we got here. Another driver or a future
// version could cache all the results and obtain the output
// parameter values from the beginning.
} catch (SQLException ex) {
assertEquals("HY010", ex.getSQLState());
assertTrue(ex.getMessage().indexOf("getMoreResults()") >= 0);
}
assertEquals(1, cstmt.getUpdateCount()); // INSERT
assertFalse(cstmt.getMoreResults());
assertEquals(1, cstmt.getUpdateCount()); // UPDATE
assertTrue(cstmt.getMoreResults()); // SELECT
ResultSet rs = cstmt.getResultSet();
assertNotNull(rs);
// Process all rows; this should cache the following update counts
assertTrue(rs.next());
assertFalse(rs.next());
assertEquals(14, cstmt.getInt(1));
assertEquals(13, cstmt.getInt(2));
// Only close the ResultSet now
rs.close();
assertFalse(cstmt.getMoreResults());
assertEquals(1, cstmt.getUpdateCount()); // INSERT
assertFalse(cstmt.getMoreResults());
assertEquals(2, cstmt.getUpdateCount()); // UPDATE
assertFalse(cstmt.getMoreResults());
assertEquals(-1, cstmt.getUpdateCount());
cstmt.close();
}
/**
* Test for bug [ 1062671 ] SQLParser unable to parse CONVERT(char,{ts ?},102)
*/
public void testTsEscape() throws Exception {
Timestamp ts = Timestamp.valueOf("2004-01-01 23:56:56");
Statement stmt = con.createStatement();
assertFalse(stmt.execute("CREATE TABLE #testTsEscape (val DATETIME)"));
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #testTsEscape VALUES({ts ?})");
pstmt.setTimestamp(1, ts);
assertEquals(1, pstmt.executeUpdate());
ResultSet rs = stmt.executeQuery("SELECT * FROM #testTsEscape");
assertTrue(rs.next());
assertEquals(ts, rs.getTimestamp(1));
}
/**
* Test for separation of IN and INOUT/OUT parameter values
*/
public void testInOutParameters() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE PROC #testInOut @in int, @out int output as SELECT @out = @out + @in");
CallableStatement cstmt = con.prepareCall("{ call #testInOut ( ?,? ) }");
cstmt.setInt(1, 1);
cstmt.registerOutParameter(2, Types.INTEGER);
cstmt.setInt(2, 2);
cstmt.execute();
assertEquals(3, cstmt.getInt(2));
cstmt.execute();
assertEquals(3, cstmt.getInt(2));
}
/**
* Test that procedure names containing semicolons are parsed correctly.
*/
public void testSemicolonProcedures() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE PROC #testInOut @in int, @out int output as SELECT @out = @out + @in");
CallableStatement cstmt = con.prepareCall("{call #testInOut;1(?,?)}");
cstmt.setInt(1, 1);
cstmt.registerOutParameter(2, Types.INTEGER);
cstmt.setInt(2, 2);
cstmt.execute();
assertEquals(3, cstmt.getInt(2));
cstmt.execute();
assertEquals(3, cstmt.getInt(2));
}
/**
* Test that procedure calls with both literal parameters and parameterr
* markers are executed correctly (bug [1078927] Callable statement fails).
*/
public void testNonRpcProc1() throws Exception {
Statement stmt = con.createStatement();
stmt.execute(
"create proc #testsp1 @p1 int, @p2 int out as set @p2 = @p1");
stmt.close();
CallableStatement cstmt = con.prepareCall("{call #testsp1(100, ?)}");
cstmt.setInt(1, 1);
cstmt.execute();
cstmt.close();
}
/**
* Test that procedure calls with both literal parameters and parameterr
* markers are executed correctly (bug [1078927] Callable statement fails).
*/
public void testNonRpcProc2() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("create proc #testsp2 @p1 int, @p2 int as return 99");
stmt.close();
CallableStatement cstmt = con.prepareCall("{?=call #testsp2(100, ?)}");
cstmt.registerOutParameter(1, java.sql.Types.INTEGER);
cstmt.setInt(2, 2);
cstmt.execute();
assertEquals(99, cstmt.getInt(1));
cstmt.close();
}
/**
* Test for bug [1152329] Spurious output params assigned (TIMESTMP).
*
* If a stored procedure execute WRITETEXT or UPDATETEXT commands, spurious
* output parameter data is returned to the client. This additional data
* can be confused with the real output parameter data leading to an output
* string parameter returning the text ?TIMESTMP? on SQL Server 7+ or
* binary garbage on other servers.
*/
public void testWritetext() throws Exception {
Statement stmt = con.createStatement();
stmt.execute(
"create proc #testWritetext @p1 varchar(20) output as "
+ "begin "
+ "create table #test (id int, txt text) "
+ "insert into #test (id, txt) values(1, '') "
+ "declare @ptr binary(16) "
+ "select @ptr = (select textptr(txt) from #test where id = 1) "
+ "writetext #test.txt @ptr 'This is a test' "
+ "select @p1 = 'done' "
+ "end");
stmt.close();
CallableStatement cstmt = con.prepareCall("{call #testWritetext(?)}");
cstmt.registerOutParameter(1, Types.VARCHAR);
cstmt.execute();
assertEquals("done", cstmt.getString(1));
cstmt.close();
}
/**
* Test for bug [1047208] SQLException chaining not implemented correctly:
* checks that all errors are returned and that output variables are also
* returned.
*/
public void testErrorOutputParams() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE PROC #error_proc @p1 int out AS \r\n" +
"RAISERROR ('TEST EXCEPTION', 15, 1)\r\n" +
"SELECT @P1=100\r\n" +
"CREATE TABLE #DUMMY (id int)\r\n" +
"INSERT INTO #DUMMY VALUES(1)\r\n"+
"INSERT INTO #DUMMY VALUES(1)");
stmt.close();
CallableStatement cstmt = con.prepareCall("{call #error_proc(?)}");
cstmt.registerOutParameter(1, Types.INTEGER);
try {
cstmt.execute();
fail("Expecting exception");
} catch (SQLException e) {
assertEquals("TEST EXCEPTION", e.getMessage());
}
assertEquals(100, cstmt.getInt(1));
cstmt.close();
}
/**
* Test for bug [1236078] Procedure doesn't get called for some BigDecimal
* values - invalid bug.
*/
public void testBigDecimal() throws Exception {
Statement stmt = con.createStatement();
assertEquals(0, stmt.executeUpdate("CREATE TABLE #dec_test "
+ "(ColumnVC varchar(50) NULL, ColumnDec decimal(18,4) NULL)"));
assertEquals(0, stmt.executeUpdate("CREATE PROCEDURE #dec_test2"
+ "(@inVc varchar(32), @inBd decimal(18,4)) AS "
+ "begin "
+ "update #dec_test set columnvc = @inVc, columndec = @inBd "
+ "end"));
assertEquals(1, stmt.executeUpdate(
"insert #dec_test (columnvc, columndec) values (null, null)"));
stmt.close();
CallableStatement cstmt = con.prepareCall("{call #dec_test2 (?,?)}");
cstmt.setString(1, "D: " + new java.util.Date());
cstmt.setBigDecimal(2, new BigDecimal("2.9E+7"));
assertEquals(1, cstmt.executeUpdate());
cstmt.close();
}
/**
* Test that output result sets, return values and output parameters are
* correctly handled for a remote procedure call.
* To set up this test you will a local and remote server where the remote
* server allows logins from the local test server.
* Install the following stored procedure on the remote server:
*
* create proc jtds_remote @in varchar(16), @out varchar(32) output as
* begin
* select 'result set'
* set @out = 'Test ' + @in;
* return 1
* end
*
* Uncomment this test and amend the remoteserver name in the prepareCall
* statement below to be the actual name of your remote server.
*
* The TDS stream for this test will comprise a result set, a dummy return
* (0x79) value and then the actual return and output parameter (0xAC) records.
*
* This call will fail with jtds 1.1 as the dummy return value of 0 in the
* TDS stream will preempt the capture of the actual value 1. In addition the
* return value will be assigned to the output parameter and the actual output
* parameter value will be lost.
*
*
public void testRemoteCallWithResultSet() throws Exception {
CallableStatement cstmt = con.prepareCall(
"{?=call remoteserver.database.user.jtds_remote(?,?)}");
cstmt.registerOutParameter(1, Types.INTEGER);
cstmt.setString(2, "data");
cstmt.registerOutParameter(3, Types.VARCHAR);
cstmt.execute();
ResultSet rs = cstmt.getResultSet();
assertNotNull(rs);
assertTrue(rs.next());
assertEquals("result set", rs.getString(1));
assertFalse(rs.next());
rs.close();
assertEquals(1, cstmt.getInt(1));
assertEquals("Test data", cstmt.getString(3));
cstmt.close();
}
*/
public static void main(String[] args) {
junit.textui.TestRunner.run(CallableStatementTest.class);
}
} libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/Tds8Test.java 0000644 0001750 0001750 00000034055 11316672660 025544 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import junit.framework.Test;
import junit.framework.TestSuite;
import net.sourceforge.jtds.jdbc.DefaultProperties;
import net.sourceforge.jtds.jdbc.Messages;
import net.sourceforge.jtds.jdbc.Driver;
import java.math.BigDecimal;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.sql.Types;
/**
* Test case to illustrate use of TDS 8 support
*
* @version 1.0
*/
public class Tds8Test extends DatabaseTestCase {
public static Test suite() {
if (!DefaultProperties.TDS_VERSION_80.equals(
props.getProperty(Messages.get(Driver.TDS)))) {
return new TestSuite();
}
return new TestSuite(Tds8Test.class);
}
public Tds8Test(String name) {
super(name);
}
public void testBigInt1() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #bigint1 (num bigint, txt varchar(100))");
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #bigint1 (num, txt) VALUES (?, ?)");
pstmt.setLong(1, 1234567890123L);
pstmt.setString(2, "1234567890123");
assertEquals("Insert bigint failed", 1, pstmt.executeUpdate());
ResultSet rs = stmt.executeQuery("SELECT * FROM #bigint1");
assertNotNull(rs);
assertTrue(rs.next());
assertEquals(String.valueOf(rs.getLong(1)), rs.getString(2));
stmt.close();
pstmt.close();
}
/**
* Test BIGINT data type.
* Test for [989963] BigInt becomes Numeric
*/
public void testBigInt2() throws Exception {
long data = 1;
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #bigint2 (data BIGINT, minval BIGINT, maxval BIGINT)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #bigint2 (data, minval, maxval) VALUES (?, ?, ?)");
pstmt.setLong(1, data);
pstmt.setLong(2, Long.MIN_VALUE);
pstmt.setLong(3, Long.MAX_VALUE);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data, minval, maxval FROM #bigint2");
assertTrue(rs.next());
assertTrue(rs.getBoolean(1));
assertTrue(rs.getByte(1) == 1);
assertTrue(rs.getShort(1) == 1);
assertTrue(rs.getInt(1) == 1);
assertTrue(rs.getLong(1) == 1);
assertTrue(rs.getFloat(1) == 1);
assertTrue(rs.getDouble(1) == 1);
assertTrue(rs.getBigDecimal(1).longValue() == 1);
assertEquals(rs.getString(1), "1");
Object tmpData = rs.getObject(1);
assertTrue(tmpData instanceof Long);
assertTrue(data == ((Long) tmpData).longValue());
ResultSetMetaData resultSetMetaData = rs.getMetaData();
assertNotNull(resultSetMetaData);
assertEquals(resultSetMetaData.getColumnType(1), Types.BIGINT);
assertEquals(rs.getLong(2), Long.MIN_VALUE);
assertEquals(rs.getLong(3), Long.MAX_VALUE);
assertTrue(!rs.next());
stmt2.close();
rs.close();
}
public void testSqlVariant() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #VARTEST (id int, data sql_variant)");
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #VARTEST (id, data) VALUES (?, ?)");
pstmt.setInt(1, 1);
pstmt.setString(2, "TEST STRING");
assertEquals("Insert 1 failed", pstmt.executeUpdate(), 1);
pstmt.setInt(1, 2);
pstmt.setInt(2, 255);
assertEquals("Insert 2 failed", pstmt.executeUpdate(), 1);
pstmt.setInt(1, 3);
pstmt.setBigDecimal(2, new BigDecimal("10.23"));
assertEquals("Insert 3 failed", pstmt.executeUpdate(), 1);
pstmt.setInt(1, 4);
byte bytes[] = {'X', 'X', 'X'};
pstmt.setBytes(2, bytes);
assertEquals("Insert 4 failed", pstmt.executeUpdate(), 1);
ResultSet rs = stmt.executeQuery("SELECT id, data FROM #VARTEST ORDER BY id");
assertNotNull(rs);
assertTrue(rs.next());
assertEquals("TEST STRING", rs.getString(2));
assertTrue(rs.next());
assertEquals(255, rs.getInt(2));
assertTrue(rs.next());
assertEquals("java.math.BigDecimal", rs.getObject(2).getClass().getName());
assertEquals("10.23", rs.getString(2));
assertTrue(rs.next());
assertEquals("585858", rs.getString(2));
stmt.close();
pstmt.close();
}
public void testUserFn() throws Exception {
dropFunction("f_varret");
Statement stmt = con.createStatement();
stmt.execute(
"CREATE FUNCTION f_varret(@data varchar(100)) RETURNS sql_variant AS\r\n" +
"BEGIN\r\n" +
"RETURN 'Test ' + @data\r\n" +
"END");
stmt.close();
CallableStatement cstmt = con.prepareCall("{?=call f_varret(?)}");
cstmt.registerOutParameter(1, java.sql.Types.OTHER);
cstmt.setString(2, "String");
cstmt.execute();
assertEquals("Test String", cstmt.getString(1));
cstmt.close();
dropFunction("f_varret");
}
public void testMetaData() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("create table #testrsmd (id int, data varchar(10), num decimal(10,2))");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("select * from #testrsmd where id = ?");
ResultSetMetaData rsmd = pstmt.getMetaData();
assertNotNull(rsmd);
assertEquals(3, rsmd.getColumnCount());
assertEquals("data", rsmd.getColumnName(2));
assertEquals(2, rsmd.getScale(3));
pstmt.close();
}
/**
* Test for bug [1042272] jTDS doesn't allow null value into Boolean.
*/
public void testNullBoolean() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("create table #testNullBoolean (id int, value bit)");
PreparedStatement pstmt = con.prepareStatement(
"insert into #testNullBoolean (id, value) values (?, ?)");
pstmt.setInt(1, 1);
pstmt.setNull(2, 16 /* Types.BOOLEAN */);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
ResultSet rs = stmt.executeQuery("select * from #testNullBoolean");
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertEquals(null, rs.getObject(2));
assertFalse(rs.next());
rs.close();
stmt.close();
}
/**
* Test column collations.
*/
public void testColumnCollations() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("create table #testColumnCollations (id int primary key, "
+ "cp437val varchar(255) collate SQL_Latin1_General_Cp437_CI_AS, "
+ "cp850val varchar(255) collate SQL_Latin1_General_Cp850_CI_AS, "
+ "ms874val varchar(255) collate Thai_CI_AS, "
+ "ms932val varchar(255) collate Japanese_CI_AS, "
+ "ms936val varchar(255) collate Chinese_PRC_CI_AS, "
+ "ms949val varchar(255) collate Korean_Wansung_CI_AS, "
+ "ms950val varchar(255) collate Chinese_Taiwan_Stroke_CI_AS, "
+ "cp1250val varchar(255) collate SQL_Romanian_Cp1250_CI_AS, "
+ "cp1252val varchar(255) collate SQL_Latin1_General_Cp1_CI_AS)");
ResultSet rs = stmt.executeQuery("select * from #testColumnCollations");
assertFalse(rs.next());
rs.close();
PreparedStatement pstmt = con.prepareStatement(
"insert into #testColumnCollations "
+ "(id, cp437val, cp850val, ms874val, ms932val, "
+ "ms936val, ms949val, ms950val, cp1250val, cp1252val) "
+ "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
// Test inserting and retrieving pure-ASCII values
pstmt.setInt(1, 1);
for (int i = 2; i <= 10; i++) {
pstmt.setString(i, "test");
}
assertEquals(1, pstmt.executeUpdate());
rs = stmt.executeQuery("select * from #testColumnCollations");
assertTrue(rs.next());
for (int i = 2; i <= 10; i++) {
assertEquals("test", rs.getString(i));
}
assertFalse(rs.next());
rs.close();
assertEquals(1, stmt.executeUpdate("delete from #testColumnCollations"));
// Test inserting and retrieving charset-specific values via PreparedStatement
String[] values = {
"123abc\u2591\u2592\u2593\u221a\u221e\u03b1",
"123abc\u00d5\u00f5\u2017\u00a5\u2591\u2592",
"123abc\u20ac\u2018\u2019\u0e10\u0e1e\u0e3a",
"123abc\uff67\uff68\uff9e\u60c6\u7210\ufa27",
"123abc\u6325\u8140\u79a9\u9f1e\u9f32\ufa29",
"123abc\uac4e\ub009\ubcde\u00de\u24d0\u30e5",
"123abc\ufe4f\u00d7\uff5e\u515e\u65b0\u7881",
"123abc\u20ac\u201a\u0103\u015e\u0162\u00f7",
"123abc\u20ac\u201e\u017d\u00fe\u02dc\u00b8"
};
for (int i = 2; i <= 10; i++) {
pstmt.setString(i, values[i - 2]);
}
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
rs = stmt.executeQuery("select * from #testColumnCollations");
assertTrue(rs.next());
for (int i = 2; i <= 10; i++) {
assertEquals("Column " + i + " doesn't match", values[i - 2], rs.getString(i));
}
assertFalse(rs.next());
rs.close();
pstmt.close();
stmt.close();
// Test inserting and retrieving charset-specific values via updateable ResultSet
stmt = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("select * from #testColumnCollations");
assertTrue(rs.next());
for (int i = 2; i <= 10; i++) {
rs.updateString(i, rs.getString(i) + "updated");
values[i - 2] = values[i - 2] + "updated";
}
rs.updateRow();
for (int i = 2; i <= 10; i++) {
assertEquals("Column " + i + " doesn't match", values[i - 2], rs.getString(i));
}
assertFalse(rs.next());
rs.close();
stmt.close();
}
/**
* Test for bug [981958] PreparedStatement doesn't work correctly
*/
public void testEncoding1251Test1() throws Exception {
String value = "\u0441\u043b\u043e\u0432\u043e"; // String in Cp1251 encoding
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #e1251t1 (data varchar(255) COLLATE Cyrillic_General_BIN)");
assertEquals(stmt.executeUpdate("INSERT INTO #e1251t1 (data) VALUES (N'" + value + "')"), 1);
stmt.close();
PreparedStatement pstmt = con.prepareStatement("SELECT data FROM #e1251t1 WHERE data = ?");
pstmt.setString(1, value);
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
//assertEquals(value, rs.getString(1));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for enhanced database metadata for SQL 2005.
* E.g. distinguish between varchar(max) and text.
* @throws Exception
*/
public void testSQL2005MetaData() throws Exception
{
Statement stmt = con.createStatement();
int dbVer = Integer.parseInt(con.getMetaData()
.getDatabaseProductVersion().
substring(0,2));
if (dbVer <= 8) {
// Not SQL 2005
return;
}
stmt.execute("CREATE TABLE #test (" +
"id int primary key, " +
"txt text, ntxt ntext, img image, " +
"vc varchar(max), nvc nvarchar(max), vb varbinary(max))");
ResultSet rs = con.getMetaData().getColumns("tempdb", null, "#test", "%");
assertNotNull(rs);
assertTrue(rs.next());
// Skip int col
assertTrue(rs.next());
// Should be text
assertEquals("text", rs.getString("TYPE_NAME"));
assertTrue(rs.next());
// Should be ntext
assertEquals("ntext", rs.getString("TYPE_NAME"));
assertTrue(rs.next());
// Should be image
assertEquals("image", rs.getString("TYPE_NAME"));
assertTrue(rs.next());
// Should be varchar(max)
assertEquals("varchar", rs.getString("TYPE_NAME"));
assertTrue(rs.next());
// Should be nvarchar(max)
assertEquals("nvarchar", rs.getString("TYPE_NAME"));
assertTrue(rs.next());
// Should be varbinary(max)
assertEquals("varbinary", rs.getString("TYPE_NAME"));
stmt.close();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(Tds8Test.class);
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/SavepointTest.java 0000644 0001750 0001750 00000036302 11316672660 026667 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.sql.*;
/**
* @version 1.0
*/
public class SavepointTest extends TestBase {
public SavepointTest(String name) {
super(name);
}
/**
* tests if rolling back to a savepoint restores the correct DB state
*/
public void testSavepoint1() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #savepoint1 (data int)");
stmt.close();
con.setAutoCommit(false);
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #savepoint1 (data) VALUES (?)");
pstmt.setInt(1, 1);
assertTrue(pstmt.executeUpdate() == 1);
Savepoint savepoint = con.setSavepoint();
assertNotNull(savepoint);
assertTrue(savepoint.getSavepointId() == 1);
try {
savepoint.getSavepointName();
assertTrue(false);
} catch (SQLException e) {
// Ignore, we should get this exception
}
pstmt.setInt(1, 2);
assertTrue(pstmt.executeUpdate() == 1);
pstmt.close();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT SUM(data) FROM #savepoint1");
assertTrue(rs.next());
assertTrue(rs.getInt(1) == 3);
assertTrue(!rs.next());
stmt.close();
rs.close();
con.rollback(savepoint);
con.commit();
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT SUM(data) FROM #savepoint1");
assertTrue(rs.next());
assertTrue(rs.getInt(1) == 1);
assertTrue(!rs.next());
stmt.close();
rs.close();
con.setAutoCommit(true);
}
/**
* rollback zu einem savepoint, dann test, ob weiter mit dem safepoint-objekt gearbeitet werden kann
*/
public void testSavepoint2() throws Exception {
String savepointName = "SAVEPOINT_1";
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #savepoint2 (data int)");
stmt.close();
con.setAutoCommit(false);
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #savepoint2 (data) VALUES (?)");
pstmt.setInt(1, 1);
assertTrue(pstmt.executeUpdate() == 1);
Savepoint savepoint = con.setSavepoint(savepointName);
assertNotNull(savepoint);
assertTrue(savepointName.equals(savepoint.getSavepointName()));
try {
savepoint.getSavepointId();
assertTrue(false);
} catch (SQLException e) {
// Ignore, we should get this exception
}
pstmt.setInt(1, 2);
assertTrue(pstmt.executeUpdate() == 1);
pstmt.close();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT SUM(data) FROM #savepoint2");
assertTrue(rs.next());
assertTrue(rs.getInt(1) == 3);
assertTrue(!rs.next());
stmt.close();
rs.close();
con.rollback(savepoint);
try {
con.rollback(null);
assertTrue(false);
} catch (SQLException e) {
// Ignore, we should get this exception
}
con.rollback(savepoint);
try {
con.releaseSavepoint(null);
assertTrue(false);
} catch (SQLException e) {
// Ignore, we should get this exception
}
con.releaseSavepoint(savepoint);
con.commit();
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT SUM(data) FROM #savepoint2");
assertTrue(rs.next());
assertTrue(rs.getInt(1) == 1);
assertTrue(!rs.next());
stmt.close();
rs.close();
con.setAutoCommit(true);
try {
con.setSavepoint();
assertTrue(false);
} catch (SQLException e) {
// Ignore, we should get this exception
}
try {
con.setSavepoint(savepointName);
assertTrue(false);
} catch (SQLException e) {
// Ignore, we should get this exception
}
}
public void testSavepoint3() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #savepoint3 (data int)");
stmt.close();
con.setAutoCommit(false);
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #savepoint3 (data) VALUES (?)");
pstmt.setInt(1, 1);
assertTrue(pstmt.executeUpdate() == 1);
Savepoint savepoint1 = con.setSavepoint();
assertNotNull(savepoint1);
assertTrue(savepoint1.getSavepointId() == 1);
pstmt.setInt(1, 2);
assertTrue(pstmt.executeUpdate() == 1);
Savepoint savepoint2 = con.setSavepoint();
assertNotNull(savepoint2);
assertTrue(savepoint2.getSavepointId() == 2);
pstmt.setInt(1, 3);
assertTrue(pstmt.executeUpdate() == 1);
Savepoint savepoint3 = con.setSavepoint();
assertNotNull(savepoint3);
assertTrue(savepoint3.getSavepointId() == 3);
pstmt.setInt(1, 4);
assertTrue(pstmt.executeUpdate() == 1);
pstmt.close();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT SUM(data) FROM #savepoint3");
assertTrue(rs.next());
assertTrue(rs.getInt(1) == 10);
assertTrue(!rs.next());
stmt.close();
rs.close();
con.releaseSavepoint(savepoint1);
try {
con.rollback(savepoint1);
assertTrue(false);
} catch (SQLException e) {
// Ignore, we should get this exception
}
try {
con.releaseSavepoint(savepoint1);
assertTrue(false);
} catch (SQLException e) {
// Ignore, we should get this exception
}
con.rollback(savepoint2);
con.rollback(savepoint2);
con.releaseSavepoint(savepoint2);
try {
con.rollback(savepoint3);
assertTrue(false);
} catch (SQLException e) {
// Ignore, we should get this exception
}
try {
con.releaseSavepoint(savepoint3);
assertTrue(false);
} catch (SQLException e) {
// Ignore, we should get this exception
}
con.commit();
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT SUM(data) FROM #savepoint3");
assertTrue(rs.next());
assertTrue(rs.getInt(1) == 3);
assertTrue(!rs.next());
stmt.close();
rs.close();
con.setAutoCommit(true);
}
/**
* Test to ensure savepoint ids restart at 1. Also ensures that the
* procedure cache is managed properly with savepoints.
*/
public void testSavepoint4() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #savepoint4 (data int)");
stmt.close();
con.setAutoCommit(false);
for (int i = 0; i < 3; i++) {
System.out.println("iteration: " + i);
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #savepoint4 (data) VALUES (?)");
pstmt.setInt(1, 1);
assertTrue(pstmt.executeUpdate() == 1);
Savepoint savepoint = con.setSavepoint();
assertNotNull(savepoint);
assertTrue(savepoint.getSavepointId() == 1);
try {
savepoint.getSavepointName();
assertTrue(false);
} catch (SQLException e) {
// Ignore, we should get this exception
}
pstmt.setInt(1, 2);
assertTrue(pstmt.executeUpdate() == 1);
pstmt.close();
pstmt = con.prepareStatement("SELECT SUM(data) FROM #savepoint4");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertTrue(rs.getInt(1) == 3);
assertTrue(!rs.next());
pstmt.close();
rs.close();
con.rollback(savepoint);
pstmt = con.prepareStatement("SELECT SUM(data) FROM #savepoint4");
rs = pstmt.executeQuery();
assertTrue(rs.next());
assertTrue(rs.getInt(1) == 1);
assertTrue(!rs.next());
pstmt.close();
rs.close();
con.rollback();
}
con.setAutoCommit(true);
}
/**
* Test to ensure savepoints can be created even when no statements have
* been issued.
*/
public void testSavepoint5() throws Exception {
con.setAutoCommit(false);
con.setSavepoint();
con.rollback();
con.setAutoCommit(true);
}
/**
* test for bug [2818256]
*
* ensure a savepoint is still valid after rollback
*/
public void testSavepoint6() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #savepoint6 (data int)");
stmt.close();
con.setAutoCommit(false);
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #savepoint6 (data) VALUES (?)");
pstmt.setInt(1, 1);
assertTrue(pstmt.executeUpdate() == 1);
Savepoint savepoint1 = con.setSavepoint();
assertNotNull(savepoint1);
assertTrue(savepoint1.getSavepointId() == 1);
pstmt.setInt(1, 2);
assertTrue(pstmt.executeUpdate() == 1);
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT SUM(data) FROM #savepoint6");
assertTrue(rs.next());
assertTrue(rs.getInt(1) == 3);
assertTrue(!rs.next());
stmt.close();
rs.close();
con.rollback(savepoint1);
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT SUM(data) FROM #savepoint6");
assertTrue(rs.next());
assertTrue(rs.getInt(1) == 1);
assertTrue(!rs.next());
stmt.close();
rs.close();
pstmt.setInt(1, 2);
assertTrue(pstmt.executeUpdate() == 1);
con.rollback(savepoint1);
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT SUM(data) FROM #savepoint6");
assertTrue(rs.next());
assertTrue(rs.getInt(1) == 1);
assertTrue(!rs.next());
stmt.close();
rs.close();
con.setAutoCommit(true);
}
/**
* roll back to one savepoint and ensure earlier savepoints are still valid
*/
public void testSavepoint7() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #savepoint7 (data int)");
stmt.close();
con.setAutoCommit(false);
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #savepoint7 (data) VALUES (?)");
pstmt.setInt(1, 1);
assertTrue(pstmt.executeUpdate() == 1);
Savepoint savepoint1 = con.setSavepoint();
assertNotNull(savepoint1);
assertTrue(savepoint1.getSavepointId() == 1);
pstmt.setInt(1, 2);
assertTrue(pstmt.executeUpdate() == 1);
Savepoint savepoint2 = con.setSavepoint();
assertNotNull(savepoint2);
assertTrue(savepoint2.getSavepointId() == 2);
pstmt.setInt(1, 3);
assertTrue(pstmt.executeUpdate() == 1);
Savepoint savepoint3 = con.setSavepoint();
assertNotNull(savepoint3);
assertTrue(savepoint3.getSavepointId() == 3);
pstmt.setInt(1, 4);
assertTrue(pstmt.executeUpdate() == 1);
pstmt.close();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT SUM(data) FROM #savepoint7");
assertTrue(rs.next());
assertTrue(rs.getInt(1) == 10);
assertTrue(!rs.next());
stmt.close();
rs.close();
con.rollback(savepoint3);
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT SUM(data) FROM #savepoint7");
assertTrue(rs.next());
assertTrue(rs.getInt(1) == 6);
assertTrue(!rs.next());
stmt.close();
rs.close();
con.rollback(savepoint1);
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT SUM(data) FROM #savepoint7");
assertTrue(rs.next());
assertTrue(rs.getInt(1) == 1);
assertTrue(!rs.next());
stmt.close();
rs.close();
con.setAutoCommit(true);
}
/**
* Test to ensure savepoints cannot be created in auto-commit mode
* (Bug [2021839]).
*/
public void testSavepoint8() {
try {
con.setSavepoint();
assertTrue(false);
} catch (SQLException e) {
// Ignore, we should get this exception
}
}
/**
* Test for bug [2021839], connection is rolled back instead of being
* committed if setSavepoint is the first operation.
*/
public void testSavepoint9() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #savepoint9 (data int)");
stmt.close();
con.setAutoCommit(false);
Savepoint sp = con.setSavepoint();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #savepoint9 (data) VALUES (?)");
pstmt.setInt(1, 1);
assertTrue(pstmt.executeUpdate() == 1);
pstmt.close();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT SUM(data) FROM #savepoint9");
assertTrue(rs.next());
assertTrue(rs.getInt(1) == 1);
assertTrue(!rs.next());
stmt.close();
rs.close();
con.commit();
con.rollback(); // this discovers bug [2021839]
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT SUM(data) FROM #savepoint9");
assertTrue(rs.next());
assertTrue("bug [2021839]",rs.getInt(1) == 1);
assertTrue(!rs.next());
stmt.close();
rs.close();
con.setAutoCommit(true);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(SavepointTest.class);
}
} libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/LOBTest.java 0000644 0001750 0001750 00000312734 11316672660 025341 0 ustar martin martin //jTDS JDBC Driver for Microsoft SQL Server and Sybase
//Copyright (C) 2004 The jTDS Project
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.io.*;
import java.sql.*;
import java.util.*;
//
// MJH - Changes for new jTDS version
// Amended many lines such as those in testBlobSetNull6
// where ResultSet variable rs was used when rs2 is actually required.
// Amazed old version did not fail also as rs was closed!
// Changed get / set UnicodeStream tests to align with standard.
//
/**
* @version $Id: LOBTest.java,v 1.27.2.1 2009/07/25 12:57:37 ickzon Exp $
*/
public class LOBTest extends TestBase {
private static final int LOB_LENGTH = 8000;
private static final byte[] blobData = new byte[LOB_LENGTH];
private static final byte[] newBlobData = new byte[LOB_LENGTH];
private static final String clobData;
private static final String newClobData;
static {
for (int i = 0; i < blobData.length; i++) {
blobData[i] = (byte) (Math.random() * 255);
newBlobData[i] = (byte) (Math.random() * 255);
}
StringBuffer data = new StringBuffer();
StringBuffer newData = new StringBuffer();
for (int i = 0; i < LOB_LENGTH; i++) {
data.append((char) (Math.random() * 58) + 32);
newData.append((char) (Math.random() * 58) + 32);
}
clobData = data.toString();
newClobData = newData.toString();
}
public LOBTest(String name) {
super(name);
}
/*************************************************************************
*************************************************************************
** BLOB TESTS **
*************************************************************************
*************************************************************************/
public void testBlobGet1() throws Exception {
byte[] data = getBlobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobget1 (data IMAGE)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobget1 (data) VALUES (?)");
// Test PreparedStatement.setBytes()
pstmt.setBytes(1, data);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobget1");
assertTrue(rs.next());
// Test ResultSet.getBytes()
assertTrue(Arrays.equals(data, rs.getBytes(1)));
// Test ResultSet.getBinaryStream()
InputStream is = rs.getBinaryStream(1);
byte[] isTmpData = new byte[data.length];
assertEquals(data.length, is.read(isTmpData));
assertEquals(-1, is.read());
assertTrue(Arrays.equals(data, isTmpData));
// Test ResultSet.getBlob()
Blob blob = rs.getBlob(1);
assertNotNull(blob);
// Test Blob.length()
assertEquals(blob.length(), data.length);
// Test Blob.getBytes(0, length); should fail
try {
blob.getBytes(0L, (int) blob.length());
fail("Blob.getBytes(0, length) should fail.");
} catch (SQLException ex) {
assertEquals("HY090", ex.getSQLState());
}
// Test Blob.getBytes()
byte[] tmpData2 = blob.getBytes(1L, (int) blob.length());
assertTrue(Arrays.equals(data, tmpData2));
// Test Blob.getBinaryStream()
InputStream is2 = blob.getBinaryStream();
compareInputStreams(new ByteArrayInputStream(data), is2);
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testBlobGet2() throws Exception {
byte[] data = getBlobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobget2 (data IMAGE)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobget2 (data) VALUES (?)");
// Test PreparedStatement.setBinaryStream()
pstmt.setBinaryStream(1, new ByteArrayInputStream(data), data.length);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobget2");
assertTrue(rs.next());
// Test ResultSet.getObject() - Blob
Object result = rs.getObject(1);
assertTrue(result instanceof Blob);
Blob blob = (Blob) result;
assertEquals(data.length, blob.length());
// Test Blob.getBytes()
assertTrue(Arrays.equals(data, blob.getBytes(1L, (int) blob.length())));
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testBlobSet1() throws Exception {
byte[] data = getBlobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobset1 (data IMAGE)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobset1 (data) VALUES (?)");
// Test PreparedStatement.setBinaryStream()
pstmt.setBinaryStream(1, new ByteArrayInputStream(data), data.length);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobset1");
assertTrue(rs.next());
// Test ResultSet.getBytes()
assertTrue(Arrays.equals(data, rs.getBytes(1)));
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testBlobSet2() throws Exception {
byte[] data = getBlobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobset2 (data IMAGE)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobset2 (data) VALUES (?)");
// Test PreparedStatement.setBytes()
pstmt.setBytes(1, data);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobset2");
assertTrue(rs.next());
Blob blob = rs.getBlob(1);
data = getNewBlobTestData();
// Test Blob.setBytes()
blob.setBytes(1, data);
assertTrue(Arrays.equals(data, blob.getBytes(1L, (int) blob.length())));
assertFalse(rs.next());
PreparedStatement pstmt2 = con.prepareStatement("UPDATE #blobset2 SET data = ?");
// Test PreparedStatement.setBlob()
pstmt2.setBlob(1, blob);
assertEquals(1, pstmt2.executeUpdate());
pstmt2.close();
stmt2.close();
rs.close();
Statement stmt3 = con.createStatement();
ResultSet rs2 = stmt3.executeQuery("SELECT data FROM #blobset2");
assertTrue(rs2.next());
// Test ResultSet.getBytes()
assertTrue(Arrays.equals(data, rs2.getBytes(1)));
assertFalse(rs2.next());
stmt3.close();
rs2.close();
}
public void testBlobSet3() throws Exception {
byte[] data = getBlobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobset3 (data IMAGE)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobset3 (data) VALUES (?)");
// Test PreparedStatement.setObject(int,byte[])
pstmt.setObject(1, data);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobset3");
assertTrue(rs.next());
// Test ResultSet.getBytes()
assertTrue(Arrays.equals(data, rs.getBytes(1)));
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testBlobSet4() throws Exception {
byte[] data = getBlobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobset4 (data IMAGE)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobset4 (data) VALUES (?)");
// Test PreparedStatement.setBytes()
pstmt.setBytes(1, data);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobset4");
assertTrue(rs.next());
Blob blob = rs.getBlob(1);
data = getNewBlobTestData();
// Test Blob.setBytes()
blob.setBytes(1, data);
assertTrue(Arrays.equals(data, blob.getBytes(1L, (int) blob.length())));
assertFalse(rs.next());
PreparedStatement pstmt2 = con.prepareStatement("UPDATE #blobset4 SET data = ?");
// Test PreparedStatement.setObject(int,Blob)
pstmt2.setObject(1, blob);
assertEquals(1, pstmt2.executeUpdate());
pstmt2.close();
stmt2.close();
rs.close();
Statement stmt3 = con.createStatement();
ResultSet rs2 = stmt3.executeQuery("SELECT data FROM #blobset4");
assertTrue(rs2.next());
// Test ResultSet.getBytes()
assertTrue(Arrays.equals(data, rs2.getBytes(1)));
assertFalse(rs2.next());
stmt3.close();
rs2.close();
}
public void testBlobSet5() throws Exception {
byte[] data = getBlobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobset5 (data IMAGE)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobset5 (data) VALUES (?)");
// Test PreparedStatement.setObject(int,byte[],int)
pstmt.setObject(1, data, Types.BINARY);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobset5");
assertTrue(rs.next());
// Test ResultSet.getBytes()
assertTrue(Arrays.equals(data, rs.getBytes(1)));
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testBlobSet6() throws Exception {
byte[] data = getBlobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobset6 (data IMAGE)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobset6 (data) VALUES (?)");
// Test PreparedStatement.setObject(int,byte[],int)
pstmt.setObject(1, data, Types.VARBINARY);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobset6");
assertTrue(rs.next());
// Test ResultSet.getBytes()
assertTrue(Arrays.equals(data, rs.getBytes(1)));
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testBlobSet7() throws Exception {
byte[] data = getBlobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobset7 (data IMAGE)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobset7 (data) VALUES (?)");
// Test PreparedStatement.setBytes()
pstmt.setBytes(1, data);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobset7");
assertTrue(rs.next());
Blob blob = rs.getBlob(1);
data = getNewBlobTestData();
// Test Blob.setBytes()
blob.setBytes(1, data);
assertTrue(Arrays.equals(data, blob.getBytes(1L, (int) blob.length())));
assertFalse(rs.next());
PreparedStatement pstmt2 = con.prepareStatement("UPDATE #blobset7 SET data = ?");
// Test PreparedStatement.setObject(int,Blob,int)
pstmt2.setObject(1, blob, Types.BLOB);
assertEquals(1, pstmt2.executeUpdate());
pstmt2.close();
stmt2.close();
rs.close();
Statement stmt3 = con.createStatement();
ResultSet rs2 = stmt3.executeQuery("SELECT data FROM #blobset7");
assertTrue(rs2.next());
// Test ResultSet.getBytes()
assertTrue(Arrays.equals(data, rs2.getBytes(1)));
assertFalse(rs2.next());
stmt3.close();
rs2.close();
}
/**
* Test inserting from an InputStream that doesn't fill the
* buffer on read().
*
* For bug #1008816 - "More data in stream ..." error when inserting an image.
*
* @throws Exception if an error condition occurs
*/
public void testBlobSet8() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobset8 (data IMAGE)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobset8 (data) VALUES (?)");
// Test PreparedStatement.setBinaryStream()
pstmt.setBinaryStream(1, new RealInputStream(), RealInputStream.LENGTH);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobset8");
assertTrue(rs.next());
// Test ResultSet.getBinaryStream()
compareInputStreams(new RealInputStream(), rs.getBinaryStream(1));
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testBlobUpdate1() throws Exception {
byte[] data = getBlobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobupdate1 (id NUMERIC IDENTITY, data IMAGE, "
+ "CONSTRAINT pk_blobupdate1 PRIMARY KEY CLUSTERED (id))");
stmt.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, data FROM #blobupdate1");
rs.moveToInsertRow();
// Test ResultSet.updateBytes()
rs.updateBytes(2, data);
rs.insertRow();
stmt.close();
rs.close();
Statement stmt2 = con.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT data FROM #blobupdate1");
assertTrue(rs2.next());
// Test ResultSet.getBytes()
assertTrue(Arrays.equals(data, rs2.getBytes(1)));
assertFalse(rs2.next());
stmt2.close();
rs2.close();
}
public void testBlobUpdate2() throws Exception {
byte[] data = getBlobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobupdate2 (id NUMERIC IDENTITY, data IMAGE, "
+ "CONSTRAINT pk_blobupdate2 PRIMARY KEY CLUSTERED (id))");
stmt.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, data FROM #blobupdate2");
rs.moveToInsertRow();
// Test ResultSet.updateBinaryStream()
rs.updateBinaryStream(2, new ByteArrayInputStream(data), data.length);
rs.insertRow();
stmt.close();
rs.close();
Statement stmt2 = con.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT data FROM #blobupdate2");
assertTrue(rs2.next());
// Test ResultSet.getBytes()
assertTrue(Arrays.equals(data, rs2.getBytes(1)));
assertFalse(rs2.next());
stmt2.close();
rs2.close();
}
public void testBlobUpdate3() throws Exception {
byte[] data = getBlobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobupdate3 (id NUMERIC IDENTITY, data IMAGE, "
+ "CONSTRAINT pk_blobupdate3 PRIMARY KEY CLUSTERED (id))");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobupdate3 (data) VALUES (?)");
// Test PreparedStatement.setBytes()
pstmt.setBytes(1, data);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobupdate3");
assertTrue(rs.next());
Blob blob = rs.getBlob(1);
data = getNewBlobTestData();
// Test Blob.setBytes()
blob.setBytes(1, data);
assertTrue(Arrays.equals(data, blob.getBytes(1L, (int) blob.length())));
assertFalse(rs.next());
Statement stmt3 = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs2 = stmt3.executeQuery("SELECT id, data FROM #blobupdate3");
assertTrue(rs2.next());
// Test ResultSet.updateBlob()
rs2.updateBlob(2, blob);
rs2.updateRow();
assertFalse(rs2.next());
stmt2.close();
rs.close();
stmt3.close();
rs2.close();
Statement stmt4 = con.createStatement();
ResultSet rs3 = stmt4.executeQuery("SELECT data FROM #blobupdate3");
assertTrue(rs3.next());
// Test ResultSet.getBytes()
assertTrue(Arrays.equals(data, rs3.getBytes(1)));
assertFalse(rs3.next());
stmt4.close();
rs3.close();
}
public void testBlobUpdate4() throws Exception {
byte[] data = getBlobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobupdate4 (id NUMERIC IDENTITY, data IMAGE, "
+ "CONSTRAINT pk_blobupdate4 PRIMARY KEY CLUSTERED (id))");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobupdate4 (data) VALUES (?)");
// Test PreparedStatement.setBytes()
pstmt.setBytes(1, data);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobupdate4");
assertTrue(rs.next());
Blob blob = rs.getBlob(1);
data = getNewBlobTestData();
// Test Blob.setBytes()
blob.setBytes(1, data);
assertTrue(Arrays.equals(data, blob.getBytes(1L, (int) blob.length())));
assertFalse(rs.next());
Statement stmt3 = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs2 = stmt3.executeQuery("SELECT id, data FROM #blobupdate4");
assertTrue(rs2.next());
// Test ResultSet.updateBlob()
rs2.updateObject(2, blob);
rs2.updateRow();
assertFalse(rs2.next());
stmt2.close();
rs.close();
stmt3.close();
rs2.close();
Statement stmt4 = con.createStatement();
ResultSet rs3 = stmt4.executeQuery("SELECT data FROM #blobupdate4");
assertTrue(rs3.next());
// Test ResultSet.getBytes()
assertTrue(Arrays.equals(data, rs3.getBytes(1)));
assertFalse(rs3.next());
stmt4.close();
rs3.close();
}
/**
* Test Long blob manipulation including updates to the middle of the
* Blob.
*/
public void testBlobUpdate5() throws Exception {
byte[] data = new byte[100000];
for (int i = 0; i < data.length; i++) {
data[i] = (byte)('A'+i%10);
}
//
// Construct a blob
//
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT 0x00");
assertNotNull(rs);
assertTrue(rs.next());
Blob blob = rs.getBlob(1);
blob.setBytes(1, data);
byte[] tmp = blob.getBytes(1, (int)blob.length());
assertTrue(compare(data, tmp));
blob.setBytes(1, data);
tmp = blob.getBytes(1, (int)blob.length());
assertTrue(compare(data, tmp));
data[100] = 'a';
data[101] = 'b';
blob.setBytes(101, data, 100, 2);
tmp = blob.getBytes(1, (int)blob.length());
assertTrue(compare(data, tmp));
InputStream is = blob.getBinaryStream();
tmp = new byte[data.length];
int b;
int p = 0;
while ((b = is.read()) >= 0) {
tmp[p++] = (byte)b;
}
is.close();
assertTrue(compare(data, tmp));
tmp = blob.getBytes(101, 2);
assertTrue(compare(new byte[]{'a','b'}, tmp));
blob = rs.getBlob(1);
OutputStream os = blob.setBinaryStream(1);
for (int i = 0; i < data.length; i++) {
os.write(('A'+i%10));
}
os.close();
os = blob.setBinaryStream(101);
os.write('a');
os.write('b');
os.close();
tmp = blob.getBytes(1, (int)blob.length());
assertTrue(compare(data, tmp));
tmp = new byte[5000];
for (int i = 0; i < 5000; i++) {
tmp[i] = (byte)(0x80 + (i % 10));
}
blob.setBytes(100000-5000, tmp);
assertTrue(compare(tmp, blob.getBytes(100000-5000, 5000)));
assertEquals(100000L, blob.length());
assertEquals(100000-5000, blob.position(tmp, 100000-5000));
Blob blob2 = rs.getBlob(1);
blob2.setBytes(1, tmp);
assertEquals(100000-5000, blob.position(blob2, 1));
assertEquals(101, blob.position(new byte[]{'a','b'}, 1));
blob.truncate(10);
assertEquals(10L, blob.length());
tmp = new byte[10];
System.arraycopy(data, 0, tmp, 0, 10);
assertTrue(compare(tmp, blob.getBytes(1, (int)blob.length())));
}
public void testBlobSetNull1() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobsetnull1 (data IMAGE NULL)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobsetnull1 (data) VALUES (?)");
// Test PreparedStatement.setBinaryStream()
pstmt.setBinaryStream(1, null, 0);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobsetnull1");
assertTrue(rs.next());
// Test ResultSet.getBinaryStream()
assertNull(rs.getBinaryStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getBlob()
assertNull(rs.getBlob(1));
assertTrue(rs.wasNull());
// Test ResultSet.getBytes()
assertNull(rs.getBytes(1));
assertTrue(rs.wasNull());
// Test ResultSet.getObject()
assertNull(rs.getObject(1));
assertTrue(rs.wasNull());
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testBlobSetNull2() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobsetnull2 (data IMAGE NULL)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobsetnull2 (data) VALUES (?)");
// Test PreparedStatement.setBlob()
pstmt.setBlob(1, (Blob)null);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobsetnull2");
assertTrue(rs.next());
// Test ResultSet.getBinaryStream()
assertNull(rs.getBinaryStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getBlob()
assertNull(rs.getBlob(1));
assertTrue(rs.wasNull());
// Test ResultSet.getBytes()
assertNull(rs.getBytes(1));
assertTrue(rs.wasNull());
// Test ResultSet.getObject()
assertNull(rs.getObject(1));
assertTrue(rs.wasNull());
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testBlobSetNull3() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobsetnull3 (data IMAGE NULL)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobsetnull3 (data) VALUES (?)");
// Test PreparedStatement.setBytes()
pstmt.setBytes(1, null);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobsetnull3");
assertTrue(rs.next());
// Test ResultSet.getBinaryStream()
assertNull(rs.getBinaryStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getBlob()
assertNull(rs.getBlob(1));
assertTrue(rs.wasNull());
// Test ResultSet.getBytes()
assertNull(rs.getBytes(1));
assertTrue(rs.wasNull());
// Test ResultSet.getObject()
assertNull(rs.getObject(1));
assertTrue(rs.wasNull());
assertFalse(rs.next());
stmt2.close();
rs.close();
}
/**
* Test for bug [985956] Cannot setObject(null) on image.
*/
public void testBlobSetNull4() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobsetnull4 (data IMAGE NULL)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobsetnull4 (data) VALUES (?)");
// Test PreparedStatement.setObject(int,Object)
pstmt.setObject(1, null);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobsetnull4");
assertTrue(rs.next());
// Test ResultSet.getBinaryStream()
assertNull(rs.getBinaryStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getBlob()
assertNull(rs.getBlob(1));
assertTrue(rs.wasNull());
// Test ResultSet.getBytes()
assertNull(rs.getBytes(1));
assertTrue(rs.wasNull());
// Test ResultSet.getObject()
assertNull(rs.getObject(1));
assertTrue(rs.wasNull());
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testBlobSetNull5() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobsetnull5 (data IMAGE NULL)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobsetnull5 (data) VALUES (?)");
// Test PreparedStatement.setObject(int,Object,int)
pstmt.setObject(1, null, Types.BLOB);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobsetnull5");
assertTrue(rs.next());
// Test ResultSet.getBinaryStream()
assertNull(rs.getBinaryStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getBlob()
assertNull(rs.getBlob(1));
assertTrue(rs.wasNull());
// Test ResultSet.getBytes()
assertNull(rs.getBytes(1));
assertTrue(rs.wasNull());
// Test ResultSet.getObject()
assertNull(rs.getObject(1));
assertTrue(rs.wasNull());
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testBlobSetNull6() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobsetnull6 (data IMAGE NULL)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobsetnull6 (data) VALUES (?)");
// Test PreparedStatement.setNull()
pstmt.setNull(1, Types.BLOB);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobsetnull6");
assertTrue(rs.next());
// Test ResultSet.getBinaryStream()
assertNull(rs.getBinaryStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getBlob()
assertNull(rs.getBlob(1));
assertTrue(rs.wasNull());
// Test ResultSet.getBytes()
assertNull(rs.getBytes(1));
assertTrue(rs.wasNull());
// Test ResultSet.getObject()
assertNull(rs.getObject(1));
assertTrue(rs.wasNull());
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testBlobSetNull7() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobsetnull7 (id NUMERIC IDENTITY, data IMAGE NULL, "
+ "CONSTRAINT pk_blobsetnull7 PRIMARY KEY CLUSTERED (id))");
stmt.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, data FROM #blobsetnull7");
rs.moveToInsertRow();
// Test ResultSet.updateBinaryStream()
rs.updateBinaryStream(2, null, 0);
rs.insertRow();
stmt.close();
rs.close();
Statement stmt2 = con.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT data FROM #blobsetnull7");
assertTrue(rs2.next());
// Test ResultSet.getBinaryStream()
assertNull(rs2.getBinaryStream(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getBlob()
assertNull(rs2.getBlob(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getBytes()
assertNull(rs2.getBytes(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getObject()
assertNull(rs2.getObject(1));
assertTrue(rs2.wasNull());
assertFalse(rs2.next());
stmt2.close();
rs2.close();
}
public void testBlobSetNull8() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobsetnull8 (id NUMERIC IDENTITY, data IMAGE NULL, "
+ "CONSTRAINT pk_blobsetnull8 PRIMARY KEY CLUSTERED (id))");
stmt.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, data FROM #blobsetnull8");
rs.moveToInsertRow();
// Test ResultSet.updateBlob()
rs.updateBlob(2, (Blob)null);
rs.insertRow();
stmt.close();
rs.close();
Statement stmt2 = con.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT data FROM #blobsetnull8");
assertTrue(rs2.next());
// Test ResultSet.getBinaryStream()
assertNull(rs2.getBinaryStream(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getBlob()
assertNull(rs2.getBlob(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getBytes()
assertNull(rs2.getBytes(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getObject()
assertNull(rs2.getObject(1));
assertTrue(rs2.wasNull());
assertFalse(rs2.next());
stmt2.close();
rs2.close();
}
public void testBlobSetNull9() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobsetnull9 (id NUMERIC IDENTITY, data IMAGE NULL, "
+ "CONSTRAINT pk_blobsetnull9 PRIMARY KEY CLUSTERED (id))");
stmt.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, data FROM #blobsetnull9");
rs.moveToInsertRow();
// Test ResultSet.updateBytes()
rs.updateBytes(2, null);
rs.insertRow();
stmt.close();
rs.close();
Statement stmt2 = con.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT data FROM #blobsetnull9");
assertTrue(rs2.next());
// Test ResultSet.getBinaryStream()
assertNull(rs2.getBinaryStream(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getBlob()
assertNull(rs2.getBlob(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getBytes()
assertNull(rs2.getBytes(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getObject()
assertNull(rs2.getObject(1));
assertTrue(rs2.wasNull());
assertFalse(rs2.next());
stmt2.close();
rs2.close();
}
public void testBlobSetNull10() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobsetnull10 (id NUMERIC IDENTITY, data IMAGE NULL, "
+ "CONSTRAINT pk_blobsetnull10 PRIMARY KEY CLUSTERED (id))");
stmt.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, data FROM #blobsetnull10");
rs.moveToInsertRow();
// Test ResultSet.updateObject()
rs.updateObject(2, null);
rs.insertRow();
stmt.close();
rs.close();
Statement stmt2 = con.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT data FROM #blobsetnull10");
assertTrue(rs2.next());
// Test ResultSet.getBinaryStream()
assertNull(rs2.getBinaryStream(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getBlob()
assertNull(rs2.getBlob(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getBytes()
assertNull(rs2.getBytes(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getObject()
assertNull(rs2.getObject(1));
assertTrue(rs2.wasNull());
assertFalse(rs2.next());
stmt2.close();
rs2.close();
}
public void testBlobSetNull11() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobsetnull11 (id NUMERIC IDENTITY, data IMAGE NULL, "
+ "CONSTRAINT pk_blobsetnull11 PRIMARY KEY CLUSTERED (id))");
stmt.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, data FROM #blobsetnull11");
rs.moveToInsertRow();
// Test ResultSet.updateNull()
rs.updateNull(2);
rs.insertRow();
stmt.close();
rs.close();
Statement stmt2 = con.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT data FROM #blobsetnull11");
assertTrue(rs2.next());
// Test ResultSet.getBinaryStream()
assertNull(rs2.getBinaryStream(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getBlob()
assertNull(rs2.getBlob(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getBytes()
assertNull(rs2.getBytes(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getObject()
assertNull(rs2.getObject(1));
assertTrue(rs2.wasNull());
assertFalse(rs2.next());
stmt2.close();
rs2.close();
}
/**
* Test for bug [989399] blob.getBytes() from 0.
*/
public void testBlobGetBytes1() throws Exception {
byte[] data = getBlobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobgetbytes1 (data IMAGE)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobgetbytes1 (data) VALUES (?)");
// Test PreparedStatement.setBytes()
pstmt.setBytes(1, data);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobgetbytes1");
assertTrue(rs.next());
// Test ResultSet.getBlob()
Blob blob = rs.getBlob(1);
assertNotNull(blob);
// Test Blob.getBytes()
assertTrue(Arrays.equals(data, blob.getBytes(1L, (int) blob.length())));
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testBlobGetBytes2() throws Exception {
byte[] data = getBlobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobgetbytes2 (data IMAGE)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobgetbytes2 (data) VALUES (?)");
// Test PreparedStatement.setBytes()
pstmt.setBytes(1, data);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobgetbytes2");
assertTrue(rs.next());
// Test ResultSet.getBlob()
Blob blob = rs.getBlob(1);
assertNotNull(blob);
byte[] tmpData = new byte[data.length / 2];
System.arraycopy(data, 0, tmpData, 0, tmpData.length);
// Test Blob.getBytes()
assertTrue(Arrays.equals(tmpData, blob.getBytes(1L, tmpData.length)));
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testBlobGetBytes3() throws Exception {
byte[] data = getBlobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobgetbytes3 (data IMAGE)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobgetbytes3 (data) VALUES (?)");
// Test PreparedStatement.setBytes()
pstmt.setBytes(1, data);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobgetbytes3");
assertTrue(rs.next());
// Test ResultSet.getBlob()
Blob blob = rs.getBlob(1);
assertNotNull(blob);
byte[] tmpData = new byte[data.length / 2];
// Offset data copy by 1
System.arraycopy(data, 1, tmpData, 0, tmpData.length);
// Test Blob.getBytes()
assertTrue(Arrays.equals(tmpData, blob.getBytes(2L, tmpData.length)));
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testBlobLength1() throws Exception {
byte[] data = getBlobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #bloblength1 (data IMAGE)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #bloblength1 (data) VALUES (?)");
// Test PreparedStatement.setBytes()
pstmt.setBytes(1, data);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #bloblength1");
assertTrue(rs.next());
// Test ResultSet.getBlob()
Blob blob = rs.getBlob(1);
assertNotNull(blob);
// Test Blob.length()
assertEquals(data.length, blob.length());
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testBlobTruncate1() throws Exception {
byte[] data = getBlobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #blobtruncate1 (data IMAGE)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #blobtruncate1 (data) VALUES (?)");
// Test PreparedStatement.setBytes()
pstmt.setBytes(1, data);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #blobtruncate1");
assertTrue(rs.next());
// Test ResultSet.getBlob()
Blob blob = rs.getBlob(1);
assertNotNull(blob);
byte[] tmpData = new byte[data.length / 2];
System.arraycopy(data, 0, tmpData, 0, tmpData.length);
// Test Blob.truncate()
blob.truncate(tmpData.length);
assertEquals(tmpData.length, blob.length());
// Test Blob.getBytes()
assertTrue(Arrays.equals(tmpData, blob.getBytes(1L, (int) blob.length())));
assertFalse(rs.next());
stmt2.close();
rs.close();
}
/**
* Test for bug [1062395] Empty (but not null) blobs should return byte[0].
*/
public void testBlobEmpty() throws Exception {
Statement stmt = con.createStatement();
assertEquals(0,
stmt.executeUpdate("CREATE TABLE #blobEmpty (data IMAGE)"));
assertEquals(1,
stmt.executeUpdate("INSERT INTO #blobEmpty (data) values ('')"));
ResultSet rs = stmt.executeQuery("SELECT * FROM #blobEmpty");
assertTrue(rs.next());
Blob blob = rs.getBlob(1);
assertEquals(0, blob.length());
assertEquals(0, blob.getBytes(1, 0).length);
rs.close();
stmt.close();
}
/*************************************************************************
*************************************************************************
** CLOB TESTS **
*************************************************************************
*************************************************************************/
public void testClobGet1() throws Exception {
String data = getClobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobget1 (data TEXT)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobget1 (data) VALUES (?)");
pstmt.setString(1, data);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobget1");
assertTrue(rs.next());
// Test ResultSet.getString()
assertTrue(data.equals(rs.getString(1)));
// Test ResultSet.getAsciiStream()
InputStream is = rs.getAsciiStream(1);
compareInputStreams(new ByteArrayInputStream(data.getBytes("ASCII")), is);
// Test ResultSet.getUnicodeStream(()
InputStream is2 = rs.getUnicodeStream(1);
compareInputStreams(new ByteArrayInputStream(data.getBytes("UTF-16BE")), is2);
// Test ResultSet.getCharacterStream()
Reader rdr = rs.getCharacterStream(1);
compareReaders(new StringReader(data), rdr);
// Test ResultSet.getClob()
Clob clob = rs.getClob(1);
assertNotNull(clob);
// Test Clob.length()
assertEquals(clob.length(), data.length());
// Test Clob.getSubString(0, length); should fail
try {
clob.getSubString(0L, (int) clob.length());
fail("Clob.getSubString(0, length) should fail.");
} catch (SQLException ex) {
assertEquals("HY090", ex.getSQLState());
}
// Test Clob.getSubString()
assertTrue(data.equals(clob.getSubString(1L, (int) clob.length())));
// Test Clob.getAsciiStream()
InputStream is3 = clob.getAsciiStream();
compareInputStreams(new ByteArrayInputStream(data.getBytes("ASCII")), is3);
// Test Clob.getCharacterStream()
Reader rdr2 = rs.getCharacterStream(1);
compareReaders(new StringReader(data), rdr2);
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testClobGet2() throws Exception {
String data = getClobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobget2 (data TEXT)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobget2 (data) VALUES (?)");
// Test PreparedStatement.setCharacterStream()
pstmt.setCharacterStream(1, new StringReader(data), data.length());
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobget2");
assertTrue(rs.next());
// Test ResultSet.getObject() - Clob
Object result = rs.getObject(1);
assertTrue(result instanceof Clob);
Clob clob = (Clob) result;
assertEquals(data.length(), clob.length());
// Test Clob.getSubString()
assertTrue(data.equals(clob.getSubString(1L, (int) clob.length())));
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testClobSet1() throws Exception {
String data = getClobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobset1 (data TEXT)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobset1 (data) VALUES (?)");
// Test PreparedStatement.setAsciiStream()
pstmt.setAsciiStream(1, new ByteArrayInputStream(data.getBytes("ASCII")), data.length());
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobset1");
assertTrue(rs.next());
// Test ResultSet.getString()
assertTrue(data.equals(rs.getString(1)));
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testClobSet2() throws Exception {
String data = getClobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobset2 (data TEXT)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobset2 (data) VALUES (?)");
// Test PreparedStatement.setCharacterStream()
pstmt.setCharacterStream(1, new StringReader(data), data.length());
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobset2");
assertTrue(rs.next());
// Test ResultSet.getString()
assertTrue(data.equals(rs.getString(1)));
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testClobSet3() throws Exception {
String data = getClobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobset3 (data TEXT)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobset3 (data) VALUES (?)");
// Test PreparedStatement.setString()
pstmt.setString(1, data);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobset3");
assertTrue(rs.next());
Clob clob = rs.getClob(1);
data = getNewClobTestData();
// Test Clob.setBytes()
clob.setString(1, data);
assertTrue(data.equals(clob.getSubString(1L, (int) clob.length())));
assertFalse(rs.next());
PreparedStatement pstmt2 = con.prepareStatement("UPDATE #clobset3 SET data = ?");
// Test PreparedStatement.setClob()
pstmt2.setClob(1, clob);
assertEquals(1, pstmt2.executeUpdate());
pstmt2.close();
stmt2.close();
rs.close();
Statement stmt3 = con.createStatement();
ResultSet rs2 = stmt3.executeQuery("SELECT data FROM #clobset3");
assertTrue(rs2.next());
// Test ResultSet.getString()
assertTrue(data.equals(rs2.getString(1)));
assertFalse(rs2.next());
stmt3.close();
rs2.close();
}
public void testClobSet4() throws Exception {
String data = getClobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobset4 (data TEXT)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobset4 (data) VALUES (?)");
// Test PreparedStatement.setUnicodeStream()
pstmt.setUnicodeStream(1, new ByteArrayInputStream(data.getBytes("UTF-16BE")), data.length() * 2);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobset4");
assertTrue(rs.next());
// Test ResultSet.getString()
assertTrue(data.equals(rs.getString(1)));
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testClobSet5() throws Exception {
String data = getClobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobset5 (data TEXT)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobset5 (data) VALUES (?)");
// Test PreparedStatement.setObject(int,String)
pstmt.setObject(1, data);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobset5");
assertTrue(rs.next());
// Test ResultSet.getString()
assertTrue(data.equals(rs.getString(1)));
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testClobSet6() throws Exception {
String data = getClobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobset6 (data TEXT)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobset6 (data) VALUES (?)");
// Test PreparedStatement.setString()
pstmt.setString(1, data);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobset6");
assertTrue(rs.next());
Clob clob = rs.getClob(1);
data = getNewClobTestData();
// Test Clob.setBytes()
clob.setString(1, data);
assertTrue(data.equals(clob.getSubString(1L, (int) clob.length())));
assertFalse(rs.next());
PreparedStatement pstmt2 = con.prepareStatement("UPDATE #clobset6 SET data = ?");
// Test PreparedStatement.setObject(int,Clob)
pstmt2.setObject(1, clob);
assertEquals(1, pstmt2.executeUpdate());
pstmt2.close();
stmt2.close();
rs.close();
Statement stmt3 = con.createStatement();
ResultSet rs2 = stmt3.executeQuery("SELECT data FROM #clobset6");
assertTrue(rs2.next());
// Test ResultSet.getString()
assertTrue(data.equals(rs2.getString(1)));
assertFalse(rs2.next());
stmt3.close();
rs2.close();
}
public void testClobSet7() throws Exception {
String data = getClobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobset7 (data TEXT)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobset7 (data) VALUES (?)");
// Test PreparedStatement.setObject(int,String,int)
pstmt.setObject(1, data, Types.LONGVARCHAR);
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobset7");
assertTrue(rs.next());
// Test ResultSet.getString()
assertTrue(data.equals(rs.getString(1)));
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testClobSet8() throws Exception {
String data = getClobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobset8 (data TEXT)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobset8 (data) VALUES (?)");
// Test PreparedStatement.setString()
pstmt.setString(1, data);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobset8");
assertTrue(rs.next());
Clob clob = rs.getClob(1);
data = getNewClobTestData();
// Test Clob.setBytes()
clob.setString(1, data);
assertTrue(data.equals(clob.getSubString(1L, (int) clob.length())));
assertFalse(rs.next());
PreparedStatement pstmt2 = con.prepareStatement("UPDATE #clobset8 SET data = ?");
// Test PreparedStatement.setObject(int,Clob,int)
pstmt2.setObject(1, clob, Types.CLOB);
assertEquals(1, pstmt2.executeUpdate());
pstmt2.close();
stmt2.close();
rs.close();
Statement stmt3 = con.createStatement();
ResultSet rs2 = stmt3.executeQuery("SELECT data FROM #clobset8");
assertTrue(rs2.next());
// Test ResultSet.getString()
assertTrue(data.equals(rs2.getString(1)));
assertFalse(rs2.next());
stmt3.close();
rs2.close();
}
public void testClobUpdate1() throws Exception {
String data = getClobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobupdate1 (id NUMERIC IDENTITY, data TEXT, "
+ "CONSTRAINT pk_clobupdate1 PRIMARY KEY CLUSTERED (id))");
stmt.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, data FROM #clobupdate1");
rs.moveToInsertRow();
// Test ResultSet.updateString()
rs.updateString(2, data);
rs.insertRow();
stmt.close();
rs.close();
Statement stmt2 = con.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT data FROM #clobupdate1");
assertTrue(rs2.next());
// Test ResultSet.getString()
assertTrue(data.equals(rs2.getString(1)));
assertFalse(rs2.next());
stmt2.close();
rs2.close();
}
public void testClobUpdate2() throws Exception {
String data = getClobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobupdate2 (id NUMERIC IDENTITY, data TEXT, "
+ "CONSTRAINT pk_clobupdate2 PRIMARY KEY CLUSTERED (id))");
stmt.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, data FROM #clobupdate2");
rs.moveToInsertRow();
// Test ResultSet.updateAsciiStream()
rs.updateAsciiStream(2, new ByteArrayInputStream(data.getBytes("ASCII")), data.length());
rs.insertRow();
stmt.close();
rs.close();
Statement stmt2 = con.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT data FROM #clobupdate2");
assertTrue(rs2.next());
// Test ResultSet.getString()
assertTrue(data.equals(rs2.getString(1)));
assertFalse(rs2.next());
stmt2.close();
rs2.close();
}
public void testClobUpdate3() throws Exception {
String data = getClobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobupdate3 (id NUMERIC IDENTITY, data TEXT, "
+ "CONSTRAINT pk_clobupdate3 PRIMARY KEY CLUSTERED (id))");
stmt.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, data FROM #clobupdate3");
rs.moveToInsertRow();
// Test ResultSet.updateCharacterStream()
rs.updateCharacterStream(2, new StringReader(data), data.length());
rs.insertRow();
stmt.close();
rs.close();
Statement stmt2 = con.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT data FROM #clobupdate3");
assertTrue(rs2.next());
// Test ResultSet.getString()
assertTrue(data.equals(rs2.getString(1)));
assertFalse(rs2.next());
stmt2.close();
rs2.close();
}
public void testClobUpdate4() throws Exception {
String data = getClobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobupdate4 (id NUMERIC IDENTITY, data TEXT, "
+ "CONSTRAINT pk_clobupdate4 PRIMARY KEY CLUSTERED (id))");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobupdate4 (data) VALUES (?)");
// Test PreparedStatement.setString()
pstmt.setString(1, data);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobupdate4");
assertTrue(rs.next());
Clob clob = rs.getClob(1);
data = getNewClobTestData();
// Test Clob.setBytes()
clob.setString(1, data);
assertTrue(data.equals(clob.getSubString(1, (int) clob.length())));
assertFalse(rs.next());
Statement stmt3 = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs2 = stmt3.executeQuery("SELECT id, data FROM #clobupdate4");
assertTrue(rs2.next());
// Test ResultSet.updateClob()
rs2.updateClob(2, clob);
rs2.updateRow();
assertFalse(rs2.next());
stmt2.close();
rs.close();
stmt3.close();
rs2.close();
Statement stmt4 = con.createStatement();
ResultSet rs3 = stmt4.executeQuery("SELECT data FROM #clobupdate4");
assertTrue(rs3.next());
// Test ResultSet.getString()
assertTrue(data.equals(rs3.getString(1)));
assertFalse(rs3.next());
stmt4.close();
rs3.close();
}
public void testClobUpdate5() throws Exception {
String data = getClobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobupdate5 (id NUMERIC IDENTITY, data TEXT, "
+ "CONSTRAINT pk_clobupdate5 PRIMARY KEY CLUSTERED (id))");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobupdate5 (data) VALUES (?)");
// Test PreparedStatement.setString()
pstmt.setString(1, data);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobupdate5");
assertTrue(rs.next());
Clob clob = rs.getClob(1);
data = getNewClobTestData();
// Test Clob.setBytes()
clob.setString(1, data);
assertTrue(data.equals(clob.getSubString(1, (int) clob.length())));
assertFalse(rs.next());
Statement stmt3 = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs2 = stmt3.executeQuery("SELECT id, data FROM #clobupdate5");
assertTrue(rs2.next());
// Test ResultSet.updateClob()
rs2.updateClob(2, clob);
rs2.updateRow();
assertFalse(rs2.next());
stmt2.close();
rs.close();
stmt3.close();
rs2.close();
Statement stmt4 = con.createStatement();
ResultSet rs3 = stmt4.executeQuery("SELECT data FROM #clobupdate5");
assertTrue(rs3.next());
// Test ResultSet.getString()
assertTrue(data.equals(rs3.getString(1)));
assertFalse(rs3.next());
stmt4.close();
rs3.close();
}
/**
* Test long Clob manipulation including indexed writes.
*/
public void testClobUpdate6() throws Exception {
int size = 100000;
StringBuffer data = new StringBuffer(size);
for (int i = 0; i < size; i++) {
data.append((char)('A'+i%10));
}
//
// Construct a clob
//
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ''");
assertNotNull(rs);
assertTrue(rs.next());
Clob clob = rs.getClob(1);
clob.setString(1, data.toString());
assertEquals((long)size, clob.length());
assertTrue(data.toString().equals(clob.getSubString(1, (int)clob.length())));
clob.setString(10, "THIS IS A TEST");
data.replace(9, 23, "THIS IS A TEST");
assertEquals("THIS IS A TEST", clob.getSubString(10, 14));
assertTrue(compare(data.toString(), clob.getSubString(1, (int)clob.length())));
clob.truncate(23);
assertEquals("ABCDEFGHITHIS IS A TEST", clob.getSubString(1, 23));
OutputStream os = clob.setAsciiStream(1);
for (int i = 0; i < size; i++) {
os.write(data.charAt(i));
}
os.close();
assertEquals((long)size, clob.length());
assertTrue(data.toString().equals(clob.getSubString(1, (int)clob.length())));
InputStream is = clob.getAsciiStream();
int b;
int p = 0;
while ((b = is.read()) >= 0) {
if ((char)b != data.charAt(p++)) {
fail("Mismatch at " + p);
}
}
is.close();
assertTrue(p == size);
Reader rdr = clob.getCharacterStream();
p = 0;
while ((b = rdr.read()) >= 0) {
if ((char)b != data.charAt(p++)) {
fail("Mismatch at " + p);
}
}
rdr.close();
assertTrue(p == size);
clob.truncate(0);
Writer wtr = clob.setCharacterStream(1);
for (int i = 0; i < size; i++) {
wtr.write(data.charAt(i));
}
wtr.close();
assertTrue(p == size);
assertTrue(data.toString().equals(clob.getSubString(1, (int)clob.length())));
wtr = clob.setCharacterStream(10000);
for (int i = 0; i < 8; i++) {
wtr.write('X');
}
wtr.close();
data.replace(10000-1, 10000-1+8, "XXXXXXXX");
assertTrue(data.toString().equals(clob.getSubString(1, (int)clob.length())));
clob.setString(100001, "XTESTX", 1, 4);
assertEquals((long)100000+4, clob.length());
assertEquals("JTEST", clob.getSubString(100000, 8));
assertEquals(100000, clob.position("JTEST", 100000));
Clob clob2 = rs.getClob(1);
clob.setString(1, "XXXXXXXX");
assertEquals(10000, clob.position("XXXXXXXX", 10000));
assertFalse(10000 == clob.position("XXXXXXXX", 10001));
}
public void testClobSetNull1() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobsetnull1 (data TEXT NULL)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobsetnull1 (data) VALUES (?)");
// Test PreparedStatement.setAsciiStream()
pstmt.setAsciiStream(1, null, 0);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobsetnull1");
assertTrue(rs.next());
// Test ResultSet.getAsciiStream()
assertNull(rs.getAsciiStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getCharacterStream()
assertNull(rs.getCharacterStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getClob()
assertNull(rs.getClob(1));
assertTrue(rs.wasNull());
// Test ResultSet.getObject()
assertNull(rs.getObject(1));
assertTrue(rs.wasNull());
// Test ResultSet.getString()
assertNull(rs.getString(1));
assertTrue(rs.wasNull());
// Test ResultSet.getUnicodeStream()
assertNull(rs.getUnicodeStream(1));
assertTrue(rs.wasNull());
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testClobSetNull2() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobsetnull2 (data TEXT NULL)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobsetnull2 (data) VALUES (?)");
// Test PreparedStatement.setCharacterStream()
pstmt.setCharacterStream(1, null, 0);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobsetnull2");
assertTrue(rs.next());
// Test ResultSet.getAsciiStream()
assertNull(rs.getAsciiStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getCharacterStream()
assertNull(rs.getCharacterStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getClob()
assertNull(rs.getClob(1));
assertTrue(rs.wasNull());
// Test ResultSet.getObject()
assertNull(rs.getObject(1));
assertTrue(rs.wasNull());
// Test ResultSet.getString()
assertNull(rs.getString(1));
assertTrue(rs.wasNull());
// Test ResultSet.getUnicodeStream()
assertNull(rs.getUnicodeStream(1));
assertTrue(rs.wasNull());
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testClobSetNull3() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobsetnull3 (data TEXT NULL)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobsetnull3 (data) VALUES (?)");
// Test PreparedStatement.setClob()
pstmt.setClob(1, (Clob)null);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobsetnull3");
assertTrue(rs.next());
// Test ResultSet.getAsciiStream()
assertNull(rs.getAsciiStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getCharacterStream()
assertNull(rs.getCharacterStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getClob()
assertNull(rs.getClob(1));
assertTrue(rs.wasNull());
// Test ResultSet.getObject()
assertNull(rs.getObject(1));
assertTrue(rs.wasNull());
// Test ResultSet.getString()
assertNull(rs.getString(1));
assertTrue(rs.wasNull());
// Test ResultSet.getUnicodeStream()
assertNull(rs.getUnicodeStream(1));
assertTrue(rs.wasNull());
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testClobSetNull4() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobsetnull4 (data TEXT NULL)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobsetnull4 (data) VALUES (?)");
// Test PreparedStatement.setObject(int,Object)
pstmt.setObject(1, null);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobsetnull4");
assertTrue(rs.next());
// Test ResultSet.getAsciiStream()
assertNull(rs.getAsciiStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getCharacterStream()
assertNull(rs.getCharacterStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getClob()
assertNull(rs.getClob(1));
assertTrue(rs.wasNull());
// Test ResultSet.getObject()
assertNull(rs.getObject(1));
assertTrue(rs.wasNull());
// Test ResultSet.getString()
assertNull(rs.getString(1));
assertTrue(rs.wasNull());
// Test ResultSet.getUnicodeStream()
assertNull(rs.getUnicodeStream(1));
assertTrue(rs.wasNull());
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testClobSetNull5() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobsetnull5 (data TEXT NULL)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobsetnull5 (data) VALUES (?)");
// Test PreparedStatement.setObject(int,Object,int)
pstmt.setObject(1, null, Types.CLOB);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobsetnull5");
assertTrue(rs.next());
// Test ResultSet.getAsciiStream()
assertNull(rs.getAsciiStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getCharacterStream()
assertNull(rs.getCharacterStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getClob()
assertNull(rs.getClob(1));
assertTrue(rs.wasNull());
// Test ResultSet.getObject()
assertNull(rs.getObject(1));
assertTrue(rs.wasNull());
// Test ResultSet.getString()
assertNull(rs.getString(1));
assertTrue(rs.wasNull());
// Test ResultSet.getUnicodeStream()
assertNull(rs.getUnicodeStream(1));
assertTrue(rs.wasNull());
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testClobSetNull6() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobsetnull6 (data TEXT NULL)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobsetnull6 (data) VALUES (?)");
// Test PreparedStatement.setString()
pstmt.setString(1, null);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobsetnull6");
assertTrue(rs.next());
// Test ResultSet.getAsciiStream()
assertNull(rs.getAsciiStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getCharacterStream()
assertNull(rs.getCharacterStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getClob()
assertNull(rs.getClob(1));
assertTrue(rs.wasNull());
// Test ResultSet.getObject()
assertNull(rs.getObject(1));
assertTrue(rs.wasNull());
// Test ResultSet.getString()
assertNull(rs.getString(1));
assertTrue(rs.wasNull());
// Test ResultSet.getUnicodeStream()
assertNull(rs.getUnicodeStream(1));
assertTrue(rs.wasNull());
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testClobSetNull7() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobsetnull7 (data TEXT NULL)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobsetnull7 (data) VALUES (?)");
// Test PreparedStatement.setUnicodeStream()
pstmt.setUnicodeStream(1, null, 0);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobsetnull7");
assertTrue(rs.next());
// Test ResultSet.getAsciiStream()
assertNull(rs.getAsciiStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getCharacterStream()
assertNull(rs.getCharacterStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getClob()
assertNull(rs.getClob(1));
assertTrue(rs.wasNull());
// Test ResultSet.getObject()
assertNull(rs.getObject(1));
assertTrue(rs.wasNull());
// Test ResultSet.getString()
assertNull(rs.getString(1));
assertTrue(rs.wasNull());
// Test ResultSet.getUnicodeStream()
assertNull(rs.getUnicodeStream(1));
assertTrue(rs.wasNull());
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testClobSetNull8() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobsetnull8 (data TEXT NULL)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobsetnull8 (data) VALUES (?)");
// Test PreparedStatement.setNull()
pstmt.setNull(1, Types.CLOB);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobsetnull8");
assertTrue(rs.next());
// Test ResultSet.getAsciiStream()
assertNull(rs.getAsciiStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getCharacterStream()
assertNull(rs.getCharacterStream(1));
assertTrue(rs.wasNull());
// Test ResultSet.getClob()
assertNull(rs.getClob(1));
assertTrue(rs.wasNull());
// Test ResultSet.getObject()
assertNull(rs.getObject(1));
assertTrue(rs.wasNull());
// Test ResultSet.getString()
assertNull(rs.getString(1));
assertTrue(rs.wasNull());
// Test ResultSet.getUnicodeStream()
assertNull(rs.getUnicodeStream(1));
assertTrue(rs.wasNull());
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testClobSetNull9() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobsetnull9 (id NUMERIC IDENTITY, data TEXT NULL, "
+ "CONSTRAINT pk_clobsetnull9 PRIMARY KEY CLUSTERED (id))");
stmt.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, data FROM #clobsetnull9");
rs.moveToInsertRow();
// Test ResultSet.updateAsciiStream()
rs.updateAsciiStream(2, null, 0);
rs.insertRow();
stmt.close();
rs.close();
Statement stmt2 = con.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT data FROM #clobsetnull9");
assertTrue(rs2.next());
// Test ResultSet.getAsciiStream()
assertNull(rs2.getAsciiStream(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getCharacterStream()
assertNull(rs2.getCharacterStream(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getClob()
assertNull(rs2.getClob(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getObject()
assertNull(rs2.getObject(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getString()
assertNull(rs2.getString(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getUnicodeStream()
assertNull(rs2.getUnicodeStream(1));
assertTrue(rs2.wasNull());
assertFalse(rs2.next());
stmt2.close();
rs2.close();
}
public void testClobSetNull10() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobsetnull10 (id NUMERIC IDENTITY, data TEXT NULL, "
+ "CONSTRAINT pk_clobsetnull10 PRIMARY KEY CLUSTERED (id))");
stmt.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, data FROM #clobsetnull10");
rs.moveToInsertRow();
// Test ResultSet.updateCharacterStream()
rs.updateCharacterStream(2, null, 0);
rs.insertRow();
stmt.close();
rs.close();
Statement stmt2 = con.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT data FROM #clobsetnull10");
assertTrue(rs2.next());
// Test ResultSet.getAsciiStream()
assertNull(rs2.getAsciiStream(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getCharacterStream()
assertNull(rs2.getCharacterStream(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getClob()
assertNull(rs2.getClob(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getObject()
assertNull(rs2.getObject(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getString()
assertNull(rs2.getString(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getUnicodeStream()
assertNull(rs2.getUnicodeStream(1));
assertTrue(rs2.wasNull());
assertFalse(rs2.next());
stmt2.close();
rs2.close();
}
public void testClobSetNull11() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobsetnull11 (id NUMERIC IDENTITY, data TEXT NULL, "
+ "CONSTRAINT pk_clobsetnull11 PRIMARY KEY CLUSTERED (id))");
stmt.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, data FROM #clobsetnull11");
rs.moveToInsertRow();
// Test ResultSet.updateClob()
rs.updateClob(2, (Clob)null);
rs.insertRow();
stmt.close();
rs.close();
Statement stmt2 = con.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT data FROM #clobsetnull11");
assertTrue(rs2.next());
// Test ResultSet.getAsciiStream()
assertNull(rs2.getAsciiStream(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getCharacterStream()
assertNull(rs2.getCharacterStream(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getClob()
assertNull(rs2.getClob(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getObject()
assertNull(rs2.getObject(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getString()
assertNull(rs2.getString(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getUnicodeStream()
assertNull(rs2.getUnicodeStream(1));
assertTrue(rs2.wasNull());
assertFalse(rs2.next());
stmt2.close();
rs2.close();
}
public void testClobSetNull12() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobsetnull12 (id NUMERIC IDENTITY, data TEXT NULL, "
+ "CONSTRAINT pk_clobsetnull12 PRIMARY KEY CLUSTERED (id))");
stmt.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, data FROM #clobsetnull12");
rs.moveToInsertRow();
// Test ResultSet.updateObject()
rs.updateObject(2, null);
rs.insertRow();
stmt.close();
rs.close();
Statement stmt2 = con.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT data FROM #clobsetnull12");
assertTrue(rs2.next());
// Test ResultSet.getAsciiStream()
assertNull(rs2.getAsciiStream(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getCharacterStream()
assertNull(rs2.getCharacterStream(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getClob()
assertNull(rs2.getClob(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getObject()
assertNull(rs2.getObject(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getString()
assertNull(rs2.getString(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getUnicodeStream()
assertNull(rs2.getUnicodeStream(1));
assertTrue(rs2.wasNull());
assertFalse(rs2.next());
stmt2.close();
rs2.close();
}
public void testClobSetNull13() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobsetnull13 (id NUMERIC IDENTITY, data TEXT NULL, "
+ "CONSTRAINT pk_clobsetnull13 PRIMARY KEY CLUSTERED (id))");
stmt.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, data FROM #clobsetnull13");
rs.moveToInsertRow();
// Test ResultSet.updateString()
rs.updateString(2, null);
rs.insertRow();
stmt.close();
rs.close();
Statement stmt2 = con.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT data FROM #clobsetnull13");
assertTrue(rs2.next());
// Test ResultSet.getAsciiStream()
assertNull(rs2.getAsciiStream(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getCharacterStream()
assertNull(rs2.getCharacterStream(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getClob()
assertNull(rs2.getClob(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getObject()
assertNull(rs2.getObject(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getString()
assertNull(rs2.getString(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getUnicodeStream()
assertNull(rs2.getUnicodeStream(1));
assertTrue(rs2.wasNull());
assertFalse(rs2.next());
stmt2.close();
rs2.close();
}
public void testClobSetNull14() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobsetnull14 (id NUMERIC IDENTITY, data TEXT NULL, "
+ "CONSTRAINT pk_clobsetnull14 PRIMARY KEY CLUSTERED (id))");
stmt.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, data FROM #clobsetnull14");
rs.moveToInsertRow();
// Test ResultSet.updateNull()
rs.updateNull(2);
rs.insertRow();
stmt.close();
rs.close();
Statement stmt2 = con.createStatement();
ResultSet rs2 = stmt2.executeQuery("SELECT data FROM #clobsetnull14");
assertTrue(rs2.next());
// Test ResultSet.getAsciiStream()
assertNull(rs2.getAsciiStream(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getCharacterStream()
assertNull(rs2.getCharacterStream(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getClob()
assertNull(rs2.getClob(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getObject()
assertNull(rs2.getObject(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getString()
assertNull(rs2.getString(1));
assertTrue(rs2.wasNull());
// Test ResultSet.getUnicodeStream()
assertNull(rs2.getUnicodeStream(1));
assertTrue(rs2.wasNull());
assertFalse(rs2.next());
stmt2.close();
rs2.close();
}
public void testClobGetSubString1() throws Exception {
String data = getClobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobgetsubstring1 (data TEXT)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobgetsubstring1 (data) VALUES (?)");
pstmt.setString(1, data);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobgetsubstring1");
assertTrue(rs.next());
// Test ResultSet.getClob()
Clob clob = rs.getClob(1);
assertNotNull(clob);
// Test Clob.getSubString()
assertTrue(data.equals(clob.getSubString(1L, (int) clob.length())));
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testClobGetSubString2() throws Exception {
String data = getClobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobgetsubstring2 (data TEXT)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobgetsubstring2 (data) VALUES (?)");
pstmt.setString(1, data);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobgetsubstring2");
assertTrue(rs.next());
// Test ResultSet.getClob()
Clob clob = rs.getClob(1);
assertNotNull(clob);
String tmpData = data.substring(0, data.length() / 2);
// Test Clob.getSubString()
assertTrue(tmpData.equals(clob.getSubString(1L, tmpData.length())));
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testClobGetSubString3() throws Exception {
String data = getClobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobgetsubstring3 (data TEXT)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobgetsubstring3 (data) VALUES (?)");
pstmt.setString(1, data);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobgetsubstring3");
assertTrue(rs.next());
// Test ResultSet.getClob()
Clob clob = rs.getClob(1);
assertNotNull(clob);
// Offset data by 1
String tmpData = data.substring(1, data.length() / 2);
// Test Clob.getSubString()
assertTrue(tmpData.equals(clob.getSubString(2L, tmpData.length())));
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testClobLength1() throws Exception {
String data = getClobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #cloblength1 (data TEXT)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #cloblength1 (data) VALUES (?)");
pstmt.setString(1, data);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #cloblength1");
assertTrue(rs.next());
// Test ResultSet.getClob()
Clob clob = rs.getClob(1);
assertNotNull(clob);
// Test Clob.length()
assertEquals(data.length(), clob.length());
assertFalse(rs.next());
stmt2.close();
rs.close();
}
public void testClobTruncate1() throws Exception {
String data = getClobTestData();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #clobtruncate1 (data TEXT)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #clobtruncate1 (data) VALUES (?)");
pstmt.setString(1, data);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #clobtruncate1");
assertTrue(rs.next());
// Test ResultSet.getClob()
Clob clob = rs.getClob(1);
assertNotNull(clob);
String tmpData = data.substring(0, data.length() / 2);
// Test Clob.truncate()
clob.truncate(tmpData.length());
assertEquals(tmpData.length(), clob.length());
// Test Clob.getSubString()
assertTrue(tmpData.equals(clob.getSubString(1L, (int) clob.length())));
assertFalse(rs.next());
stmt2.close();
rs.close();
}
/**
* Test for bug [1062395] Empty (but not null) blobs should return byte[0].
*/
public void testClobEmpty() throws Exception {
Statement stmt = con.createStatement();
assertEquals(0,
stmt.executeUpdate("CREATE TABLE #clobEmpty (data TEXT)"));
assertEquals(1,
stmt.executeUpdate("INSERT INTO #clobEmpty (data) values ('')"));
ResultSet rs = stmt.executeQuery("SELECT * FROM #clobEmpty");
assertTrue(rs.next());
Clob clob = rs.getClob(1);
assertEquals(0, clob.length());
assertEquals("", clob.getSubString(1, 0));
rs.close();
stmt.close();
}
public void testClobCaching() throws Exception {
// Create a Clob large enough to need caching to disk
char[] in = new char[100000];
for (int i = 0; i < in.length; i++) {
// Store non-Cp1252 characters into it
in[i] = 0x2032;
}
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #testClobCaching (val ntext)");
PreparedStatement pstmt = con.prepareStatement(
"insert into #testClobCaching values (?)");
pstmt.setCharacterStream(1, new CharArrayReader(in), in.length);
pstmt.executeUpdate();
pstmt.close();
ResultSet rs = stmt.executeQuery("select * from #testClobCaching");
assertTrue(rs.next());
String out = rs.getString(1);
assertEquals(in.length, out.length());
for (int i = 0; i < in.length; i++) {
if (in[i] != out.charAt(i)) {
fail("Result differs at position " + i);
}
}
assertFalse(rs.next());
rs.close();
stmt.close();
}
/**
* Test for incorrect handling of zero length streams (bug [1096086] Zero
* length streams generate null values).
*/
public void testZeroLengthStreams() throws Exception {
Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
stmt.execute("create table #test (id int primary key, s_ascii text," +
"s_char text, s_unicode text, s_bytes image)");
PreparedStatement pstmt =
con.prepareStatement("insert into #test values(?,?,?,?,?)");
// Write zero length fields
pstmt.setInt(1, 1);
pstmt.setAsciiStream(2, new ByteArrayInputStream(new byte[0]), 0);
pstmt.setCharacterStream(3, new StringReader(""), 0);
pstmt.setUnicodeStream(4, new ByteArrayInputStream(new byte[0]), 0);
pstmt.setBinaryStream(5, new ByteArrayInputStream(new byte[0]), 0);
assertEquals(1, pstmt.executeUpdate());
// Write non zero fields
pstmt.setInt(1, 2);
pstmt.setAsciiStream(2, new ByteArrayInputStream(new byte[1]), 1);
pstmt.setCharacterStream(3, new StringReader("TEST"), 4);
pstmt.setCharacterStream(4, new StringReader(""), 0);
pstmt.setUnicodeStream(4, new ByteArrayInputStream(new byte[2]), 2);
pstmt.setBinaryStream(5, new ByteArrayInputStream(new byte[1]), 1);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
ResultSet rs = stmt.executeQuery("select * from #test order by id");
assertTrue(rs.next());
assertTrue(rs.next());
// Update non zero length fields to zero
rs.updateAsciiStream(2, new ByteArrayInputStream(new byte[0]), 0);
rs.updateCharacterStream(3, new StringReader(""), 0);
Clob clob = rs.getClob(4);
clob.truncate(0);
rs.updateClob(4, clob);
rs.updateBinaryStream(5, new ByteArrayInputStream(new byte[0]), 0);
rs.updateRow();
rs.close();
// Test all fields now zero length
rs = stmt.executeQuery("select * from #test order by id");
while (rs.next()) {
assertEquals("AsciiStream", "", rs.getString(2));
assertEquals("Reader", "", rs.getString(3));
assertEquals("UnicodeStream", "", rs.getString(4));
assertEquals("byteStream", 0, rs.getBytes(5).length);
}
rs.close();
stmt.close();
}
/**
* Test for bug [1172405] BLOB/CLOB position methods fail.
*/
public void testBlobMethods() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #TESTBLOB (id int, blob image null)");
assertEquals(1, stmt.executeUpdate(
"INSERT INTO #TESTBLOB (id) VALUES (1)"));
assertEquals(1, stmt.executeUpdate(
"INSERT INTO #TESTBLOB (id, blob) VALUES (2, 0x4445)"));
assertEquals(1, stmt.executeUpdate(
"INSERT INTO #TESTBLOB (id, blob) VALUES (3, 0x4142434445464748)"));
ResultSet rs = stmt.executeQuery("SELECT * FROM #TESTBLOB");
assertNotNull(rs);
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
Blob blob = rs.getBlob(2);
assertNull(blob);
assertTrue(rs.next());
assertEquals(2, rs.getInt(1));
Blob pattern = rs.getBlob(2);
assertNotNull(pattern);
assertTrue(rs.next());
assertEquals(3, rs.getInt(1));
blob = rs.getBlob(2);
assertEquals(8, blob.length());
assertEquals("ABCDEFGH", new String(blob.getBytes(1, 8)));
assertEquals(4, blob.position(pattern, 1));
assertEquals(-1, blob.position(pattern, 8));
assertEquals(3, blob.position(new byte[]{0x43,0x44}, 1));
assertEquals(-1, blob.position(new byte[]{0x43,0x44}, 8));
byte buf[] = new byte[(int)blob.length()];
InputStream is = blob.getBinaryStream();
assertEquals((int)blob.length(), is.read(buf));
assertEquals(-1, is.read());
assertEquals("ABCDEFGH", new String(buf));
}
/**
* Test for bug [1172405] BLOB/CLOB position methods fail.
*/
public void testClobMethods() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #TESTCLOB (id int, clob text null)");
assertEquals(1, stmt.executeUpdate(
"INSERT INTO #TESTCLOB (id) VALUES (1)"));
assertEquals(1, stmt.executeUpdate(
"INSERT INTO #TESTCLOB (id, clob) VALUES (2, 'CD')"));
assertEquals(1, stmt.executeUpdate(
"INSERT INTO #TESTCLOB (id, clob) VALUES (3, 'ABCDEFGH')"));
ResultSet rs = stmt.executeQuery("SELECT * FROM #TESTCLOB");
assertNotNull(rs);
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
Clob clob = rs.getClob(2);
assertNull(clob);
assertTrue(rs.next());
assertEquals(2, rs.getInt(1));
Clob pattern = rs.getClob(2);
assertNotNull(pattern);
assertTrue(rs.next());
assertEquals(3, rs.getInt(1));
clob = rs.getClob(2);
assertEquals(8, clob.length());
assertEquals("ABCDEFGH", clob.getSubString(1, 8));
assertEquals(3, clob.position(pattern, 1));
assertEquals(-1, clob.position(pattern, 8));
assertEquals(3, clob.position("CD", 1));
assertEquals(-1, clob.position("CD", 8));
Reader rdr = clob.getCharacterStream();
char buf[] = new char[(int)clob.length()];
assertEquals((int)clob.length(), rdr.read(buf));
assertEquals(-1, rdr.read());
assertEquals("ABCDEFGH", new String(buf));
byte bbuf[] = new byte[(int)clob.length()];
InputStream is = clob.getAsciiStream();
assertEquals((int)clob.length(), is.read(bbuf));
assertEquals(-1, is.read());
assertEquals("ABCDEFGH", new String(bbuf));
}
private byte[] getBlobTestData() {
return blobData;
}
private byte[] getNewBlobTestData() {
return newBlobData;
}
private String getClobTestData() {
return clobData;
}
private String getNewClobTestData() {
return newClobData;
}
/**
* Implements an InputStream that only returns a limited
* number of bytes on read (less than the requested number of bytes).
*
* Used for testing Blob insert behavior.
*/
static class RealInputStream extends InputStream {
/**
* Length of the stream.
*/
static final int LENGTH = 10000;
/**
* Current position in the stream.
*/
private int pos = 0;
public int read() {
if (++pos > LENGTH) {
return -1;
}
return pos % 256;
}
public int read(byte[] b) {
return read(b, 0, b.length);
}
public int read(byte[] b, int off, int len) {
int res = read();
if (res == -1) {
return -1;
} else {
b[off] = (byte) res;
return 1;
}
}
}
/**
* Compares long byte arrays.
*/
private boolean compare(byte []b1, byte[] b2) {
if (b1.length != b2.length) {
System.out.println("Compare failed: lengths differ");
return false;
}
for (int i = 0; i < b1.length; i++) {
if (b1[i] != b2[i]) {
System.out.println("Compare failed: bytes at " + i + " differ ["
+ b1[i] + "] [" + b2[i] + "]");
return false;
}
}
return true;
}
/**
* Compare long Strings.
*/
public boolean compare(String s1, String s2) {
if (s1.length() != s2.length()) {
System.out.println("Compare failed: lengths differ");
return false;
}
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) != s2.charAt(i)) {
System.out.println("Compare failed: bytes at " + i + " differ ["
+ s1.charAt(i) + "] [" + s2.charAt(i) + "]");
return false;
}
}
return true;
}
public static void main(String[] args) {
junit.textui.TestRunner.run(LOBTest.class);
}
} libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/EncodingTest.java 0000644 0001750 0001750 00000010254 11316672660 026443 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.sql.*;
import java.util.Arrays;
import net.sourceforge.jtds.jdbc.Messages;
/**
* @version 1.0
*/
public class EncodingTest extends TestBase {
public EncodingTest(String name) {
super(name);
}
/**
* Test for bug [101956] updateBytes converted to hex in varchar
*
DatabaseMetaData.
*
* @version $Id: DatabaseMetaDataJDBC3Test.java,v 1.2 2005/01/05 12:24:14 alin_sinpalean Exp $
*/
public class DatabaseMetaDataJDBC3Test extends MetaDataTestCase {
public DatabaseMetaDataJDBC3Test(String name) {
super(name);
}
/**
* Test meta data functions that return boolean values.
*/
public void testBooleanOptions() throws Exception {
DatabaseMetaData dbmd = con.getMetaData();
//
// Test JDBC 3 items
//
assertTrue("locatorsUpdateCopy",dbmd.locatorsUpdateCopy());
assertTrue("supportsGetGeneratedKeys", dbmd.supportsGetGeneratedKeys());
assertTrue("supportsMultipleOpenResults", dbmd.supportsMultipleOpenResults());
assertTrue("supportsNamedParameters", dbmd.supportsNamedParameters());
assertFalse("supportsResultSetHoldability", dbmd.supportsResultSetHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT));
assertFalse("supportsResultSetHoldability", dbmd.supportsResultSetHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT));
assertTrue("supportsSavepoints", dbmd.supportsSavepoints());
assertTrue("supportsStatementPooling", dbmd.supportsStatementPooling());
}
/**
* Test meta data function that return integer values.
*/
public void testIntOptions() throws Exception {
DatabaseMetaData dbmd = con.getMetaData();
//
// JDBC3 functions
//
assertTrue("getDatabaseMajorVersion", dbmd.getDatabaseMajorVersion() >= 0);
assertTrue("getDatabaseMinorVersion", dbmd.getDatabaseMinorVersion() >= 0);
assertEquals("getResultSetHoldability",ResultSet.HOLD_CURSORS_OVER_COMMIT, dbmd.getResultSetHoldability());
assertEquals("getSQLStateType",1, dbmd.getSQLStateType());
assertEquals("getJDBCMajorVersion", 3, dbmd.getJDBCMajorVersion());
assertEquals("getJDBCMinorVersion", 0, dbmd.getJDBCMinorVersion());
}
/**
* Test meta data functions that return result sets.
*/
public void testResultSets() throws Exception
{
DatabaseMetaData dbmd = con.getMetaData();
ResultSet rs;
//
// JDBC3 Methods
//
rs = dbmd.getAttributes(null, null, null, null);
assertTrue(checkColumnNames(rs, new String[]{"TYPE_CAT", "TYPE_SCHEM","TYPE_NAME","ATTR_NAME",
"DATA_TYPE","ATTR_TYPE_NAME","ATTR_SIZE","DECIMAL_DIGITS","NUM_PREC_RADIX","NULLABLE",
"REMARKS","ATTR_DEF","SQL_DATA_TYPE","SQL_DATETIME_SUB","CHAR_OCTET_LENGTH",
"ORDINAL_POSITION","IS_NULLABLE","SCOPE_CATALOG","SCOPE_SCHEMA","SCOPE_TABLE","SOURCE_DATA_TYPE"}));
assertFalse(rs.next());
rs.close();
//
rs = dbmd.getSuperTables(null, null, "%");
assertTrue(checkColumnNames(rs, new String[]{"TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME","SUPERTABLE_NAME"}));
assertFalse(rs.next());
rs.close();
//
rs = dbmd.getSuperTypes(null, null, "%");
assertTrue(checkColumnNames(rs, new String[]{"TYPE_CAT", "TYPE_SCHEM", "TYPE_NAME",
"SUPERTYPE_CAT", "SUPERTYPE_SCHEM", "SUPERTYPE_NAME"}));
assertFalse(rs.next());
rs.close();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(DatabaseMetaDataJDBC3Test.class);
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/JtdsDataSourceUnitTest.java 0000644 0001750 0001750 00000035020 11316672660 030432 0 ustar martin martin //jTDS JDBC Driver for Microsoft SQL Server and Sybase
//Copyright (C) 2004 The jTDS Project
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.naming.NamingException;
import javax.naming.Reference;
import junit.framework.Test;
import junit.framework.TestSuite;
import net.sourceforge.jtds.jdbcx.JtdsDataSource;
import net.sourceforge.jtds.jdbc.Messages;
import net.sourceforge.jtds.jdbc.Driver;
/**
* Unit tests for the {@link JtdsDataSource} class.
*
* @author David D. Kilzer
* @version $Id: JtdsDataSourceUnitTest.java,v 1.21 2007/07/08 18:08:54 bheineman Exp $
*/
public class JtdsDataSourceUnitTest extends UnitTestBase {
/**
* Construct a test suite for this class.
*
* The test suite includes the tests in this class as
* well as {@link Test_JtdsDataSource_getConnection}.
*
* @return The test suite to run.
*/
public static Test suite() {
TestSuite testSuite = new TestSuite(JtdsDataSourceUnitTest.class);
testSuite.addTest(new TestSuite(
JtdsDataSourceUnitTest.Test_JtdsDataSource_fields.class, "test_fields_DefaultProperties"));
testSuite.addTest(new TestSuite(
JtdsDataSourceUnitTest.Test_JtdsDataSource_getReference.class, "test_getReference_DefaultProperties"));
testSuite.addTest(new TestSuite(
JtdsDataSourceUnitTest.Test_JtdsDataSource_addNonNullProperties.class, "test_addNonNullProperties_DefaultProperties"));
testSuite.addTest(new TestSuite(
JtdsDataSourceUnitTest.Test_JtdsDataSource_getConnection.class, "test_getConnection"));
return testSuite;
}
/**
* Constructor.
*
* @param name The name of the test.
*/
public JtdsDataSourceUnitTest(String name) {
super(name);
}
/**
* Tests that the public constructor works.
*
* Needed so that this class has at least one test.
*/
public void testPublicConstructor() {
assertNotNull(new JtdsDataSource());
}
/** Class used to test {@link JtdsDataSource}. */
public static class Test_JtdsDataSource_fields
extends DefaultPropertiesTestLibrary {
/**
* Default constructor.
*/
public Test_JtdsDataSource_fields() {
setTester(
new DefaultPropertiesTester() {
public void assertDefaultProperty(
String message, String url, Properties properties, String fieldName,
String key, String expected) {
// Hack for JtdsDataSource.getCacheMetaData()
{
if ("useMetadataCache".equals(fieldName)) {
fieldName = "cacheMetaData";
}
}
JtdsDataSource dataSource = new JtdsDataSource();
invokeSetInstanceField(dataSource, fieldName, expected);
// Hack for JtdsDataSource.getTds()
{
if ("tdsVersion".equals(fieldName)) {
fieldName = "tds";
}
}
String actual =
String.valueOf(
invokeInstanceMethod(
dataSource,
"get" + ucFirst(fieldName),
new Class[]{}, new Object[]{}));
assertEquals(message, expected, actual);
}
}
);
}
}
/** Class used to test {@link JtdsDataSource#getReference()}. */
public static class Test_JtdsDataSource_getReference
extends DefaultPropertiesTestLibrary {
/**
* Default constructor.
*/
public Test_JtdsDataSource_getReference() {
setTester(
new DefaultPropertiesTester() {
public void assertDefaultProperty(
String message, String url, Properties properties, String fieldName,
String key, String expected) {
try {
// Hack for JtdsDataSource.getCacheMetaData()
{
if ("useMetadataCache".equals(fieldName)) {
fieldName = "cacheMetaData";
}
}
JtdsDataSource dataSource = new JtdsDataSource();
invokeSetInstanceField(dataSource, fieldName, expected);
Reference reference = dataSource.getReference();
assertEquals(message, expected, reference.get(Messages.get(key)).getContent());
}
catch (NamingException e) {
throw new RuntimeException(e.getMessage());
}
}
}
);
}
}
/** Class used to test JtdsDataSource.addNonNullProperties(Properties, String, String). */
public static class Test_JtdsDataSource_addNonNullProperties
extends DefaultPropertiesTestLibrary {
/**
* Default constructor.
*/
public Test_JtdsDataSource_addNonNullProperties() {
setTester(
new DefaultPropertiesTester() {
public void assertDefaultProperty(
String message, String url, Properties properties, String fieldName,
String key, String expected) {
// Hack for JtdsDataSource.cacheMetaData
{
if ("useMetadataCache".equals(fieldName)) {
fieldName = "cacheMetaData";
}
}
JtdsDataSource dataSource = new JtdsDataSource();
dataSource.setServerName("non-null-value");
invokeSetInstanceField(dataSource, fieldName, expected);
Properties props = new Properties();
invokeInstanceMethod(dataSource, "addNonNullProperties",
new Class[]{Properties.class, String.class, String.class},
new Object[]{props, "", ""});
assertEquals(message, expected, props.getProperty(Messages.get(key)));
}
}
);
}
}
public static class Test_JtdsDataSource_getConnection extends UnitTestBase {
// TODO Specify host name separately in the properties so that testing can be more accurate
public Test_JtdsDataSource_getConnection(String name) {
super(name);
}
/**
* Provides a null test suite so that JUnit will not try to instantiate this class directly.
*
* @return The test suite (always null).
*/
public static final Test suite() {
return null;
}
/**
* Test connecting without specifying a host. Should get an SQL state
* of 08001 (SQL client unable to establish SQL connection).
*/
public void testNoHost() {
JtdsDataSource ds = new JtdsDataSource();
ds.setUser(TestBase.props.getProperty(Messages.get(Driver.USER)));
ds.setPassword(TestBase.props.getProperty(Messages.get(Driver.PASSWORD)));
ds.setDatabaseName(TestBase.props.getProperty(Messages.get(Driver.DATABASENAME)));
try {
ds.setPortNumber(Integer.parseInt(
TestBase.props.getProperty(Messages.get(Driver.PORTNUMBER))));
} catch (Exception ex) {
// Ignore
}
try {
assertNotNull(ds.getConnection());
fail("What the?...");
} catch (SQLException ex) {
assertEquals("Expecting SQL state 08001. Got " + ex.getSQLState(), "08001", ex.getSQLState());
} catch (Throwable t) {
t.printStackTrace();
fail(t.getClass().getName() + " caught while testing JtdsDataSource.getConnection(): " + t);
}
}
/**
* Test connecting without specifying a user. Should get an SQL state
* of either 28000 (invalid authorization specification) or 08S01 (bad
* host name).
*/
public void testNoUser() {
JtdsDataSource ds = new JtdsDataSource();
ds.setServerName(TestBase.props.getProperty(Messages.get(Driver.SERVERNAME)));
ds.setDatabaseName(TestBase.props.getProperty(Messages.get(Driver.DATABASENAME)));
try {
ds.setPortNumber(Integer.parseInt(
TestBase.props.getProperty(Messages.get(Driver.PORTNUMBER))));
} catch (Exception ex) {
// Ignore
}
try {
assertNotNull(ds.getConnection());
fail("What the?...");
} catch (SQLException ex) {
String sqlState = ex.getSQLState();
if (!"28000".equals(sqlState) && !sqlState.startsWith("08")) {
ex.printStackTrace();
fail("Expecting SQL state 28000 or 08XXX. Got " + ex.getSQLState());
}
} catch (Throwable t) {
t.printStackTrace();
fail(t.getClass().getName() + " caught while testing JtdsDataSource.getConnection(): " + t);
}
}
/**
* Test connecting with the settings in connection.properties.
* * Should also test bug [1051595] jtdsDataSource connects only to * localhost. */ public void testNormal() { JtdsDataSource ds = new JtdsDataSource(); ds.setServerName(TestBase.props.getProperty(Messages.get(Driver.SERVERNAME))); ds.setUser(TestBase.props.getProperty(Messages.get(Driver.USER))); ds.setPassword(TestBase.props.getProperty(Messages.get(Driver.PASSWORD))); ds.setDatabaseName(TestBase.props.getProperty(Messages.get(Driver.DATABASENAME))); ds.setTds(TestBase.props.getProperty(Messages.get(Driver.TDS))); ds.setServerType("2".equals(TestBase.props.getProperty(Messages.get(Driver.SERVERTYPE))) ? 2 : 1); try { ds.setPortNumber(Integer.parseInt( TestBase.props.getProperty(Messages.get(Driver.PORTNUMBER)))); } catch (Exception ex) { // Ignore } try { Connection c = ds.getConnection(); assertNotNull(c); c.close(); } catch (SQLException ex) { ex.printStackTrace(); fail("SQLException caught: " + ex.getMessage() + " SQLState=" + ex.getSQLState()); } catch (Throwable t) { t.printStackTrace(); fail(t.getClass().getName() + " caught while testing JtdsDataSource.getConnection(): " + t); } } /** * Test connecting without specifying TDS version. *
* Test for bug [1113709] Connecting via DataSource. Issue was caused * by JtdsDataSource setting the default values in the constructor, so * the TDS version was always set to 8.0 unless explicitly modified. * * The incorrect behavior occured when connecting to Sybase (when the * TDS version should have been 5.0 by default). */ public void testDefaultTdsVersion() { JtdsDataSource ds = new JtdsDataSource(); ds.setServerName(TestBase.props.getProperty(Messages.get(Driver.SERVERNAME))); ds.setUser(TestBase.props.getProperty(Messages.get(Driver.USER))); ds.setPassword(TestBase.props.getProperty(Messages.get(Driver.PASSWORD))); ds.setDatabaseName(TestBase.props.getProperty(Messages.get(Driver.DATABASENAME))); ds.setServerType("2".equals(TestBase.props.getProperty(Messages.get(Driver.SERVERTYPE))) ? 2 : 1); try { ds.setPortNumber(Integer.parseInt( TestBase.props.getProperty(Messages.get(Driver.PORTNUMBER)))); } catch (Exception ex) { // Ignore } try { Connection c = ds.getConnection(); assertNotNull(c); c.close(); } catch (SQLException ex) { ex.printStackTrace(); fail("SQLException caught: " + ex.getMessage() + " SQLState=" + ex.getSQLState()); } catch (Throwable t) { t.printStackTrace(); fail(t.getClass().getName() + " caught while testing JtdsDataSource.getConnection(): " + t); } } } } libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/DatabaseMetaDataTest.java 0000644 0001750 0001750 00000140701 11316672660 030023 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase // Copyright (C) 2004 The jTDS Project // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // package net.sourceforge.jtds.test; import java.sql.*; import java.util.Properties; /** * TestDatabaseMetaData.
*
* @version $Id: DatabaseMetaDataTest.java,v 1.17.2.5 2009/12/30 13:45:25 ickzon Exp $
*/
public class DatabaseMetaDataTest extends MetaDataTestCase {
public DatabaseMetaDataTest(String name) {
super(name);
}
/**
* Test meta data functions that return boolean values.
* @throws Exception
*/
public void testBooleanOptions() throws Exception {
DatabaseMetaData dbmd = con.getMetaData();
assertFalse("dataDefinitionCausesTransactionCommit", dbmd.dataDefinitionCausesTransactionCommit());
assertFalse("dataDefinitionIgnoredInTransactions", dbmd.dataDefinitionIgnoredInTransactions());
assertTrue("deletesAreDetected", dbmd.deletesAreDetected(ResultSet.TYPE_FORWARD_ONLY));
assertTrue("deletesAreDetected", dbmd.deletesAreDetected(ResultSet.TYPE_SCROLL_INSENSITIVE));
assertFalse("doesMaxRowSizeIncludeBlobs", dbmd.doesMaxRowSizeIncludeBlobs());
assertFalse("insertsAreDetected", dbmd.insertsAreDetected(ResultSet.TYPE_FORWARD_ONLY));
assertFalse("insertsAreDetected", dbmd.insertsAreDetected(ResultSet.TYPE_SCROLL_INSENSITIVE));
assertFalse("insertsAreDetected", dbmd.insertsAreDetected(ResultSet.TYPE_SCROLL_SENSITIVE));
assertTrue("isCatalogAtStart", dbmd.isCatalogAtStart());
assertFalse("isReadOnly", dbmd.isReadOnly());
assertTrue("nullPlusNonNullIsNull", dbmd.nullPlusNonNullIsNull());
assertFalse("nullsAreSortedAtEnd", dbmd.nullsAreSortedAtEnd());
assertFalse("nullsAreSortedAtStart", dbmd.nullsAreSortedAtStart());
assertFalse("nullsAreSortedHigh", dbmd.nullsAreSortedHigh());
assertTrue("nullsAreSortedLow", dbmd.nullsAreSortedLow());
assertFalse("othersDeletesAreVisible",dbmd.othersDeletesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));
assertFalse("othersInsertsAreVisible",dbmd.othersInsertsAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));
assertFalse("othersInsertsAreVisible",dbmd.othersInsertsAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));
assertTrue("othersInsertsAreVisible",dbmd.othersInsertsAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE + 1));
assertFalse("othersUpdatesAreVisible",dbmd.othersUpdatesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));
assertTrue("othersUpdatesAreVisible",dbmd.othersUpdatesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));
assertTrue("ownInsertsAreVisible", dbmd.ownInsertsAreVisible(ResultSet.TYPE_FORWARD_ONLY));
assertTrue("ownInsertsAreVisible", dbmd.ownInsertsAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));
assertTrue("ownInsertsAreVisible", dbmd.ownInsertsAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));
assertTrue("ownUpdatesAreVisible", dbmd.ownUpdatesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));
assertTrue("ownUpdatesAreVisible", dbmd.ownUpdatesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));
assertFalse("storesLowerCaseIdentifiers", dbmd.storesLowerCaseIdentifiers());
assertFalse("storesLowerCaseQuotedIdentifiers", dbmd.storesLowerCaseQuotedIdentifiers());
assertFalse("storesUpperCaseIdentifiers", dbmd.storesUpperCaseIdentifiers());
assertFalse("storesUpperCaseQuotedIdentifiers", dbmd.storesUpperCaseQuotedIdentifiers());
assertTrue("supportsAlterTableWithAddColumn", dbmd.supportsAlterTableWithAddColumn());
assertTrue("supportsAlterTableWithDropColumn", dbmd.supportsAlterTableWithDropColumn());
assertTrue("supportsANSI92EntryLevelSQL", dbmd.supportsANSI92EntryLevelSQL());
assertFalse("supportsANSI92FullSQL", dbmd.supportsANSI92FullSQL());
assertFalse("supportsANSI92IntermediateSQL", dbmd.supportsANSI92IntermediateSQL());
assertTrue("supportsBatchUpdates", dbmd.supportsBatchUpdates());
assertTrue("supportsCatalogsInDataManipulation", dbmd.supportsCatalogsInDataManipulation());
assertTrue("supportsCatalogsInIndexDefinitions", dbmd.supportsCatalogsInIndexDefinitions());
assertTrue("supportsCatalogsInProcedureCalls", dbmd.supportsCatalogsInProcedureCalls());
assertTrue("supportsCatalogsInTableDefinitions", dbmd.supportsCatalogsInTableDefinitions());
assertTrue("supportsColumnAliasing", dbmd.supportsColumnAliasing());
assertTrue("supportsConvert", dbmd.supportsConvert());
assertTrue("supportsCorrelatedSubqueries", dbmd.supportsCorrelatedSubqueries());
assertTrue("supportsDataDefinitionAndDataManipulationTransactions", dbmd.supportsDataDefinitionAndDataManipulationTransactions());
assertFalse("supportsDataManipulationTransactionsOnly", dbmd.supportsDataManipulationTransactionsOnly());
assertFalse("supportsDifferentTableCorrelationNames", dbmd.supportsDifferentTableCorrelationNames());
assertTrue("supportsExpressionsInOrderBy", dbmd.supportsExpressionsInOrderBy());
assertFalse("supportsExtendedSQLGrammar", dbmd.supportsExtendedSQLGrammar());
assertTrue("supportsGroupBy", dbmd.supportsGroupBy());
assertTrue("supportsGroupByBeyondSelect", dbmd.supportsGroupByBeyondSelect());
assertTrue("supportsGroupByUnrelated", dbmd.supportsGroupByUnrelated());
assertTrue("supportsLimitedOuterJoins", dbmd.supportsLimitedOuterJoins());
assertTrue("supportsMinimumSQLGrammar", dbmd.supportsMinimumSQLGrammar());
assertTrue("supportsMultipleResultSets", dbmd.supportsMultipleResultSets());
assertTrue("supportsMultipleTransactions", dbmd.supportsMultipleTransactions());
assertTrue("supportsNonNullableColumns", dbmd.supportsNonNullableColumns());
assertTrue("supportsOpenStatementsAcrossCommit", dbmd.supportsOpenStatementsAcrossCommit());
assertTrue("supportsOpenStatementsAcrossRollback", dbmd.supportsOpenStatementsAcrossRollback());
assertTrue("supportsOrderByUnrelated", dbmd.supportsOrderByUnrelated());
assertTrue("supportsOuterJoins", dbmd.supportsOuterJoins());
assertTrue("supportsResultSetConcurrency", dbmd.supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY));
assertTrue("supportsResultSetConcurrency", dbmd.supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE));
assertTrue("supportsResultSetConcurrency", dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY));
assertTrue("supportsResultSetConcurrency", dbmd.supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE + 1));
assertTrue("supportsResultSetConcurrency", dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE + 2));
assertTrue("supportsResultSetType", dbmd.supportsResultSetType(ResultSet.TYPE_FORWARD_ONLY));
assertTrue("supportsResultSetType", dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE));
assertTrue("supportsResultSetType", dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE));
assertTrue("supportsResultSetType", dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE + 1));
assertTrue("supportsSchemasInDataManipulation", dbmd.supportsSchemasInDataManipulation());
assertTrue("supportsSchemasInIndexDefinitions", dbmd.supportsSchemasInIndexDefinitions());
assertTrue("supportsSchemasInProcedureCalls", dbmd.supportsSchemasInProcedureCalls());
assertTrue("supportsSchemasInTableDefinitions", dbmd.supportsSchemasInTableDefinitions());
assertTrue("supportsStoredProcedures", dbmd.supportsStoredProcedures());
assertTrue("supportsSubqueriesInComparisons", dbmd.supportsSubqueriesInComparisons());
assertTrue("supportsSubqueriesInExists", dbmd.supportsSubqueriesInExists());
assertTrue("supportsSubqueriesInIns", dbmd.supportsSubqueriesInIns());
assertTrue("supportsSubqueriesInQuantifieds", dbmd.supportsSubqueriesInQuantifieds());
assertTrue("supportsTableCorrelationNames", dbmd.supportsTableCorrelationNames());
assertTrue("supportsTransactionIsolationLevel", dbmd.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED));
assertTrue("supportsTransactionIsolationLevel", dbmd.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_UNCOMMITTED));
assertTrue("supportsTransactionIsolationLevel", dbmd.supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE));
assertTrue("supportsTransactions", dbmd.supportsTransactions());
assertTrue("supportsUnion", dbmd.supportsUnion());
assertTrue("supportsUnionAll", dbmd.supportsUnionAll());
assertFalse("updatesAreDetected", dbmd.updatesAreDetected(ResultSet.TYPE_FORWARD_ONLY));
assertFalse("updatesAreDetected", dbmd.updatesAreDetected(ResultSet.TYPE_SCROLL_INSENSITIVE));
assertFalse("updatesAreDetected", dbmd.updatesAreDetected(ResultSet.TYPE_SCROLL_SENSITIVE));
assertFalse("usesLocalFilePerTable", dbmd.usesLocalFilePerTable());
assertFalse("usesLocalFiles", dbmd.usesLocalFiles());
assertTrue("deletesAreDetected", dbmd.deletesAreDetected(ResultSet.TYPE_SCROLL_SENSITIVE));
assertTrue("othersDeletesAreVisible",dbmd.othersDeletesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));
assertTrue("supportsResultSetConcurrency", dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY));
assertTrue("supportsResultSetConcurrency", dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE));
assertTrue("allProceduresAreCallable", dbmd.allProceduresAreCallable());
assertFalse("othersDeletesAreVisible",dbmd.othersDeletesAreVisible(ResultSet.TYPE_FORWARD_ONLY));
assertFalse("othersInsertsAreVisible",dbmd.othersInsertsAreVisible(ResultSet.TYPE_FORWARD_ONLY));
assertFalse("othersUpdatesAreVisible",dbmd.othersUpdatesAreVisible(ResultSet.TYPE_FORWARD_ONLY));
assertTrue("ownUpdatesAreVisible", dbmd.ownUpdatesAreVisible(ResultSet.TYPE_FORWARD_ONLY));
assertTrue("storesMixedCaseIdentifiers", dbmd.storesMixedCaseIdentifiers());
assertTrue("storesMixedCaseQuotedIdentifiers", dbmd.storesMixedCaseQuotedIdentifiers());
assertTrue("supportsCoreSQLGrammar", dbmd.supportsCoreSQLGrammar());
assertFalse("supportsIntegrityEnhancementFacility", dbmd.supportsIntegrityEnhancementFacility());
assertFalse("supportsMixedCaseIdentifiers", dbmd.supportsMixedCaseIdentifiers());
assertFalse("supportsMixedCaseQuotedIdentifiers", dbmd.supportsMixedCaseQuotedIdentifiers());
assertTrue("supportsPositionedDelete", dbmd.supportsPositionedDelete());
assertTrue("supportsPositionedUpdate", dbmd.supportsPositionedUpdate());
assertFalse("supportsResultSetConcurrency", dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE));
assertFalse("supportsResultSetConcurrency", dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE + 1));
assertFalse("supportsResultSetConcurrency", dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE + 2));
assertTrue("supportsSchemasInPrivilegeDefinitions", dbmd.supportsSchemasInPrivilegeDefinitions());
assertFalse("supportsSelectForUpdate", dbmd.supportsSelectForUpdate());
assertTrue("supportsTransactionIsolationLevel", dbmd.supportsTransactionIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ));
assertTrue("ownDeletesAreVisible", dbmd.ownDeletesAreVisible(ResultSet.TYPE_FORWARD_ONLY));
assertTrue("ownDeletesAreVisible", dbmd.ownDeletesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));
assertTrue("ownDeletesAreVisible", dbmd.ownDeletesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));
assertTrue("supportsCatalogsInPrivilegeDefinitions", dbmd.supportsCatalogsInPrivilegeDefinitions());
assertTrue("supportsFullOuterJoins", dbmd.supportsFullOuterJoins());
assertTrue("supportsLikeEscapeClause", dbmd.supportsLikeEscapeClause());
assertTrue("supportsOpenCursorsAcrossCommit", dbmd.supportsOpenCursorsAcrossCommit());
assertFalse("supportsTransactionIsolationLevel", dbmd.supportsTransactionIsolationLevel(Connection.TRANSACTION_NONE));
if (dbmd.getDatabaseProductName().startsWith("Microsoft")) {
assertTrue("allTablesAreSelectable", dbmd.allTablesAreSelectable());
assertFalse("supportsOpenCursorsAcrossRollback", dbmd.supportsOpenCursorsAcrossRollback());
} else {
assertFalse("allTablesAreSelectable", dbmd.allTablesAreSelectable());
assertTrue("supportsOpenCursorsAcrossRollback", dbmd.supportsOpenCursorsAcrossRollback());
}
}
/**
* Test meta data functions that return strings.
* @throws Exception
*/
public void testStringOptions() throws Exception {
DatabaseMetaData dbmd = con.getMetaData();
assertEquals("getCatalogSeparator", ".", dbmd.getCatalogSeparator());
assertEquals("getCatalogTerm","database", dbmd.getCatalogTerm());
assertNotNull("getDatabaseProductName", dbmd.getDatabaseProductName());
assertNotNull("getDatabaseProductVersion", dbmd.getDatabaseProductVersion());
assertNotNull("getDriverName", dbmd.getDriverName());
assertNotNull("getDriverVersion", dbmd.getDriverVersion());
assertEquals("getExtraNameCharacters","$#@", dbmd.getExtraNameCharacters());
assertEquals("getIdentifierQuoteString","\"", dbmd.getIdentifierQuoteString());
assertEquals("getNumericFunctions","abs,acos,asin,atan,atan2,ceiling,cos,cot,degrees,exp,floor,log,log10,mod,pi,power,radians,rand,round,sign,sin,sqrt,tan", dbmd.getNumericFunctions());
assertEquals("getProcedureTerm","stored procedure", dbmd.getProcedureTerm());
assertEquals("getSchemaTerm","owner", dbmd.getSchemaTerm());
assertEquals("getSearchStringEscape","\\", dbmd.getSearchStringEscape());
assertEquals("getSQLKeywords","ARITH_OVERFLOW,BREAK,BROWSE,BULK,CHAR_CONVERT,CHECKPOINT,CLUSTERED,COMPUTE,CONFIRM,CONTROLROW,DATA_PGS,DATABASE,DBCC,DISK,DUMMY,DUMP,ENDTRAN,ERRLVL,ERRORDATA,ERROREXIT,EXIT,FILLFACTOR,HOLDLOCK,IDENTITY_INSERT,IF,INDEX,KILL,LINENO,LOAD,MAX_ROWS_PER_PAGE,MIRROR,MIRROREXIT,NOHOLDLOCK,NONCLUSTERED,NUMERIC_TRUNCATION,OFF,OFFSETS,ONCE,ONLINE,OVER,PARTITION,PERM,PERMANENT,PLAN,PRINT,PROC,PROCESSEXIT,RAISERROR,READ,READTEXT,RECONFIGURE,REPLACE,RESERVED_PGS,RETURN,ROLE,ROWCNT,ROWCOUNT,RULE,SAVE,SETUSER,SHARED,SHUTDOWN,SOME,STATISTICS,STRIPE,SYB_IDENTITY,SYB_RESTREE,SYB_TERMINATE,TEMP,TEXTSIZE,TRAN,TRIGGER,TRUNCATE,TSEQUAL,UNPARTITION,USE,USED_PGS,USER_OPTION,WAITFOR,WHILE,WRITETEXT", dbmd.getSQLKeywords());
assertEquals("getSystemFunctions","database,ifnull,user,convert", dbmd.getSystemFunctions());
assertEquals("getTimeDateFunctions","curdate,curtime,dayname,dayofmonth,dayofweek,dayofyear,hour,minute,month,monthname,now,quarter,timestampadd,timestampdiff,second,week,year", dbmd.getTimeDateFunctions());
assertNotNull("getURL", dbmd.getURL());
assertNotNull("getUserName", dbmd.getUserName());
if (dbmd.getDatabaseProductName().startsWith("Microsoft")) {
assertEquals("getStringFunctions","ascii,char,concat,difference,insert,lcase,left,length,locate,ltrim,repeat,replace,right,rtrim,soundex,space,substring,ucase", dbmd.getStringFunctions());
} else {
assertEquals("getStringFunctions","ascii,char,concat,difference,insert,lcase,length,ltrim,repeat,right,rtrim,soundex,space,substring,ucase", dbmd.getStringFunctions());
}
}
/**
* Test meta data function that return integer values.
* @throws Exception
*/
public void testIntOptions() throws Exception {
DatabaseMetaData dbmd = con.getMetaData();
int sysnamelen = (dbmd.getDatabaseProductName().startsWith("Microsoft"))? 128: 30;
assertEquals("getDefaultTransactionIsolation",Connection.TRANSACTION_READ_COMMITTED, dbmd.getDefaultTransactionIsolation());
assertTrue("getDriverMajorVersion", dbmd.getDriverMajorVersion() >= 0);
assertTrue("getDriverMinorVersion", dbmd.getDriverMinorVersion() >=0);
assertEquals("getMaxBinaryLiteralLength", 131072, dbmd.getMaxBinaryLiteralLength());
assertEquals("getMaxCatalogNameLength",sysnamelen, dbmd.getMaxCatalogNameLength());
assertEquals("getMaxCharLiteralLength", 131072, dbmd.getMaxCharLiteralLength());
assertEquals("getMaxColumnNameLength",sysnamelen, dbmd.getMaxColumnNameLength());
assertEquals("getMaxColumnsInIndex",16, dbmd.getMaxColumnsInIndex());
assertEquals("getMaxColumnsInSelect",4096, dbmd.getMaxColumnsInSelect());
assertEquals("getMaxConnections",32767, dbmd.getMaxConnections());
assertEquals("getMaxCursorNameLength",sysnamelen, dbmd.getMaxCursorNameLength());
assertEquals("getMaxProcedureNameLength",sysnamelen, dbmd.getMaxProcedureNameLength());
assertEquals("getMaxSchemaNameLength",sysnamelen, dbmd.getMaxSchemaNameLength());
assertEquals("getMaxStatementLength",0, dbmd.getMaxStatementLength());
assertEquals("getMaxStatements", 0, dbmd.getMaxStatements());
assertEquals("getMaxTableNameLength",sysnamelen, dbmd.getMaxTableNameLength());
assertEquals("getMaxUserNameLength",sysnamelen, dbmd.getMaxUserNameLength());
if (dbmd.getDatabaseProductName().startsWith("Microsoft")) {
assertEquals("getMaxColumnsInGroupBy",0, dbmd.getMaxColumnsInGroupBy());
assertEquals("getMaxColumnsInOrderBy",0, dbmd.getMaxColumnsInOrderBy());
assertEquals("getMaxColumnsInTable",1024, dbmd.getMaxColumnsInTable());
assertEquals("getMaxIndexLength", 900, dbmd.getMaxIndexLength());
assertEquals("getMaxRowSize",8060, dbmd.getMaxRowSize());
assertEquals("getMaxTablesInSelect",256, dbmd.getMaxTablesInSelect());
} else {
assertEquals("getMaxColumnsInGroupBy",16, dbmd.getMaxColumnsInGroupBy());
assertEquals("getMaxColumnsInOrderBy",16, dbmd.getMaxColumnsInOrderBy());
assertEquals("getMaxColumnsInTable", 250, dbmd.getMaxColumnsInTable());
assertEquals("getMaxIndexLength", 255, dbmd.getMaxIndexLength());
assertEquals("getMaxRowSize",1962, dbmd.getMaxRowSize());
assertEquals("getMaxTablesInSelect",16, dbmd.getMaxTablesInSelect());
}
}
/**
* Test meta data functions that return result sets.
* @throws Exception
*/
public void testResultSets() throws Exception
{
try {
DatabaseMetaData dbmd = con.getMetaData();
ResultSet rs;
Statement stmt = con.createStatement();
dropTable("jTDS_META2");
dropTable("jTDS_META");
dropProcedure("jtds_spmeta");
//
// Create test data
//
stmt.execute("CREATE PROC jtds_spmeta @p1 int, @p2 varchar(30) output AS SELECT @p2 = 'test'");
stmt.execute("CREATE TABLE jTDS_META (id int NOT NULL primary key , data nvarchar(255) NULL, ts timestamp)");
stmt.execute("CREATE TABLE jTDS_META2 (id int NOT NULL, data2 varchar(255) NULL "+
", FOREIGN KEY (id) REFERENCES jTDS_META(id)) ");
//
rs = dbmd.getBestRowIdentifier(null, null, "jTDS_META", DatabaseMetaData.bestRowUnknown, true);
assertTrue(checkColumnNames(rs, new String[]{"SCOPE", "COLUMN_NAME", "DATA_TYPE",
"TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH",
"DECIMAL_DIGITS","PSEUDO_COLUMN"}));
assertTrue(rs.next());
assertEquals("id", rs.getString(2));
//
rs = dbmd.getCatalogs();
assertTrue(checkColumnNames(rs, new String[]{"TABLE_CAT"}));
boolean fail = true;
while (rs.next()) {
if (rs.getString(1).equalsIgnoreCase("master")) {
fail=false;
break;
}
}
assertTrue(!fail);
//
rs = dbmd.getColumnPrivileges(null, null, "jTDS_META", "id");
assertTrue(checkColumnNames(rs, new String[]{"TABLE_CAT","TABLE_SCHEM","TABLE_NAME",
"COLUMN_NAME","GRANTOR","GRANTEE","PRIVILEGE","IS_GRANTABLE"}));
assertTrue(rs.next());
assertTrue(rs.getString(7).equals("INSERT") ||
rs.getString(7).equals("UPDATE") ||
rs.getString(7).equals("DELETE") ||
rs.getString(7).equals("SELECT"));
//
rs = dbmd.getColumns(null, null, "jTDS_META", "%");
assertTrue(checkColumnNames(rs, new String[]{"TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME",
"COLUMN_NAME", "DATA_TYPE", "TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH",
"DECIMAL_DIGITS","NUM_PREC_RADIX", "NULLABLE","REMARKS","COLUMN_DEF",
"SQL_DATA_TYPE","SQL_DATETIME_SUB","CHAR_OCTET_LENGTH","ORDINAL_POSITION",
"IS_NULLABLE","SCOPE_CATALOG","SCOPE_SCHEMA","SCOPE_TABLE","SOURCE_DATA_TYPE"}));
assertTrue(rs.next());
assertEquals("id", rs.getString(4));
assertEquals(java.sql.Types.INTEGER, rs.getInt(5));
assertTrue(rs.next());
assertEquals("data", rs.getString(4));
assertEquals(java.sql.Types.VARCHAR, rs.getInt(5));
//
rs = dbmd.getCrossReference(null, null, "jTDS_META", null, null, "jTDS_META2");
assertTrue(checkColumnNames(rs, new String[]{"PKTABLE_CAT", "PKTABLE_SCHEM", "PKTABLE_NAME","PKCOLUMN_NAME",
"FKTABLE_CAT", "FKTABLE_SCHEM", "FKTABLE_NAME","FKCOLUMN_NAME",
"KEY_SEQ","UPDATE_RULE","DELETE_RULE","FK_NAME","PK_NAME","DEFERRABILITY"}));
assertTrue(rs.next());
assertEquals("id", rs.getString(4));
//
rs = dbmd.getExportedKeys(null, null, "jTDS_META");
assertTrue(checkColumnNames(rs, new String[]{"PKTABLE_CAT", "PKTABLE_SCHEM", "PKTABLE_NAME","PKCOLUMN_NAME",
"FKTABLE_CAT", "FKTABLE_SCHEM", "FKTABLE_NAME","FKCOLUMN_NAME",
"KEY_SEQ","UPDATE_RULE","DELETE_RULE","FK_NAME","PK_NAME","DEFERRABILITY"}));
assertTrue(rs.next());
assertEquals("id", rs.getString(4));
//
rs = dbmd.getImportedKeys(null, null, "jTDS_META2");
assertTrue(checkColumnNames(rs, new String[]{"PKTABLE_CAT", "PKTABLE_SCHEM", "PKTABLE_NAME","PKCOLUMN_NAME",
"FKTABLE_CAT", "FKTABLE_SCHEM", "FKTABLE_NAME","FKCOLUMN_NAME",
"KEY_SEQ","UPDATE_RULE","DELETE_RULE","FK_NAME","PK_NAME","DEFERRABILITY"}));
assertTrue(rs.next());
assertEquals("id", rs.getString(4));
//
rs = dbmd.getIndexInfo(null, null, "jTDS_META", false, true);
assertTrue(checkColumnNames(rs, new String[]{"TABLE_CAT","TABLE_SCHEM","TABLE_NAME","NON_UNIQUE",
"INDEX_QUALIFIER","INDEX_NAME","TYPE","ORDINAL_POSITION", "COLUMN_NAME",
"ASC_OR_DESC","CARDINALITY","PAGES","FILTER_CONDITION"}));
assertTrue(rs.next());
assertEquals("jTDS_META", rs.getString(3));
//
rs = dbmd.getPrimaryKeys(null, null, "jTDS_META");
assertTrue(checkColumnNames(rs, new String[]{"TABLE_CAT","TABLE_SCHEM","TABLE_NAME","COLUMN_NAME","KEY_SEQ", "PK_NAME"}));
assertTrue(rs.next());
assertEquals("id", rs.getString(4));
//
rs = dbmd.getProcedureColumns(null, null, "jtds_spmeta", "@p1");
assertTrue(checkColumnNames(rs, new String[]{"PROCEDURE_CAT", "PROCEDURE_SCHEM", "PROCEDURE_NAME",
"COLUMN_NAME", "COLUMN_TYPE","DATA_TYPE","TYPE_NAME","PRECISION",
"LENGTH","SCALE","RADIX","NULLABLE","REMARKS"}));
assertTrue(rs.next());
assertEquals("jtds_spmeta", rs.getString(3));
assertEquals("@p1", rs.getString(4));
//
rs = dbmd.getProcedures(null, null, "jtds_spmeta%");
assertTrue(checkColumnNames(rs, new String[]{"PROCEDURE_CAT", "PROCEDURE_SCHEM", "PROCEDURE_NAME",
"","","","REMARKS","PROCEDURE_TYPE"}));
assertTrue(rs.next());
assertEquals("jtds_spmeta", rs.getString(3));
//
rs = dbmd.getSchemas();
if (net.sourceforge.jtds.jdbc.Driver.JDBC3) {
assertTrue(checkColumnNames(rs, new String[]{"TABLE_SCHEM","TABLE_CATALOG"}));
} else {
assertTrue(checkColumnNames(rs, new String[]{"TABLE_SCHEM"}));
}
assertTrue(rs.next());
//
rs = dbmd.getTablePrivileges(null, null, "jTDS_META");
assertTrue(checkColumnNames(rs, new String[]{"TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME",
"GRANTOR", "GRANTEE","PRIVILEGE", "IS_GRANTABLE"}));
assertTrue(rs.next());
assertTrue(rs.getString(6).equals("INSERT") ||
rs.getString(6).equals("UPDATE") ||
rs.getString(6).equals("DELETE") ||
rs.getString(6).equals("SELECT"));
//
rs = dbmd.getTables(null, null, "jTDS_META", new String[]{"TABLE"});
assertTrue(checkColumnNames(rs, new String[]{"TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME",
"TABLE_TYPE","REMARKS","TYPE_CAT","TYPE_SCHEM","TYPE_NAME",
"SELF_REFERENCING_COL_NAME","REF_GENERATION"}));
assertTrue(rs.next());
assertEquals("jTDS_META", rs.getString(3));
//
rs = dbmd.getTableTypes();
assertTrue(checkColumnNames(rs, new String[]{"TABLE_TYPE"}));
assertTrue(rs.next());
assertEquals("SYSTEM TABLE", rs.getString(1));
//
rs = dbmd.getTypeInfo();
assertTrue(checkColumnNames(rs, new String[]{"TYPE_NAME","DATA_TYPE","PRECISION","LITERAL_PREFIX",
"LITERAL_SUFFIX", "CREATE_PARAMS","NULLABLE","CASE_SENSITIVE","SEARCHABLE",
"UNSIGNED_ATTRIBUTE","FIXED_PREC_SCALE","AUTO_INCREMENT","LOCAL_TYPE_NAME",
"MINIMUM_SCALE","MAXIMUM_SCALE","SQL_DATA_TYPE","SQL_DATETIME_SUB","NUM_PREC_RADIX"}));
while (rs.next()) {
if (rs.getString(1).equalsIgnoreCase("nvarchar")) {
assertEquals(java.sql.Types.VARCHAR, rs.getInt(2));
}
}
//
rs = dbmd.getUDTs(null, null, "%", null);
assertTrue(checkColumnNames(rs, new String[]{"TYPE_CAT", "TYPE_SCHEM", "TYPE_NAME", "CLASS_NAME",
"DATA_TYPE","REMARKS","BASE_TYPE"}));
assertFalse(rs.next());
//
rs = dbmd.getVersionColumns(null, null, "jTDS_META");
assertTrue(checkColumnNames(rs, new String[]{"SCOPE", "COLUMN_NAME","DATA_TYPE","TYPE_NAME",
"COLUMN_SIZE","BUFFER_LENGTH","DECIMAL_DIGITS","PSEUDO_COLUMN"}));
assertTrue(rs.next());
assertEquals("ts", rs.getString(2));
} finally {
dropTable("jTDS_META2");
dropTable("jTDS_META");
dropProcedure("jtds_spmeta");
}
}
/**
* Test for bug [974036] Bug in 0.8rc1 DatabaseMetaData method getTableTypes()
*/
public void testGetTableTypesOrder() throws Exception {
DatabaseMetaData dmd = con.getMetaData();
ResultSet rs = dmd.getTableTypes();
String previousType = "";
while (rs.next()) {
String type = rs.getString(1);
assertTrue(type.compareTo(previousType) >= 0);
previousType = type;
}
rs.close();
}
/**
* Test for bug [998765] Exception with Sybase and metaData.getTables()
*/
public void testGetTables() throws Exception {
DatabaseMetaData dmd = con.getMetaData();
ResultSet rs = dmd.getTables(null, null, null, null);
assertNotNull(rs);
rs.close();
}
/**
* Test for bug [1120168] jTDS 101 - TDS data type 0 invalid.
*/
public void testGetColumnsMetaData() throws Exception {
DatabaseMetaData dmd = con.getMetaData();
ResultSet rs = dmd.getColumns(null, null, "Table doesn't exist", null);
assertNotNull(rs);
// Obtain the ResultSetMetaData for the dummy CachedResultSet
ResultSetMetaData rsmd = rs.getMetaData();
// Now call all methods and make sure they don't crash
// For some of them also make simple tests
assertNotNull(rsmd.getCatalogName(1));
assertNotNull(rsmd.getColumnClassName(1));
rsmd.getColumnCount();
assertTrue(0 != rsmd.getColumnDisplaySize(1));
assertNotNull(rsmd.getColumnLabel(1));
assertNotNull(rsmd.getColumnName(1));
rsmd.getColumnType(1);
assertNotNull(rsmd.getColumnTypeName(1));
rsmd.getPrecision(1);
rsmd.getScale(1);
assertNotNull(rsmd.getSchemaName(1));
assertNotNull(rsmd.getTableName(1));
rsmd.isAutoIncrement(1);
rsmd.isCaseSensitive(1);
rsmd.isCurrency(1);
rsmd.isDefinitelyWritable(1);
rsmd.isNullable(1);
rsmd.isReadOnly(1);
rsmd.isSearchable(1);
rsmd.isSigned(1);
rsmd.isWritable(1);
rs.close();
}
/**
* Test for bug [1023984] Protocol error processing table meta data.
* * Test to demonstrate failure to process the TDS table name token * correctly. Must be run with TDS=8.0. * @throws Exception */ public void testTableMetaData() throws Exception { // This test is supposed to select from a different database, in order to // force the server to return a fully qualified table name. Do not alter. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery("SELECT * FROM master.dbo.sysdatabases"); assertNotNull(rs); ResultSetMetaData rsmd = rs.getMetaData(); assertEquals("master", rsmd.getCatalogName(1)); assertEquals("dbo", rsmd.getSchemaName(1)); assertEquals("sysdatabases", rsmd.getTableName(1)); stmt.close(); rs.close(); } public void testColumnClassName() throws SQLException { byte[] bytes = new byte[] {1, 2, 3}; String uid = "colGuid char(38)"; if (con.getMetaData().getDatabaseProductName().startsWith("Microsoft")) { uid = "colGuid UNIQUEIDENTIFIER"; } // Create a table w/ pretty much all the possible types String tabdef = "CREATE TABLE #testColumnClassName(" + "colByte TINYINT," + "colShort SMALLINT," + "colInt INTEGER," + "colBigint DECIMAL(29,0)," + "colFloat REAL," + "colDouble FLOAT," + "colDecimal DECIMAL(29,10)," + "colBit BIT," + "colByteArray VARBINARY(255)," + "colTimestamp DATETIME," + "colBlob IMAGE," + "colClob TEXT," + "colString VARCHAR(255)," + uid + ")"; Statement stmt = con.createStatement(); stmt.executeUpdate(tabdef); // Insert a row into the table PreparedStatement pstmt = con.prepareStatement( "INSERT INTO #testColumnClassName (" + "colByte,colShort,colInt,colBigint,colFloat,colDouble," + "colDecimal,colBit,colByteArray,colTimestamp,colBlob,colClob," + "colString,colGuid) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); pstmt.setByte(1, (byte) 1); pstmt.setShort(2, (short) 2222); pstmt.setInt(3, 123456); pstmt.setInt(4, 123456); pstmt.setFloat(5, 0.111f); pstmt.setDouble(6, 0.111); pstmt.setDouble(7, 0.111111); pstmt.setBoolean(8, true); pstmt.setBytes(9, bytes); pstmt.setTimestamp(10, new Timestamp(System.currentTimeMillis())); pstmt.setBytes(11, bytes); pstmt.setString(12, "Test"); pstmt.setString(13, "Test"); pstmt.setString(14, "ebd558a0-0c68-11d9-9669-0800200c9a66"); assertEquals("No row inserted", 1, pstmt.executeUpdate()); pstmt.close(); // Select the row and check that getColumnClassName matches the actual // class ResultSet rs = stmt.executeQuery("SELECT * FROM #testColumnClassName"); assertTrue("No rows in ResultSet", rs.next()); ResultSetMetaData meta = rs.getMetaData(); for (int i=1; i<=meta.getColumnCount(); i++) { Object obj = rs.getObject(i); assertNotNull("Expecting non-null value", obj); String metaClass = meta.getColumnClassName(i); Class c; try { c = Class.forName(metaClass); } catch (ClassNotFoundException ex) { fail("Class returned by getColumnClassName() not found: " + metaClass); return; } if (!c.isAssignableFrom(obj.getClass())) { fail("getColumnClassName() returned " + metaClass + " but the actual class is " + obj.getClass().getName()); } } stmt.close(); } /** * Test to check DatabaseMetaData.getColumns and ResultSetMetaData is equivalent. * This test also checks for bug [ 1074096 ] Incorrect data type determine on dataset meta data. * This is because getColumns will return a typename of timestamp which should now also be * returned by the result set meta data as well. * @throws Exception if an error condition occurs */ public void testColumnMetaData() throws Exception { String sql = "CREATE TABLE jTDSTYPETEST (ti tinyint not null, si smallint, i int, bi bigint, " + " f float, r real, d decimal(28,10), n numeric(28,10), sm smallmoney, m money, " + "c char(10) not null, vc varchar(255), nc nchar(10) not null, nvc nvarchar(255), " + " txt text, ntxt ntext, b binary(8) not null, vb varbinary(8), img image, " + " dt datetime, sdt smalldatetime, bt bit not null, ts timestamp, sn sysname, "+ " ui uniqueidentifier, sv sql_variant)"; String sql7 = "CREATE TABLE jTDSTYPETEST (ti tinyint not null, si smallint, i int, " + " f float, r real, d decimal(28,10), n numeric(28,10), sm smallmoney, m money, " + "c char(10) not null, vc varchar(255), nc nchar(10) not null, nvc nvarchar(255), " + " txt text, ntxt ntext, b binary(8) not null, vb varbinary(8), img image, " + " dt datetime, sdt smalldatetime, bt bit not null, ts timestamp, sn sysname, "+ " ui uniqueidentifier)"; String sql65 = "CREATE TABLE jTDSTYPETEST (ti tinyint not null, si smallint, i int, " + " f float, r real, d decimal(28,10), n numeric(28,10), sm smallmoney, m money, " + "c char(10) not null, vc varchar(255), " + " txt text, b binary(8) not null, vb varbinary(8), img image, " + " dt datetime, sdt smalldatetime, bt bit not null, ts timestamp, sn sysname)"; String sql125 = "CREATE TABLE jTDSTYPETEST (ti tinyint not null, si smallint, i int, " + " f float, r real, d decimal(28,10), n numeric(28,10), sm smallmoney, m money, " + "c char(10) not null, vc varchar(255), nc nchar(10) not null, nvc nvarchar(255), " + " txt text, b binary(8) not null, vb varbinary(8), img image, " + " dt datetime, sdt smalldatetime, bt bit not null, ts timestamp, sn sysname, "+ " uc unichar(10), vuc univarchar(255), sydt date, syt time)"; try { dropTable("jTDSTYPETEST"); Statement stmt = con.createStatement(); DatabaseMetaData dbmd = con.getMetaData(); if (dbmd.getDatabaseProductName().startsWith("Microsoft")) { if (dbmd.getDatabaseProductVersion().startsWith("6.5")) stmt.execute(sql65); else if (dbmd.getDatabaseProductVersion().startsWith("7")) stmt.execute(sql7); else stmt.execute(sql); } else { if (dbmd.getDatabaseProductVersion().startsWith("12")) stmt.execute(sql125); else stmt.execute(sql65); } ResultSetMetaData rsmd = stmt.executeQuery("SELECT * FROM jTDSTYPETEST").getMetaData(); ResultSet rs = dbmd.getColumns(null, null, "jTDSTYPETEST", "%"); // ResultSetMetaData rsmd2 = rs.getMetaData(); // System.out.println(); while (rs.next()) { String cn = rs.getString("COLUMN_NAME"); int ord = rs.getInt("ORDINAL_POSITION"); assertEquals(cn+" typename", rs.getString("TYPE_NAME"), rsmd.getColumnTypeName(ord)); assertEquals(cn+" datatype", rs.getInt("DATA_TYPE"), rsmd.getColumnType(ord)); if (rs.getInt("DATA_TYPE") != Types.REAL && rs.getInt("DATA_TYPE") != Types.DOUBLE) { // Seems to be genuine disagreement between getColumns and metadata on float data! assertEquals(cn+" precision", rs.getInt("COLUMN_SIZE"), rsmd.getPrecision(ord)); } assertEquals(cn+" scale", rs.getInt("DECIMAL_DIGITS"), rsmd.getScale(ord)); assertEquals(cn+" nullable", rs.getInt("NULLABLE"), rsmd.isNullable(ord)); } } finally { dropTable("jTDSTYPETEST"); } } /** * Test for bug [1833720], invalid table names for large result sets. */ public void testResultSetMetadate() throws Exception { final int rows = 1; final int tables = 10; final int columns = 100; Statement st = con.createStatement(); StringBuffer sb = new StringBuffer(); try { // create tables for (int t=0; t < tables; t++) { sb.setLength(0); sb.append("create table #TABLE"); sb.append(t); sb.append("(ID int primary key"); for (int c=0; c < columns; c++) { sb.append(",COLUMN"); sb.append(c); sb.append(" int"); } sb.append(")"); st.execute(sb.toString()); } // insert data for (int t=0; t < tables; t++) { sb.setLength(0); sb.append("insert into #TABLE"); sb.append(t); sb.append(" values(?"); for (int c=0; c < columns; c++) { sb.append(",?"); } sb.append(")"); PreparedStatement pst = con.prepareStatement(sb.toString()); for (int r = 0; r < rows; r++) { for (int c=0; c <= columns; c++) { pst.setInt(c + 1, r); } pst.addBatch(); } assertEquals(rows, pst.executeBatch().length); } // create select sb.setLength(0); sb.append("select * from "); for (int t=0; t < tables; t++) { sb.append(t > 0 ? "," : ""); sb.append("#TABLE"); sb.append(t); } if (tables > 1) { sb.append(" where "); for (int t=1; t < tables; t++) { sb.append(t > 1 ? " and " : ""); sb.append("#TABLE"); sb.append(t); sb.append(".id="); sb.append("#TABLE"); sb.append(t-1); sb.append(".id"); } } // get result ResultSet rs = st.executeQuery(sb.toString()); ResultSetMetaData rsmd = rs.getMetaData(); int toalColumns = rsmd.getColumnCount(); assertEquals(tables * (columns + 1), toalColumns); for (int r=0; r < rows; r++) { assertTrue(rs.next()); } int index = 0; for (int t=0; t < tables; t++) { for (int c = 1; c <= columns + 1; c++) { index ++; // FIXME: column names are transformed to upper case by jTDS, think that's an error assertEquals(c > 1 ? ("COLUMN" + (c - 2)) : "ID", rsmd.getColumnName(index)); assertEquals(Types.INTEGER, rsmd.getColumnType(index)); // test for bug [1833720] assertEquals("#TABLE" + t, rsmd.getTableName(index)); } } } finally { for (int t=0; t < tables; t++) { dropTable("#TABLE" + t); } } } /** * Test for bug [1184376] Sybase getProcedureColumns bug */ public void testProcedureColumns() throws Exception { try { dropProcedure("jtds_testparam"); Statement stmt = con.createStatement(); stmt.execute("CREATE PROC jtds_testparam @p1 int, @p2 int output as\r\n" + "BEGIN\r\n" + " SELECT @p2 = @p1\r\n" + "END"); stmt.close(); DatabaseMetaData dbmd = con.getMetaData(); String[] columnPatterns = new String[] {null, "%"}; for (int i = 0; i < columnPatterns.length; i++) { ResultSet rs = dbmd.getProcedureColumns(null, null, "jtds_testparam", columnPatterns[i]); assertTrue(rs.next()); assertEquals("@RETURN_VALUE", rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.procedureColumnReturn, rs.getInt("COLUMN_TYPE")); assertTrue(rs.next()); assertEquals("@p1", rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.procedureColumnIn, rs.getInt("COLUMN_TYPE")); assertTrue(rs.next()); assertEquals("@p2", rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.procedureColumnInOut, rs.getInt("COLUMN_TYPE")); rs.close(); } } finally { dropProcedure("jtds_testparam"); } } /** * Test for bug [1245775] Column type inconsistency when useLOBs=false. */ public void testProcedureUseLOBsFalse() throws Exception { Properties props = new Properties(); props.setProperty("useLOBs", "false"); Connection con = getConnection(props); try { DatabaseMetaData meta = con.getMetaData(); ResultSet rs = meta.getTypeInfo(); while (rs.next()) { if ("text".equalsIgnoreCase(rs.getString(1)) || "ntext".equalsIgnoreCase(rs.getString(1))) { assertEquals(Types.LONGVARCHAR, rs.getInt(2)); } else if ("image".equalsIgnoreCase(rs.getString(1))) { assertEquals(Types.LONGVARBINARY, rs.getInt(2)); } } } finally { con.close(); } DatabaseMetaData meta = this.con.getMetaData(); ResultSet rs = meta.getTypeInfo(); while (rs.next()) { if ("text".equalsIgnoreCase(rs.getString(1)) || "ntext".equalsIgnoreCase(rs.getString(1))) { assertEquals(Types.CLOB, rs.getInt(2)); } else if ("image".equalsIgnoreCase(rs.getString(1))) { assertEquals(Types.BLOB, rs.getInt(2)); } } } /** * Test for bug [1825743], default value not returned for column with * default value. */ public void testDefaultValue() throws SQLException { Statement st = con.createStatement(); // try dropping test table try { st.execute("drop TABLE testDefaultValue"); } catch (SQLException e) { // ignored } String[] columns = new String[] { "tinyint", "1", "smallint", "2", "int", "3", "bigint", "4", "float", "5.0", "real", "6.0", "decimal(28,10)", "0.1234567890", "numeric(28,10)", "0.1234567890", "smallmoney", "123.4567", "money", "12345.6789", "bit", "false", "smalldatetime", "1900-01-01 00:00:00.0", "datetime", "1900-01-01 00:00:00.0", "char(10)", "AaBbCcDdEe", "varchar(10)", "FfGgHhIiJj", "nchar(10)", "KkLlMmNnOo", "nvarchar(10)", "PpQqRrSsTt", // "text", "CLOB", // "ntext", "CLOB", // "image", "BLOB", // "binary(10)", "", // "varbinary(10)", "" }; // build and execute CREATE TABLE statement StringBuffer sb = new StringBuffer(); sb.append("CREATE TABLE testDefaultValue ("); for (int i = 0; i < columns.length/2; i++) { sb.append(i == 0 ? "" : ","); sb.append("col"); sb.append(i); sb.append(" "); sb.append(columns[i*2]); sb.append(" default "); sb.append(i > 9 ? "'" : ""); sb.append(columns[i*2+1]); sb.append(i > 9 ? "'" : ""); } sb.append(")"); st.execute(sb.toString()); // check if meta data reports correct defaults ResultSet rs = con.getMetaData().getColumns(null, null, "testDefaultValue", "col%"); for (int i = 0; i < columns.length/2; i++) { assertTrue(rs.next()); assertNotNull(rs.getString("COLUMN_DEF")); assertTrue(rs.getString("COLUMN_DEF").indexOf(columns[i*2+1]) > 0); } rs.close(); // test if the default values are being used assertEquals(1, st.executeUpdate("insert into testDefaultValue (col0) values (" + columns[1] + ")")); rs = st.executeQuery("select * from testDefaultValue"); assertTrue(rs.next()); for (int i = 0; i < columns.length/2; i++) { assertEquals(columns[i*2+1], rs.getObject(i+1).toString()); } rs.close(); st.close(); } public static void main(String[] args) { junit.textui.TestRunner.run(DatabaseMetaDataTest.class); } } libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/DefaultPropertiesTestLibrary.java 0000644 0001750 0001750 00000051424 11316672660 031707 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase // Copyright (C) 2004 The jTDS Project // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // package net.sourceforge.jtds.test; import java.util.Properties; import junit.framework.Test; import junit.framework.TestCase; import net.sourceforge.jtds.jdbc.DefaultProperties; import net.sourceforge.jtds.jdbc.Driver; import net.sourceforge.jtds.jdbc.Messages; /** * Library for testing default properties. *
* Uses a {@link DefaultPropertiesTester} object to test different methods * in different classes. * * To extend this class, the programmer must implement the following items: *#tester field in a public default
* constructor that takes no arguments.public static Test suite() method that takes one or more
* arguments. (The {@link #suite()} method in this class should
* not be overridden.)null).
*/
public static final Test suite() {
return null;
}
/**
* Default constructor.
*
* The extender of this class is required to set the #tester
* field in a public default constructor.
*/
public DefaultPropertiesTestLibrary() {
}
/**
* Test the serverType property.
*
* Different values are set depending on whether SQL Server or
* Sybase is used.
*/
public void test_serverType() {
String fieldName = "serverType";
String messageKey = Driver.SERVERTYPE;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, String.valueOf(Driver.SQLSERVER));
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, String.valueOf(Driver.SYBASE));
}
}
/**
* Test the tds (version) property.
*/
public void test_tds() {
String fieldName = "tdsVersion";
String messageKey = Driver.TDS;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, DefaultProperties.TDS_VERSION_80);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, DefaultProperties.TDS_VERSION_50);
}
}
/**
* Test the portNumber property.
*
* Different values are set depending on whether SQL Server or
* Sybase is used.
*/
public void test_portNumber() {
String fieldName = "portNumber";
String messageKey = Driver.PORTNUMBER;
assertDefaultPropertyByServerType(
URL_SQLSERVER, messageKey, fieldName, DefaultProperties.PORT_NUMBER_SQLSERVER);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(
URL_SYBASE, messageKey, fieldName, DefaultProperties.PORT_NUMBER_SYBASE);
}
}
/**
* Test the databaseName property.
*/
public void test_databaseName() {
String fieldName = "databaseName";
String messageKey = Driver.DATABASENAME;
String expectedValue = DefaultProperties.DATABASE_NAME;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Test the appName property.
*/
public void test_appName() {
String fieldName = "appName";
String messageKey = Driver.APPNAME;
String expectedValue = DefaultProperties.APP_NAME;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Test the bindAddress property.
*/
public void test_bindAddress() {
String fieldName = "bindAddress";
String messageKey = Driver.BINDADDRESS;
String expectedValue = DefaultProperties.BIND_ADDRESS;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Test the lastUpdateCount property.
*/
public void test_lastUpdateCount() {
String fieldName = "lastUpdateCount";
String messageKey = Driver.LASTUPDATECOUNT;
String expectedValue = DefaultProperties.LAST_UPDATE_COUNT;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Test the lobBuffer property.
*/
public void test_lobBuffer() {
String fieldName = "lobBuffer";
String messageKey = Driver.LOBBUFFER;
String expectedValue = DefaultProperties.LOB_BUFFER_SIZE;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Test the loginTimeout property.
*/
public void test_loginTimeout() {
String fieldName = "loginTimeout";
String messageKey = Driver.LOGINTIMEOUT;
String expectedValue = DefaultProperties.LOGIN_TIMEOUT;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Test the socketTimeout property.
*/
public void test_socketTimeout() {
String fieldName = "socketTimeout";
String messageKey = Driver.SOTIMEOUT;
String expectedValue = DefaultProperties.SOCKET_TIMEOUT;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Test the socketKeepAlive property.
*/
public void test_socketKeepAlive() {
String fieldName = "socketKeepAlive";
String messageKey = Driver.SOKEEPALIVE;
String expectedValue = DefaultProperties.SOCKET_KEEPALIVE;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Test the processId property.
*/
public void test_processId() {
String fieldName = "processId";
String messageKey = Driver.PROCESSID;
String expectedValue = DefaultProperties.PROCESS_ID;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Test the macAddress property.
*/
public void test_macAddress() {
String fieldName = "macAddress";
String messageKey = Driver.MACADDRESS;
String expectedValue = DefaultProperties.MAC_ADDRESS;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Test the namedPipe property.
*/
public void test_namedPipe() {
String fieldName = "namedPipe";
String messageKey = Driver.NAMEDPIPE;
String expectedValue = DefaultProperties.NAMED_PIPE;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Test the packetSize property.
*/
public void test_packetSize() {
String fieldName = "packetSize";
String messageKey = Driver.PACKETSIZE;
if (!isOnlyTds70Tests()) {
String expectedValue = DefaultProperties.PACKET_SIZE_42;
assertDefaultPropertyByTdsVersion(
URL_SQLSERVER, DefaultProperties.TDS_VERSION_42, messageKey, fieldName, expectedValue);
expectedValue = DefaultProperties.PACKET_SIZE_50;
assertDefaultPropertyByTdsVersion(
URL_SYBASE, DefaultProperties.TDS_VERSION_50, messageKey, fieldName, expectedValue);
}
String expectedValue = DefaultProperties.PACKET_SIZE_70_80;
assertDefaultPropertyByTdsVersion(
URL_SQLSERVER, DefaultProperties.TDS_VERSION_70, messageKey, fieldName, expectedValue);
if (!isOnlyTds70Tests()) {
assertDefaultPropertyByTdsVersion(
URL_SQLSERVER, DefaultProperties.TDS_VERSION_80, messageKey, fieldName, expectedValue);
}
}
/**
* Test the prepareSql property.
*/
public void test_prepareSql() {
String fieldName = "prepareSql";
String messageKey = Driver.PREPARESQL;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName,
DefaultProperties.PREPARE_SQLSERVER);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName,
DefaultProperties.PREPARE_SYBASE);
}
}
/**
* Test the progName property.
*/
public void test_progName() {
String fieldName = "progName";
String messageKey = Driver.PROGNAME;
String expectedValue = DefaultProperties.PROG_NAME;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Test the sendStringParametersAsUnicode property.
*/
public void test_sendStringParametersAsUnicode() {
String fieldName = "sendStringParametersAsUnicode";
String messageKey = Driver.SENDSTRINGPARAMETERSASUNICODE;
String expectedValue = DefaultProperties.USE_UNICODE;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Test the batchSize property.
*/
public void test_batchSize() {
String fieldName = "batchSize";
String messageKey = Driver.BATCHSIZE;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName,
DefaultProperties.BATCH_SIZE_SQLSERVER);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName,
DefaultProperties.BATCH_SIZE_SYBASE);
}
}
/**
* Test the bufferDir property.
*/
public void test_bufferDir() {
String fieldName = "bufferDir";
String messageKey = Driver.BUFFERDIR;
String expectedValue = DefaultProperties.BUFFER_DIR;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Test the bufferMaxMemory property.
*/
public void test_bufferMaxMemory() {
String fieldName = "bufferMaxMemory";
String messageKey = Driver.BUFFERMAXMEMORY;
String expectedValue = DefaultProperties.BUFFER_MAX_MEMORY;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Test the bufferMinPackets property.
*/
public void test_bufferMinPackets() {
String fieldName = "bufferMinPackets";
String messageKey = Driver.BUFFERMINPACKETS;
String expectedValue = DefaultProperties.BUFFER_MIN_PACKETS;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Test the cacheMetaData property.
*/
public void test_cacheMetaData() {
String fieldName = "useMetadataCache";
String messageKey = Driver.CACHEMETA;
String expectedValue = DefaultProperties.CACHEMETA;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Test the tcpNoDelay property.
*/
public void test_tcpNoDelay() {
String fieldName = "tcpNoDelay";
String messageKey = Driver.TCPNODELAY;
String expectedValue = DefaultProperties.TCP_NODELAY;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Test the useCursors property.
*/
public void test_useCursors() {
String fieldName = "useCursors";
String messageKey = Driver.USECURSORS;
String expectedValue = DefaultProperties.USECURSORS;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Test the useJCIFS property.
*/
public void test_useJCIFS() {
String fieldName = "useJCIFS";
String messageKey = Driver.USEJCIFS;
String expectedValue = DefaultProperties.USEJCIFS;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Test the useLOBs property.
*/
public void test_useLOBs() {
String fieldName = "useLOBs";
String messageKey = Driver.USELOBS;
String expectedValue = DefaultProperties.USELOBS;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Test the wsid property.
*/
public void test_wsid() {
String fieldName = "wsid";
String messageKey = Driver.WSID;
String expectedValue = DefaultProperties.WSID;
assertDefaultPropertyByServerType(URL_SQLSERVER, messageKey, fieldName, expectedValue);
if (!isOnlySqlServerTests()) {
assertDefaultPropertyByServerType(URL_SYBASE, messageKey, fieldName, expectedValue);
}
}
/**
* Assert that the expected property value is set using
* a given url and tdsVersion property.
*
* @param url The JDBC URL.
* @param tdsVersion The TDS version.
* @param key The message key.
* @param fieldName The field name used in the class.
* @param expected The expected value of the property.
*/
private void assertDefaultPropertyByTdsVersion(
String url, String tdsVersion, String key, String fieldName, String expected) {
Properties properties = new Properties();
properties.setProperty(Messages.get(Driver.TDS), tdsVersion);
getTester().assertDefaultProperty("Default property incorrect", url, properties, fieldName, key, expected);
}
/**
* Assert that the expected property value is set using
* a given url.
*
* @param url The JDBC URL.
* @param key The message key.
* @param fieldName The field name used in the class.
* @param expected The expected value of the property.
*/
private void assertDefaultPropertyByServerType(String url, String key, String fieldName, String expected) {
getTester().assertDefaultProperty("Default property incorrect", url, new Properties(), fieldName, key, expected);
}
/**
* Getter for {@link #tester}.
*
* @return Value of {@link #tester}.
*/
protected DefaultPropertiesTester getTester() {
return tester;
}
/**
* Setter for #tester.
*
* @param tester The value to set #tester to.
*/
public void setTester(DefaultPropertiesTester tester) {
this.tester = tester;
}
/**
* Getter for #onlySqlServerTests.
*
* @return Value of #onlySqlServerTests.
*/
public boolean isOnlySqlServerTests() {
return onlySqlServerTests;
}
/**
* Setter for {@link #onlySqlServerTests}.
*
* @param onlySqlServerTests The value to set {@link #onlySqlServerTests} to.
*/
protected void setOnlySqlServerTests(boolean onlySqlServerTests) {
this.onlySqlServerTests = onlySqlServerTests;
}
/**
* Getter for #onlyTds70Tests.
*
* @return Value of #onlyTds70Tests.
*/
public boolean isOnlyTds70Tests() {
return onlyTds70Tests;
}
/**
* Setter for {@link #onlyTds70Tests}.
*
* @param onlyTds70Tests The value to set {@link #onlyTds70Tests} to.
*/
protected void setOnlyTds70Tests(boolean onlyTds70Tests) {
this.onlyTds70Tests = onlyTds70Tests;
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/CSUnitTest.java 0000644 0001750 0001750 00000171706 11316672660 026074 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.sql.*;
import java.math.BigDecimal;
import junit.framework.TestSuite;
import java.io.*;
import net.sourceforge.jtds.util.Logger;
/**
*
* @author Alin Sinpalean
* @version $Id: CSUnitTest.java,v 1.12.6.2 2009/11/06 08:24:24 ickzon Exp $
*/
public class CSUnitTest extends DatabaseTestCase {
public CSUnitTest(String name) {
super(name);
if (output == null)
try {
output = new PrintStream(new FileOutputStream("nul"));
} catch (FileNotFoundException ex) {
throw new RuntimeException("could not create device nul");
}
}
static PrintStream output = null;
public static void main(String args[]) {
Logger.setActive(true);
if (args.length > 0) {
output = System.out;
junit.framework.TestSuite s = new TestSuite();
for (int i = 0; i < args.length; i++) {
s.addTest(new CSUnitTest(args[i]));
}
junit.textui.TestRunner.run(s);
} else {
junit.textui.TestRunner.run(CSUnitTest.class);
}
}
public void testMaxRows0003() throws Exception {
dropTable("#t0003");
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0003 "
+ " (i integer not null) ");
stmt.close();
PreparedStatement pstmt = con.prepareStatement(
"insert into #t0003 values (?)");
final int rowsToAdd = 100;
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pstmt.setInt(1, i);
count += pstmt.executeUpdate();
}
assertEquals("count: " + count + " rowsToAdd: " + rowsToAdd, rowsToAdd, count);
pstmt.close();
pstmt = con.prepareStatement("select i from #t0003 order by i");
int rowLimit = 32;
pstmt.setMaxRows(rowLimit);
assertTrue(pstmt.getMaxRows() == rowLimit);
ResultSet rs = pstmt.executeQuery();
count = 0;
while (rs.next()) {
count++;
assertEquals(rs.getInt("i"), count);
}
pstmt.close();
assertEquals(rowLimit, count);
}
public void testGetAsciiStream0018() throws Exception {
Statement stmt = con.createStatement();
ResultSet rs;
String bigtext1 =
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"";
String bigimage1 = "0x" +
"0123456789abcdef" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"fedcba9876543210" +
"";
dropTable("#t0018");
String sql =
"create table #t0018 ( " +
" mybinary binary(5) not null, " +
" myvarbinary varbinary(4) not null, " +
" mychar char(10) not null, " +
" myvarchar varchar(8) not null, " +
" mytext text not null, " +
" myimage image not null, " +
" mynullbinary binary(3) null, " +
" mynullvarbinary varbinary(6) null, " +
" mynullchar char(10) null, " +
" mynullvarchar varchar(40) null, " +
" mynulltext text null, " +
" mynullimage image null) ";
assertEquals(stmt.executeUpdate(sql), 0);
// Insert a row without nulls via a Statement
sql =
"insert into #t0018( " +
" mybinary, " +
" myvarbinary, " +
" mychar, " +
" myvarchar, " +
" mytext, " +
" myimage, " +
" mynullbinary, " +
" mynullvarbinary, " +
" mynullchar, " +
" mynullvarchar, " +
" mynulltext, " +
" mynullimage " +
") " +
"values( " +
" 0xffeeddccbb, " + // mybinary
" 0x78, " + // myvarbinary
" 'Z', " + // mychar
" '', " + // myvarchar
" '" + bigtext1 + "', " + // mytext
" " + bigimage1 + ", " + // myimage
" null, " + // mynullbinary
" null, " + // mynullvarbinary
" null, " + // mynullchar
" null, " + // mynullvarchar
" null, " + // mynulltext
" null " + // mynullimage
")";
assertEquals(stmt.executeUpdate(sql), 1);
sql = "select * from #t0018";
rs = stmt.executeQuery(sql);
if (!rs.next()) {
fail("should get Result");
} else {
output.println("Getting the results");
output.println("mybinary is " + rs.getObject("mybinary"));
output.println("myvarbinary is " + rs.getObject("myvarbinary"));
output.println("mychar is " + rs.getObject("mychar"));
output.println("myvarchar is " + rs.getObject("myvarchar"));
output.println("mytext is " + rs.getObject("mytext"));
output.println("myimage is " + rs.getObject("myimage"));
output.println("mynullbinary is " + rs.getObject("mynullbinary"));
output.println("mynullvarbinary is " + rs.getObject("mynullvarbinary"));
output.println("mynullchar is " + rs.getObject("mynullchar"));
output.println("mynullvarchar is " + rs.getObject("mynullvarchar"));
output.println("mynulltext is " + rs.getObject("mynulltext"));
output.println("mynullimage is " + rs.getObject("mynullimage"));
}
stmt.close();
}
public void testMoneyHandling0019() throws Exception {
java.sql.Statement stmt;
int i;
BigDecimal money[] = {
new BigDecimal("922337203685477.5807"),
new BigDecimal("-922337203685477.5807"),
new BigDecimal("1.0000"),
new BigDecimal("0.0000"),
new BigDecimal("-1.0000")
};
BigDecimal smallmoney[] = {
new BigDecimal("214748.3647"),
new BigDecimal("-214748.3648"),
new BigDecimal("1.0000"),
new BigDecimal("0.0000"),
new BigDecimal("-1.0000")
};
if (smallmoney.length != money.length) {
throw new SQLException("Must have same number of elements in " +
"money and smallmoney");
}
stmt = con.createStatement();
dropTable("#t0019");
stmt.executeUpdate("create table #t0019 ( " +
" i integer primary key, " +
" mymoney money not null, " +
" mysmallmoney smallmoney not null) " +
"");
for (i=0; iSupport.calculateNamedPipeBufferSize(int, int)
* sets the buffer size appropriately for TDS 4.2 when the packet
* size is set to 0.
*/
public void testCalculateBufferSize_TDS42() {
int length = invoke_calculateBufferSize(Driver.TDS42, 0);
assertEquals(TdsCore.MIN_PKT_SIZE, length);
}
/**
* Test that Support.calculateNamedPipeBufferSize(int, int)
* sets the buffer size appropriately for TDS 5.0 when the packet
* size is set to 0.
*/
public void testCalculateBufferSize_TDS50() {
int length = invoke_calculateBufferSize(Driver.TDS50, 0);
assertEquals(TdsCore.MIN_PKT_SIZE, length);
}
/**
* Test that Support.calculateNamedPipeBufferSize(int, int)
* sets the buffer size appropriately for TDS 7.0 when the packet
* size is set to 0.
*/
public void testCalculateBufferSize_TDS70() {
int length = invoke_calculateBufferSize(Driver.TDS70, 0);
assertEquals(TdsCore.DEFAULT_MIN_PKT_SIZE_TDS70, length);
}
/**
* Test that Support.calculateNamedPipeBufferSize(int, int)
* sets the buffer size appropriately for TDS 8.0 when the packet
* size is set to 0.
*/
public void testCalculateBufferSize_TDS80() {
int length = invoke_calculateBufferSize(Driver.TDS80, 0);
assertEquals(TdsCore.DEFAULT_MIN_PKT_SIZE_TDS70, length);
}
/**
* Helper method to invoke {@link Support#calculateNamedPipeBufferSize(int, int)}
* using reflection.
*
* @param tdsVersion The TDS version as an int.
* @param packetSize The packet size as an int.
* @return Result of calling {@link Support#calculateNamedPipeBufferSize(int, int)}.
*/
private int invoke_calculateBufferSize(int tdsVersion, int packetSize) {
Class[] classes = new Class[]{int.class, int.class};
Object[] objects = new Object[]{new Integer(tdsVersion), new Integer(packetSize)};
return ((Integer) invokeStaticMethod(Support.class,
"calculateNamedPipeBufferSize", classes, objects)).intValue();
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/SAfeTest.java 0000644 0001750 0001750 00000205475 11316672660 025546 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.sql.*;
import java.math.BigDecimal;
import junit.framework.TestSuite;
import net.sourceforge.jtds.util.Logger;
import net.sourceforge.jtds.jdbc.Driver;
import net.sourceforge.jtds.jdbc.Messages;
import java.text.SimpleDateFormat;
import java.util.Vector;
/**
* @author Alin Sinpalean
* @version $Id: SAfeTest.java,v 1.62.2.1 2009/08/04 10:33:54 ickzon Exp $
* @since 0.4
*/
public class SAfeTest extends DatabaseTestCase {
public SAfeTest(String name) {
super(name);
}
public static void main(String args[]) {
Logger.setActive(true);
if (args.length > 0) {
junit.framework.TestSuite s = new TestSuite();
for (int i=0; iCursorResultSet concurrency. Create a number of threads that execute concurrent queries using
* scrollable result sets. All requests should be run on the same connection (Tds instance).
*/
public void testCursorResultSetConcurrency0003() throws Exception {
Statement stmt0 = con.createStatement();
stmt0.execute(
"create table #SAfe0003(id int primary key, val varchar(20) null)");
stmt0.execute(
"insert into #SAfe0003 values (1, 'Line 1') "+
"insert into #SAfe0003 values (2, 'Line 2')");
while (stmt0.getMoreResults() || stmt0.getUpdateCount() != -1);
final Object o1=new Object(), o2=new Object();
int threadCount = 25;
Thread threads[] = new Thread[threadCount];
started = done = 0;
failed = false;
for (int i=0; iisAfterLast,
* isFirst and isLast methods work for
* forward-only, read-only result sets (bug [1039876] MS SQL
* JtdsResultSet.isAfterLast() always returns false).
*
* @throws Exception if an error condition occurs
*/
public void testPlainResultSetPosition0004() throws Exception {
Statement stmt = con.createStatement();
// Try with an empty ResultSet
ResultSet rs = stmt.executeQuery("SELECT 5 Value WHERE 1=0");
assertEquals(null, stmt.getWarnings());
assertEquals(null, rs.getWarnings());
assertEquals("Value", rs.getMetaData().getColumnName(1));
assertTrue(!rs.isBeforeFirst());
assertTrue(!rs.isAfterLast());
assertTrue(!rs.isFirst());
assertTrue(!rs.isLast());
rs.next();
assertTrue(!rs.isBeforeFirst());
assertTrue(!rs.isAfterLast());
assertTrue(!rs.isFirst());
assertTrue(!rs.isLast());
rs.close();
// Try with a non-empty ResultSet
rs = stmt.executeQuery("SELECT 5 Value");
assertEquals(null, stmt.getWarnings());
assertEquals(null, rs.getWarnings());
assertEquals("Value", rs.getMetaData().getColumnName(1));
assertTrue(rs.isBeforeFirst());
assertTrue(!rs.isAfterLast());
assertTrue(!rs.isFirst());
assertTrue(!rs.isLast());
rs.next();
assertTrue(!rs.isBeforeFirst());
assertTrue(!rs.isAfterLast());
assertTrue(rs.isFirst());
assertTrue(rs.isLast());
rs.next();
assertTrue(!rs.isBeforeFirst());
assertTrue(rs.isAfterLast());
assertTrue(!rs.isFirst());
assertTrue(!rs.isLast());
rs.close();
stmt.close();
}
/**
* Check that values returned from bit fields are correct (not just 0) (bug #841670).
*
* @throws Exception
*/
public void testBitFields0005() throws Exception {
Statement stmt = con.createStatement();
stmt.execute(
"create table #SAfe0005(id int primary key, bit1 bit not null, bit2 bit not null)");
stmt.execute(
"insert into #SAfe0005 values (0, 0, 0) "+
"insert into #SAfe0005 values (1, 1, 1) "+
"insert into #SAfe0005 values (2, 0, 0)");
while (stmt.getMoreResults() || stmt.getUpdateCount() != -1);
ResultSet rs = stmt.executeQuery("SELECT * FROM #SAfe0005");
while (rs.next()) {
int id = rs.getInt(1);
int bit1 = rs.getInt(2);
int bit2 = rs.getInt(3);
assertTrue("id: " + id + "; bit1: " + bit1 + "; bit2: " + bit2,
bit1 == id % 2 && (bit2 == id || id == 2 && bit2 == 0));
}
rs.close();
stmt.close();
}
/**
* Test that CallableStatements with return values work correctly.
*
* @throws Exception
*/
public void testCallableStatement0006() throws Exception {
final int myVal = 13;
Statement stmt = con.createStatement();
stmt.execute("CREATE PROCEDURE #SAfe0006 @p1 INT, @p2 VARCHAR(20) OUT AS "
+ "SELECT @p2=CONVERT(VARCHAR(20), @p1-1) "
+ "SELECT @p1 AS value "
+ "RETURN @p1+1");
stmt.close();
// Try all formats: escaped, w/ exec and w/o exec
String[] sql = {"{?=call #SAfe0006(?,?)}", "exec ?=#SAfe0006 ?,?", "?=#SAfe0006 ?,?"};
for (int i = 0; i < sql.length; i++) {
// Execute it using executeQuery
CallableStatement cs = con.prepareCall(sql[i]);
cs.registerOutParameter(1, Types.INTEGER);
cs.setInt(2, myVal);
cs.registerOutParameter(3, Types.VARCHAR);
cs.executeQuery().close();
assertFalse(cs.getMoreResults());
assertEquals(-1, cs.getUpdateCount());
assertEquals(myVal+1, cs.getInt(1));
assertEquals(String.valueOf(myVal-1), cs.getString(3));
cs.close();
// Now use execute
cs = con.prepareCall(sql[i]);
cs.registerOutParameter(1, Types.INTEGER);
cs.setInt(2, myVal);
cs.registerOutParameter(3, Types.VARCHAR);
assertTrue(cs.execute());
cs.getResultSet().close();
assertFalse(cs.getMoreResults());
assertEquals(-1, cs.getUpdateCount());
assertEquals(myVal+1, cs.getInt(1));
assertEquals(String.valueOf(myVal-1), cs.getString(3));
cs.close();
}
}
/**
* Helper method for testBigDecimal0007. Inserts a BigDecimal
* value obtained from a double value.
*
* @param stmt PreparedStatement instance
* @param val the double value to insert
* @param scaleFlag if true scale the value to 4, otherwise
* leave it as it is
*/
private static void insertBigDecimal(PreparedStatement stmt, double val,
boolean scaleFlag)
throws Exception {
BigDecimal bd = new BigDecimal(val);
if (scaleFlag) {
bd = bd.setScale(4,
BigDecimal.ROUND_HALF_EVEN);
}
stmt.setBigDecimal(1, bd);
stmt.execute();
int rowCount = stmt.getUpdateCount();
assertEquals(1, rowCount);
assertTrue(stmt.getMoreResults());
ResultSet rs = stmt.getResultSet();
assertTrue(rs.next());
assertEquals("Values don't match.", val, rs.getDouble(1), 0);
}
/**
* Test BigDecimals created from double values (i.e with very
* large scales).
*/
public void testBigDecimal0007() throws Exception {
Statement createStmt = con.createStatement();
createStmt.execute("CREATE TABLE #SAfe0007(value MONEY)");
createStmt.close();
PreparedStatement stmt = con.prepareStatement(
"INSERT INTO #SAfe0007(value) VALUES (?) "
+ "SELECT * FROM #SAfe0007 DELETE #SAfe0007");
// Now test with certain values.
insertBigDecimal(stmt, 1.1, false);
insertBigDecimal(stmt, 0.1, false);
insertBigDecimal(stmt, 0.1, true);
insertBigDecimal(stmt, 0.01, false);
insertBigDecimal(stmt, 0.01, true);
insertBigDecimal(stmt, 0.02, false);
insertBigDecimal(stmt, 0.02, true);
insertBigDecimal(stmt, 0.25, false);
stmt.close();
}
/**
* Test writing long values to VARCHAR fields. There was a
* regression introduced in release 0.6 that caused long
* fields to be sent with non-zero scale and appear with decimals when
* written into VARCHAR fields.
*/
public void testLongToVarchar0008() throws Exception {
long myVal = 13;
Statement createStmt = con.createStatement();
createStmt.execute("CREATE TABLE #SAfe0008(value VARCHAR(255))");
createStmt.close();
PreparedStatement stmt = con.prepareStatement(
"INSERT INTO #SAfe0008(value) values (CONVERT(VARCHAR(255), ?)) "
+ "SELECT * FROM #SAfe0008 DELETE #SAfe0008");
stmt.setLong(1, myVal);
stmt.execute();
int rowCount = stmt.getUpdateCount();
assertEquals(1, rowCount);
assertTrue(stmt.getMoreResults());
ResultSet rs = stmt.getResultSet();
assertTrue(rs.next());
assertEquals("Values don't match.",
String.valueOf(myVal), rs.getString(1));
stmt.close();
}
/**
* Test ResultSet.deleteRow() on updateable result sets.
*/
public void testDeleteRow0009() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #SAfe0009(value VARCHAR(255) PRIMARY KEY)");
stmt.close();
PreparedStatement insStmt = con.prepareStatement(
"INSERT INTO #SAfe0009(value) values (?)");
insStmt.setString(1, "Row 1");
assertEquals(1, insStmt.executeUpdate());
insStmt.setString(1, "Row 2");
assertEquals(1, insStmt.executeUpdate());
insStmt.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT * FROM #SAfe0009 ORDER BY 1");
assertEquals(null, stmt.getWarnings());
assertEquals(null, rs.getWarnings());
assertTrue(rs.last());
assertTrue(!rs.rowDeleted());
rs.deleteRow();
assertTrue(rs.rowDeleted());
rs.close();
rs = stmt.executeQuery("SELECT * FROM #SAfe0009");
assertTrue(rs.next());
assertEquals("Row 1", rs.getString(1));
assertTrue(!rs.next());
rs.close();
stmt.close();
}
/**
* Test VARCHAR output parameters returned by CallableStatements.
*
* An issue existed, caused by the fact that the parameter was sent to SQL
* Server as a short VARCHAR (not XORed with 0x80) limiting its length to
* 255 characters. See bug [815348] for more details.
*/
public void testCallableStatementVarchar0010() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE PROCEDURE #SAfe0010 @p1 VARCHAR(255) OUT AS "
+ "SELECT @p1 = @p1 + @p1 "
+ "SELECT @p1 = @p1 + @p1 "
+ "SELECT @p1 = @p1 + @p1 "
+ "SELECT @p1 AS value "
+ "RETURN 255");
stmt.close();
// 256 characters long string
String myVal = "01234567890123456789012345678901234567890123456789"
+ "01234567890123456789012345678901234567890123456789"
+ "01234567890123456789012345678901234567890123456789"
+ "01234567890123456789012345678901234567890123456789"
+ "01234567890123456789012345678901234567890123456789"
+ "01234";
// Execute it using executeQuery
CallableStatement cs = con.prepareCall("{?=call #SAfe0010(?)}");
cs.registerOutParameter(1, Types.INTEGER);
cs.setString(2, myVal);
cs.registerOutParameter(2, Types.VARCHAR);
ResultSet rs = cs.executeQuery();
assertTrue(rs.next());
String rsVal = rs.getString(1);
rs.close();
assertFalse(cs.getMoreResults());
assertEquals(-1, cs.getUpdateCount());
assertEquals(myVal.length(), cs.getInt(1));
assertEquals(rsVal, cs.getString(2));
cs.close();
}
/**
* Test ResultSet.updateRow() on updateable result sets.
*/
public void testUpdateRow0011() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #SAfe0011(value VARCHAR(255) PRIMARY KEY)");
stmt.close();
PreparedStatement insStmt = con.prepareStatement(
"INSERT INTO #SAfe0011(value) values (?)");
insStmt.setString(1, "Row 1");
assertEquals(1, insStmt.executeUpdate());
insStmt.setString(1, "Row 2");
assertEquals(1, insStmt.executeUpdate());
insStmt.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT * FROM #SAfe0011 ORDER BY 1");
assertEquals(null, stmt.getWarnings());
assertEquals(null, rs.getWarnings());
assertTrue(rs.next());
assertTrue(rs.next());
rs.updateString(1, "Row X");
rs.updateRow();
rs.next();
assertEquals("Row X", rs.getString(1));
rs.close();
stmt.close();
}
/**
* Test ResultSet.insertRow() on updateable result sets.
*/
public void testInsertRow0012() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #SAfe0012(value VARCHAR(255) PRIMARY KEY)");
stmt.close();
PreparedStatement insStmt = con.prepareStatement(
"INSERT INTO #SAfe0012(value) values (?)");
insStmt.setString(1, "Row 1");
assertEquals(1, insStmt.executeUpdate());
insStmt.setString(1, "Row 2");
assertEquals(1, insStmt.executeUpdate());
insStmt.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT * FROM #SAfe0012 ORDER BY 1");
assertEquals(null, stmt.getWarnings());
assertEquals(null, rs.getWarnings());
// Insert the new row
rs.moveToInsertRow();
rs.updateString(1, "Row X");
rs.insertRow();
// Check the ResultSet contents
rs.moveToCurrentRow();
rs.next();
assertEquals("Row 1", rs.getString(1));
rs.next();
assertEquals("Row 2", rs.getString(1));
rs.next();
assertEquals("Row X", rs.getString(1));
rs.close();
stmt.close();
}
/**
* Test how an "out-of-order" close behaves (e.g close the
* Connection first, then the Statement anf
* finally the ResultSet).
*/
public void testOutOfOrderClose0013() throws Exception {
Connection localConn = getConnection();
Statement stmt = localConn.createStatement();
stmt.execute("CREATE TABLE #SAfe0013(value VARCHAR(255) PRIMARY KEY)");
PreparedStatement insStmt = localConn.prepareStatement(
"INSERT INTO #SAfe0013(value) values (?)");
insStmt.setString(1, "Row 1");
assertEquals(1, insStmt.executeUpdate());
insStmt.setString(1, "Row 2");
assertEquals(1, insStmt.executeUpdate());
ResultSet rs = stmt.executeQuery("SELECT * FROM #SAfe0013");
// Close the connection first
localConn.close();
// Now, close the statements
stmt.close();
insStmt.close();
// And finally, close the ResultSet
rs.close();
}
/**
* Test cursor-based ResultSets obtained from
* PreparedStatements and CallableStatements.
*/
public void testPreparedAndCallableCursors0014() throws Exception {
// Logger.setActive(true);
Statement stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE #SAfe0014(id INT PRIMARY KEY)");
stmt.executeUpdate("INSERT INTO #SAfe0014 VALUES (1)");
stmt.executeUpdate("CREATE PROCEDURE #sp_SAfe0014(@P1 INT, @P2 INT) AS "
+ "SELECT id, @P2 FROM #SAfe0014 WHERE id=@P1");
stmt.close();
PreparedStatement ps = con.prepareStatement("SELECT id FROM #SAfe0014",
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet resultSet = ps.executeQuery();
// No warnings
assertEquals(null, resultSet.getWarnings());
assertEquals(null, ps.getWarnings());
// Correct ResultSet
assertTrue(resultSet.next());
assertEquals(1, resultSet.getInt(1));
assertTrue(!resultSet.next());
// Correct meta data
ResultSetMetaData rsmd = resultSet.getMetaData();
assertEquals("id", rsmd.getColumnName(1));
assertEquals("#SAfe0014", rsmd.getTableName(1));
// Insert row
resultSet.moveToInsertRow();
resultSet.updateInt(1, 2);
resultSet.insertRow();
resultSet.moveToCurrentRow();
// Check correct row count
resultSet.last();
assertEquals(2, resultSet.getRow());
resultSet.close();
ps.close();
ps = con.prepareStatement("SELECT id, ? FROM #SAfe0014 WHERE id = ?",
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ps.setInt(1, 5);
ps.setInt(2, 1);
resultSet = ps.executeQuery();
// No warnings
assertEquals(null, resultSet.getWarnings());
assertEquals(null, ps.getWarnings());
// Correct ResultSet
assertTrue(resultSet.next());
assertEquals(1, resultSet.getInt(1));
assertEquals(5, resultSet.getInt(2));
assertTrue(!resultSet.next());
// Correct meta data
rsmd = resultSet.getMetaData();
assertEquals("id", rsmd.getColumnName(1));
assertEquals("#SAfe0014", rsmd.getTableName(1));
resultSet.close();
ps.close();
CallableStatement cs = con.prepareCall("{call #sp_SAfe0014(?,?)}",
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
cs.setInt(1, 1);
cs.setInt(2, 3);
resultSet = cs.executeQuery();
// No warnings
assertEquals(null, resultSet.getWarnings());
assertEquals(null, cs.getWarnings());
// Correct ResultSet
assertTrue(resultSet.next());
assertEquals(1, resultSet.getInt(1));
assertEquals(3, resultSet.getInt(2));
assertTrue(!resultSet.next());
// Correct meta data
rsmd = resultSet.getMetaData();
assertEquals("id", rsmd.getColumnName(1));
assertEquals("#SAfe0014", rsmd.getTableName(1));
resultSet.close();
cs.close();
}
/**
* Test batch updates for both plain and prepared statements.
*/
public void testBatchUpdates0015() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #SAfe0015(value VARCHAR(255) PRIMARY KEY)");
// Execute prepared batch
PreparedStatement insStmt = con.prepareStatement(
"INSERT INTO #SAfe0015(value) values (?)");
insStmt.setString(1, "Row 1");
insStmt.addBatch();
insStmt.setString(1, "Row 2");
insStmt.addBatch();
int[] res = insStmt.executeBatch();
assertEquals(2, res.length);
assertEquals(1, res[0]);
assertEquals(1, res[1]);
// Execute an empty batch
res = insStmt.executeBatch();
insStmt.close();
assertEquals(0, res.length);
// Execute plain batch
stmt.addBatch("UPDATE #SAfe0015 SET value='R1' WHERE value='Row 1'");
stmt.addBatch("UPDATE #SAfe0015 SET value='R2' WHERE value='Row 2'");
res = stmt.executeBatch();
assertEquals(2, res.length);
assertEquals(1, res[0]);
assertEquals(1, res[1]);
// Execute an empty batch
res = stmt.executeBatch();
assertEquals(0, res.length);
// Close the statement
stmt.close();
}
/**
* Test that dates prior to 06/15/1940 0:00:00 are stored and retrieved
* correctly.
*/
public void testOldDates0016() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #SAfe0016(id INT, value DATETIME)");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String[] dates = {
"1983-10-30 02:00:00",
"1983-10-30 01:59:59",
"1940-06-14 23:59:59",
"1911-03-11 00:51:39",
"1911-03-11 00:51:38",
"1900-01-01 01:00:00",
"1900-01-01 00:59:59",
"1900-01-01 00:09:21",
"1900-01-01 00:09:20",
"1753-01-01 00:00:00"
};
// Insert the timestamps
PreparedStatement pstmt =
con.prepareStatement("INSERT INTO #SAfe0016 VALUES(?, ?)");
for (int i = 0; i < dates.length; i++) {
pstmt.setInt(1, i);
pstmt.setString(2, dates[i]);
pstmt.addBatch();
}
int[] res = pstmt.executeBatch();
// Check that the insertion went ok
assertEquals(dates.length, res.length);
for (int i = 0; i < dates.length; i++) {
assertEquals(1, res[i]);
}
// Select the timestamps and make sure they are the same
ResultSet rs = stmt.executeQuery(
"SELECT value FROM #SAfe0016 ORDER BY id");
int counter = 0;
while (rs.next()) {
assertEquals(format.parse(dates[counter]), rs.getTimestamp(1));
++counter;
}
// Close everything
rs.close();
stmt.close();
pstmt.close();
}
/**
* Test bug #926620 - Too long value for VARCHAR field.
*/
/* does not work with SQL 6.5
public void testCursorLargeCharInsert0017() throws Exception {
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
stmt.execute("CREATE TABLE #SAfe0017(value VARCHAR(10) PRIMARY KEY)");
// Create the updateable ResultSet
ResultSet rs = stmt.executeQuery(
"SELECT value FROM #SAfe0017");
// Try inserting a character string less than 10 characters long
rs.moveToInsertRow();
rs.updateString(1, "Test");
rs.insertRow();
rs.moveToCurrentRow();
rs.last();
// Check that we do indeed have one row in the ResultSet now
assertEquals(1, rs.getRow());
// Try inserting a character string more than 10 characters long
rs.moveToInsertRow();
rs.updateString(1, "Testing: 1, 2, 3...");
try {
rs.insertRow();
fail("Should cause an SQLException with native error number 8152"
+ "and SQL state 22001");
} catch (SQLException ex) {
// assertEquals("22001", ex.getSQLState());
assertTrue(ex instanceof DataTruncation);
}
// Close everything
rs.close();
stmt.close();
}*/
/**
* Test for bug [939206] TdsException: can't sent this BigDecimal
*/
public void testBigDecimal1() throws Exception {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT @@MAX_PRECISION");
assertTrue(rs.next());
int maxPrecision = rs.getInt(1);
rs.close();
BigDecimal maxval = new BigDecimal("1E+" + maxPrecision);
maxval = maxval.subtract(new BigDecimal(1));
// maxval now = 99999999999999999999999999999999999999
if (maxPrecision > 28) {
stmt.execute("create table #testBigDecimal1 (id int primary key, data01 decimal(38,0), data02 decimal(38,12) null, data03 money)");
} else {
stmt.execute("create table #testBigDecimal1 (id int primary key, data01 decimal(28,0), data02 decimal(28,12) null, data03 money)");
}
PreparedStatement pstmt = con.prepareStatement("insert into #testBigDecimal1 (id, data01, data02, data03) values (?,?,?,?)");
pstmt.setInt(1, 1);
try {
pstmt.setBigDecimal(2, maxval.add(new BigDecimal(1)));
assertTrue(false); // Should fail
} catch (SQLException e) {
// System.out.println(e.getMessage());
// OK Genuinely can't send this one!
}
pstmt.setBigDecimal(2, maxval);
pstmt.setBigDecimal(3, new BigDecimal(1.0 / 3.0)); // Scale > 38
pstmt.setBigDecimal(4, new BigDecimal("12345.56789"));
assertTrue(pstmt.executeUpdate() == 1);
pstmt.close();
rs = stmt.executeQuery("SELECT * FROM #testBigDecimal1");
assertTrue(rs.next());
assertEquals(maxval, rs.getBigDecimal(2));
assertEquals(new BigDecimal("0.333333333333"), rs.getBigDecimal(3)); // Rounded to scale 10
assertEquals(new BigDecimal("12345.5679"), rs.getBigDecimal(4)); // Money has scale of 4
rs.close();
maxval = maxval.negate();
Statement stmt2 = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
rs = stmt2.executeQuery("SELECT * FROM #testBigDecimal1");
SQLWarning warn = stmt.getWarnings();
while (warn != null) {
System.out.println(warn.getMessage());
warn = warn.getNextWarning();
}
assertTrue(rs.next());
rs.updateBigDecimal("data01", maxval);
rs.updateNull("data02");
rs.updateObject("data03", new BigDecimal("-12345.56789"), 2); // Round to scale 2
rs.updateRow();
rs.close();
stmt2.close();
rs = stmt.executeQuery("SELECT * FROM #testBigDecimal1");
assertTrue(rs.next());
assertEquals(maxval, rs.getBigDecimal(2));
assertEquals(null, rs.getBigDecimal(3));
assertEquals(new BigDecimal("-12345.5700"), rs.getBigDecimal(4));
rs.close();
stmt.close();
}
/**
* Test for bug [963799] float values change when written to the database
*/
public void testFloat1() throws Exception {
float value = 2.2f;
Statement stmt = con.createStatement();
stmt.execute("create table #testFloat1 (data decimal(28,10))");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #testFloat1 (data) values (?)");
pstmt.setFloat(1, value);
assertTrue(pstmt.executeUpdate() == 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #testFloat1");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertTrue(value == rs.getFloat(1));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for bug [983561] getDatetimeValue truncates fractional milliseconds
*/
public void testDatetimeRounding1() throws Exception {
long dateTime = 1089297738677L;
Timestamp value = new Timestamp(dateTime);
Statement stmt = con.createStatement();
stmt.execute("create table #dtr1 (data datetime)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #dtr1 (data) values (?)");
pstmt.setTimestamp(1, value);
assertTrue(pstmt.executeUpdate() == 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #dtr1");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertTrue(value.equals(rs.getTimestamp(1)));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
public void testSocketConcurrency1() {
final Connection con = this.con;
final int threadCount = 10, loopCount = 10;
final Vector errors = new Vector();
// DriverManager.setLogStream(System.out);
// Create a huge query
StringBuffer queryBuffer = new StringBuffer(4100);
queryBuffer.append("SELECT '");
while (queryBuffer.length() < 2000) {
queryBuffer.append("0123456789");
}
queryBuffer.append("' AS value1, '");
while (queryBuffer.length() < 4000) {
queryBuffer.append("9876543210");
}
queryBuffer.append("' AS value2");
final String query = queryBuffer.toString();
Thread heavyThreads[] = new Thread[threadCount],
lightThreads[] = new Thread[threadCount];
// Create threadCount heavy threads
for (int i = 0; i < threadCount; i++) {
heavyThreads[i] = new Thread() {
public void run() {
try {
Statement stmt = con.createStatement();
for (int i = 0; i < loopCount; i++) {
stmt.execute(query);
}
stmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
errors.add(ex);
}
}
};
}
// Create threadCount light threads
for (int i = 0; i < threadCount; i++) {
lightThreads[i] = new Thread() {
public void run() {
try { sleep(100); } catch (InterruptedException ex) {}
try {
Statement stmt = con.createStatement();
for (int i = 0; i < loopCount; i++) {
stmt.execute("SELECT 1");
}
stmt.close();
} catch (Exception ex) {
ex.printStackTrace();
errors.add(ex);
}
}
};
}
for (int i = 0; i < threadCount; i++) {
heavyThreads[i].start();
lightThreads[i].start();
}
for (int i = 0; i < threadCount; i++) {
try { heavyThreads[i].join(); } catch (InterruptedException ex) {}
try { lightThreads[i].join(); } catch (InterruptedException ex) {}
}
assertEquals(0, errors.size());
}
public void testSocketConcurrency2() {
final Connection con = this.con;
final int threadCount = 10, loopCount = 10;
final Vector errors = new Vector();
// DriverManager.setLogStream(System.out);
// Create a huge query
StringBuffer valueBuffer = new StringBuffer(4000);
while (valueBuffer.length() < 4000) {
valueBuffer.append("0123456789");
}
final String value = valueBuffer.toString();
Thread heavyThreads[] = new Thread[threadCount],
lightThreads[] = new Thread[threadCount];
// Create threadCount heavy threads
for (int i = 0; i < threadCount; i++) {
heavyThreads[i] = new Thread() {
public void run() {
try {
PreparedStatement pstmt = con.prepareStatement(
"SELECT ? AS value1, ? AS value2");
pstmt.setString(1, value);
pstmt.setString(2, value);
for (int i = 0; i < loopCount; i++) {
pstmt.execute();
}
pstmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
errors.add(ex);
}
}
};
}
// Create threadCount light threads
for (int i = 0; i < threadCount; i++) {
lightThreads[i] = new Thread() {
public void run() {
try { sleep(100); } catch (InterruptedException ex) {}
try {
Statement stmt = con.createStatement();
for (int i = 0; i < loopCount; i++) {
stmt.execute("SELECT 1");
}
stmt.close();
} catch (Exception ex) {
ex.printStackTrace();
errors.add(ex);
}
}
};
}
for (int i = 0; i < threadCount; i++) {
heavyThreads[i].start();
lightThreads[i].start();
}
for (int i = 0; i < threadCount; i++) {
try { heavyThreads[i].join(); } catch (InterruptedException ex) {}
try { lightThreads[i].join(); } catch (InterruptedException ex) {}
}
assertEquals(0, errors.size());
}
public void testSocketConcurrency3() {
final Connection con = this.con;
final int threadCount = 10, loopCount = 10;
final Vector errors = new Vector();
// DriverManager.setLogStream(System.out);
// Create a huge query
StringBuffer valueBuffer = new StringBuffer(4000);
while (valueBuffer.length() < 4000) {
valueBuffer.append("0123456789");
}
final String value = valueBuffer.toString();
Thread heavyThreads[] = new Thread[threadCount],
lightThreads[] = new Thread[threadCount];
// Create threadCount heavy threads
for (int i = 0; i < threadCount; i++) {
heavyThreads[i] = new Thread() {
public void run() {
try {
PreparedStatement pstmt = con.prepareStatement(
"SELECT ? AS value1, ? AS value2");
pstmt.setString(1, value);
pstmt.setString(2, value);
for (int i = 0; i < loopCount; i++) {
pstmt.execute();
}
pstmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
errors.add(ex);
}
}
};
}
// Create threadCount light threads
for (int i = 0; i < threadCount; i++) {
lightThreads[i] = new Thread() {
public void run() {
try { sleep(100); } catch (InterruptedException ex) {}
try {
CallableStatement cstmt = con.prepareCall("sp_who");
for (int i = 0; i < loopCount; i++) {
cstmt.execute();
}
cstmt.close();
} catch (Exception ex) {
ex.printStackTrace();
errors.add(ex);
}
}
};
}
for (int i = 0; i < threadCount; i++) {
heavyThreads[i].start();
lightThreads[i].start();
}
for (int i = 0; i < threadCount; i++) {
try { heavyThreads[i].join(); } catch (InterruptedException ex) {}
try { lightThreads[i].join(); } catch (InterruptedException ex) {}
}
assertEquals(0, errors.size());
}
/**
* Test running SELECT queries on one Statement at the same
* time as cancel() is called on a concurrent
* Statement.
*/
public void testSocketConcurrency4() throws Exception {
// Just enough rows to break the server response in two network packets
final int rowCount = 256;
//Set up the test table
final Statement stmt = con.createStatement();
stmt.executeUpdate("create table #testSocketConcurrency4 "
+ "(id int primary key, value varchar(30))");
for (int i = 0; i < rowCount; i++) {
stmt.executeUpdate("insert into #testSocketConcurrency4 "
+ "values (" + i + ", 'Row number " + i + "')");
}
final Vector errors = new Vector();
// Start a thread that does some work
Thread t = new Thread() {
public void run() {
try {
for (int j = 0; j < 10; j++) {
ResultSet rs = stmt.executeQuery(
"select * from #testSocketConcurrency4");
int cnt = 0;
while (rs.next()) {
++cnt;
}
assertEquals(rowCount, cnt);
rs.close();
assertEquals(1, stmt.executeUpdate(
"update #testSocketConcurrency4 "
+ "set value='Updated' where id=" + j));
}
} catch (Exception ex) {
ex.printStackTrace();
errors.add(ex);
}
}
};
t.start();
// At the same time run some cancel() tests (on the same connection!)
testCancel0003();
// Now wait for the worker thread to finish
t.join();
assertEquals(0, errors.size());
}
/**
* Test that null output parameters are handled correctly.
*
INTN with
* length 0, which means it's null, it returns an INT4
* followed by a single 0 byte). The output parameter packet length is also
* incorrect, which indicates that SQL Server is confused.
*
* Currently jTDS always sends RPC parameters as nullable types, but this
* test is necessary to ensure that it will always remain so.
*/
public void testNullOutputParameters() throws SQLException {
Statement stmt = con.createStatement();
assertEquals(0, stmt.executeUpdate(
"create procedure #testNullOutput @p1 int output as "
+ "select @p1=null"));
stmt.close();
CallableStatement cstmt = con.prepareCall("#testNullOutput ?");
cstmt.setInt(1, 1);
cstmt.registerOutParameter(1, Types.INTEGER);
assertEquals(0, cstmt.executeUpdate());
assertNull(cstmt.getObject(1));
cstmt.close();
}
/**
* Test that the SQL parser doesn't try to parse the table name unless
* necessary (or that it is able to parse function calls if it does).
*/
public void testTableParsing() throws SQLException {
Statement stmt = con.createStatement();
try {
stmt.executeQuery(
"SELECT * FROM ::fn_missing('c:\\t file.trc')");
fail("Expecting an SQLException");
} catch (SQLException ex) {
// 42000 == syntax error or access rule violation
assertEquals("42000", ex.getSQLState());
}
}
/**
* Test for bug related with [1368058] Calling StoredProcedure with
* functions ({fn} escape can't handle special characters, e.g. underscore).
*/
public void testFnEscape() throws Exception {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT {fn host_id()}");
assertTrue(rs.next());
assertFalse(rs.next());
rs.close();
stmt.close();
}
/**
* Test for bug #1116046 {fn } escape can't handle nested functions.
*/
public void testFnEscapeNesting() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate(
"create table #testFnEscapeNesting (col1 int null, col2 int)");
stmt.executeUpdate("insert into #testFnEscapeNesting (col1, col2) "
+ "values (null, 1)");
stmt.executeUpdate("insert into #testFnEscapeNesting (col1, col2) "
+ "values (1, 2)");
ResultSet rs = stmt.executeQuery(
"select {fn ifnull({fn max(col2)}, 0)} "
+ "from #testFnEscapeNesting");
assertNotNull(rs);
assertTrue(rs.next());
assertEquals(2, rs.getInt(1));
assertFalse(rs.next());
rs.close();
rs = stmt.executeQuery("select {fn ifnull((select col1 "
+ "from #testFnEscapeNesting where col2 = 1), 0) }");
assertNotNull(rs);
assertTrue(rs.next());
assertEquals(0, rs.getInt(1));
assertFalse(rs.next());
rs.close();
rs = stmt.executeQuery(
"select {fn ifnull(sum({fn ifnull(col1, 4)}), max(col2))} "
+ "from #testFnEscapeNesting "
+ "group by col2 order by col2");
assertNotNull(rs);
assertTrue(rs.next());
assertEquals(4, rs.getInt(1));
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertFalse(rs.next());
rs.close();
stmt.close();
}
/**
* Test DataTruncation exception.
*/
public void testDataTruncException() throws Exception {
con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
Statement stmt = con.createStatement();
if (!con.getMetaData().getDatabaseProductName().
toLowerCase().startsWith("microsoft")) {
// By default Sybase will silently truncate strings,
// set an option to ensure that an exception is thrown.
stmt.execute("SET STRING_RTRUNCATION ON");
}
stmt.execute("CREATE TABLE #TESTTRUNC (i tinyint, n numeric(2), c char(2))");
try {
stmt.execute("INSERT INTO #TESTTRUNC VALUES(1111, 1, 'X')");
fail("Expected data truncation on tinyint");
} catch (DataTruncation e) {
// Expected DataTruncation
}
try {
stmt.execute("INSERT INTO #TESTTRUNC VALUES(1, 1111, 'X')");
fail("Expected data truncation on numeric");
} catch (DataTruncation e) {
// Expected DataTruncation
}
try {
stmt.execute("INSERT INTO #TESTTRUNC VALUES(1, 1, 'XXXXX')");
fail("Expected data truncation on char");
} catch (DataTruncation e) {
// Expected DataTruncation
}
}
/**
* Test Statement.setMaxFieldSize().
*/
public void testMaxFieldSize() throws Exception {
// TODO Should it also work for fields other than TEXT, per JDBC spec?
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #testMaxFieldSize (i int primary key, t text)");
stmt.executeUpdate("insert into #testMaxFieldSize (i, t) values (1, 'This is a test')");
PreparedStatement pstmt = con.prepareStatement("select * from #testMaxFieldSize");
// Set different max field sizes for two concurrent statements
// Also set max rows, to test setting field size and max rows at the
// same time works ok
stmt.setMaxFieldSize(3);
stmt.setMaxRows(1);
pstmt.setMaxFieldSize(5);
// Test plain statement
ResultSet rs = stmt.executeQuery("select * from #testMaxFieldSize");
assertNotNull(rs);
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertEquals(3, rs.getString(2).length());
rs.close();
// Test prepared statement
rs = pstmt.executeQuery();
assertNotNull(rs);
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertEquals(5, rs.getString(2).length());
rs.close();
stmt.close();
// Test scrollable statement
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
stmt.setMaxFieldSize(3);
rs = stmt.executeQuery("select * from #testMaxFieldSize");
assertNotNull(rs);
assertEquals(null, stmt.getWarnings());
assertEquals(null, rs.getWarnings());
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertEquals(3, rs.getString(2).length());
rs.close();
}
/**
* Test return of multiple scrollable result sets from one execute.
*/
public void testGetMultiScrollRs() throws Exception {
// Manual commit mode to make sure no garbage is left behind
con.setAutoCommit(false);
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
try {
dropProcedure("jtds_multiSet");
stmt.execute("CREATE PROC jtds_multiSet as\r\n " +
"BEGIN\r\n" +
"SELECT 'SINGLE ROW RESULT'\r\n"+
"SELECT 1, 'LINE ONE'\r\n"+
"UNION\r\n" +
"SELECT 2, 'LINE TWO'\r\n"+
"UNION\r\n" +
"SELECT 3, 'LINE THREE'\r\n"+
"SELECT 'ANOTHER SINGLE ROW RESULT'\r\n"+
"END\r\n");
assertTrue(stmt.execute("exec jtds_multiSet"));
stmt.clearWarnings();
ResultSet rs = stmt.getResultSet();
assertNotNull(stmt.getWarnings()); // Downgrade to read only
assertNotNull(stmt.getWarnings().getNextWarning()); // Downgrade to insensitive
assertTrue(rs.next());
assertEquals("SINGLE ROW RESULT", rs.getString(1));
assertTrue(stmt.getMoreResults());
rs = stmt.getResultSet();
assertTrue(rs.absolute(2));
assertEquals("LINE TWO", rs.getString(2));
assertTrue(rs.relative(-1));
assertEquals("LINE ONE", rs.getString(2));
assertTrue(stmt.getMoreResults());
rs = stmt.getResultSet();
assertTrue(rs.next());
assertEquals("ANOTHER SINGLE ROW RESULT", rs.getString(1));
} finally {
dropProcedure("jtds_multiSet");
stmt.close();
// We can safely commit, mess cleaned up (we could rollback, too)
con.commit();
}
}
/**
* Test for bug [1187927] Driver Hangs on Statement.execute().
*
* Versions 1.0.3 and prior entered an infinite loop when parsing an
* unterminated multi-line comment.
*/
public void testUnterminatedCommentParsing() throws Exception {
Statement stmt = con.createStatement();
try {
stmt.execute("/* This is an unterminated comment");
fail("Expecting parse exception");
} catch (SQLException ex) {
assertEquals("22025", ex.getSQLState());
}
stmt.close();
}
/**
* Test that getString() on a varbinary column returns a hex string.
*/
public void testBytesToString() throws Exception {
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
stmt.execute(
"CREATE TABLE #testbytes (id int primary key, b varbinary(8), i image, c varchar(255) null)");
assertEquals(1, stmt.executeUpdate(
"INSERT INTO #testbytes VALUES (1, 0x41424344, 0x41424344, null)"));
ResultSet rs = stmt.executeQuery("SELECT * FROM #testbytes");
assertNotNull(rs);
assertTrue(rs.next());
assertEquals("41424344", rs.getString(2));
assertEquals("41424344", rs.getString(3));
Clob clob = rs.getClob(2);
assertEquals("41424344", clob.getSubString(1, (int)clob.length()));
clob = rs.getClob(3);
assertEquals("41424344", clob.getSubString(1, (int)clob.length()));
//
// Check that updating sensitive result sets yields the correct
// results. This test is mainly for Sybase scroll sensitive client
// side cursors.
//
rs.updateBytes(4, new byte[]{0x41, 0x42, 0x43, 0x44});
rs.updateRow();
assertEquals("ABCD", rs.getString(4));
stmt.close();
}
/**
* Tests that executeUpdate("SELECT ...") fails.
*/
public void testExecuteUpdateSelect() throws Exception {
Statement stmt = con.createStatement();
try {
stmt.executeUpdate("select 1");
fail("Expecting an exception to be thrown");
} catch (SQLException ex) {
assertEquals("07000", ex.getSQLState());
}
stmt.close();
PreparedStatement pstmt = con.prepareStatement("select 1");
try {
pstmt.executeUpdate();
fail("Expecting an exception to be thrown");
} catch (SQLException ex) {
assertEquals("07000", ex.getSQLState());
}
stmt.close();
}
/**
* Test for bug [1596743] executeQuery absorbs thread interrupt status
*/
public void testThreadInterrupt() throws Exception {
Thread.currentThread().interrupt();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT 1");
rs.close();
stmt.close();
assertTrue(Thread.currentThread().isInterrupted());
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/GenKeyTest.java 0000644 0001750 0001750 00000015775 11316672660 026114 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.sql.*;
/**
* Test case to illustrate JDBC 3 GetGeneratedKeys() function.
*
* @version 1.0
*/
public class GenKeyTest extends TestBase {
public GenKeyTest(String name) {
super(name);
}
public void testParams() throws Exception {
//
// Test data
//
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #gktemp (id INT IDENTITY (1,1) PRIMARY KEY, dummyx VARCHAR(50))");
stmt.close();
//
// Test PrepareStatement(sql, int) option
//
PreparedStatement pstmt =
con.prepareStatement("INSERT INTO #gktemp (dummyx) VALUES (?)", Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, "TEST01");
assertEquals("First Insert failed", 1, pstmt.executeUpdate());
ResultSet rs = pstmt.getGeneratedKeys();
assertTrue("ResultSet empty", rs.next());
assertEquals("Bad inserted row ID ", 1, rs.getInt(1));
rs.close();
pstmt.close();
//
// Test PrepareStatement(sql, int[]) option
//
int cols[] = new int[1];
cols[0] = 1;
pstmt =
con.prepareStatement("INSERT INTO #gktemp (dummyx) VALUES (?)", cols);
pstmt.setString(1, "TEST02");
assertEquals("Second Insert failed", 1, pstmt.executeUpdate());
rs = pstmt.getGeneratedKeys();
assertTrue("ResultSet 2 empty", rs.next());
assertEquals("Bad inserted row ID ", 2, rs.getInt(1));
rs.close();
pstmt.close();
//
// Test PrepareStatement(sql, String[]) option
//
String colNames[] = new String[1];
colNames[0] = "ID";
pstmt =
con.prepareStatement("INSERT INTO #gktemp (dummyx) VALUES (?)", colNames);
pstmt.setString(1, "TEST03");
pstmt.execute();
assertEquals("Third Insert failed", 1, pstmt.getUpdateCount());
rs = pstmt.getGeneratedKeys();
assertTrue("ResultSet 3 empty", rs.next());
assertEquals("Bad inserted row ID ", 3, rs.getInt(1));
rs.close();
pstmt.close();
//
// Test CreateStatement()
//
stmt = con.createStatement();
assertEquals("Fourth Insert failed", 1,
stmt.executeUpdate("INSERT INTO #gktemp (dummyx) VALUES ('TEST04')",
Statement.RETURN_GENERATED_KEYS));
rs = stmt.getGeneratedKeys();
assertTrue("ResultSet 4 empty", rs.next());
assertEquals("Bad inserted row ID ", 4, rs.getInt(1));
rs.close();
stmt.close();
stmt = con.createStatement();
stmt.execute("DROP TABLE #gktemp");
stmt.close();
}
/**
* Test for bug [930305] getGeneratedKeys() does not work with triggers
*/
public void testTrigger1() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE jtdsTestTrigger1 (id INT IDENTITY (1,1) PRIMARY KEY, data INT)");
stmt.execute("CREATE TABLE jtdsTestTrigger2 (id INT IDENTITY (1,1) PRIMARY KEY, data INT)");
stmt.close();
try {
stmt = con.createStatement();
stmt.execute("CREATE TRIGGER testTrigger1 ON jtdsTestTrigger1 FOR INSERT AS "
+ "INSERT INTO jtdsTestTrigger2 (data) VALUES (1)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement(
"INSERT INTO jtdsTestTrigger1 (data) VALUES (?)",
Statement.RETURN_GENERATED_KEYS);
for (int i = 0; i < 10; i++) {
pstmt.setInt(1, i);
assertEquals("Insert failed: " + i, 1, pstmt.executeUpdate());
ResultSet rs = pstmt.getGeneratedKeys();
assertTrue("ResultSet empty: " + i, rs.next());
assertEquals("Bad inserted row ID: " + i, i + 1, rs.getInt(1));
assertTrue("ResultSet not empty: " + i, !rs.next());
rs.close();
}
pstmt.close();
} finally {
stmt = con.createStatement();
stmt.execute("DROP TABLE jtdsTestTrigger1");
stmt.execute("DROP TABLE jtdsTestTrigger2");
stmt.close();
}
}
/**
* Test empty result set returned when no keys available.
*/
public void testNoKeys() throws Exception {
Statement stmt = con.createStatement();
ResultSet rs = stmt.getGeneratedKeys();
assertEquals("ID", rs.getMetaData().getColumnName(1));
assertFalse(rs.next());
}
/**
* Test that SELECT statements work correctly with
* PreparedStatements created with
* RETURN_GENERATED_KEYS.
*/
public void testSelect() throws SQLException {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #colors (id int, color varchar(255))");
stmt.executeUpdate("insert into #colors values (1, 'red')");
stmt.executeUpdate("insert into #colors values (1, 'green')");
stmt.executeUpdate("insert into #colors values (1, 'blue')");
stmt.close();
PreparedStatement pstmt = con.prepareStatement(
"select * from #colors", Statement.RETURN_GENERATED_KEYS);
assertTrue(pstmt.execute());
ResultSet rs = pstmt.getResultSet();
assertEquals(2, rs.getMetaData().getColumnCount());
assertTrue(rs.next());
assertTrue(rs.next());
assertTrue(rs.next());
assertFalse(rs.next());
rs.close();
assertFalse(pstmt.getMoreResults());
assertEquals(-1, pstmt.getUpdateCount());
rs = pstmt.executeQuery();
assertEquals(2, rs.getMetaData().getColumnCount());
assertTrue(rs.next());
assertTrue(rs.next());
assertTrue(rs.next());
assertFalse(rs.next());
rs.close();
pstmt.close();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(GenKeyTest.class);
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/TypeInfoTest.java 0000644 0001750 0001750 00000005730 11316672660 026455 0 ustar martin martin //jTDS JDBC Driver for Microsoft SQL Server and Sybase
//Copyright (C) 2004 The jTDS Project
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.sql.Types;
import junit.framework.TestCase;
import net.sourceforge.jtds.jdbc.TypeInfo;
/**
* Tests for the TypeInfo class.
*
* @author David Eaves
* @version $Id: TypeInfoTest.java,v 1.1 2005/01/05 12:24:14 alin_sinpalean Exp $
*/
public class TypeInfoTest extends TestCase {
public TypeInfoTest(String testName) {
super(testName);
}
public void testCharTypes() {
TypeInfo charType = new TypeInfo("char", Types.CHAR, false);
// Following types are normalized to char
TypeInfo nchar = new TypeInfo("nchar", -8, false);
TypeInfo uniqueid = new TypeInfo("uniqueidentifier", -11, false);
assertComparesLessThan(charType, nchar);
assertComparesLessThan(nchar, uniqueid);
}
public void testVarcharTypes() {
TypeInfo varchar = new TypeInfo("varchar", Types.VARCHAR, false);
// Following types are normalized to varchar
TypeInfo nvarchar = new TypeInfo("nvarchar", -9, false);
TypeInfo sysname = new TypeInfo("sysname", -9, false);
TypeInfo variant = new TypeInfo("sql_variant", -150, false);
assertComparesLessThan(varchar, nvarchar);
assertComparesLessThan(nvarchar, sysname);
assertComparesLessThan(sysname, variant);
}
public void testCompareToDifferentDataType() {
TypeInfo decimal = new TypeInfo("decimal", Types.DECIMAL /* 3 */, false);
TypeInfo integer = new TypeInfo("integer", Types.INTEGER /* 4 */, false);
assertComparesLessThan(decimal, integer);
}
public void testCompareToIdentity() {
TypeInfo bigint = new TypeInfo("bigint", Types.BIGINT, false);
TypeInfo bigintIdentity = new TypeInfo("bigint identity", Types.BIGINT, true);
assertComparesLessThan(bigint, bigintIdentity);
}
private void assertComparesLessThan(TypeInfo t1, TypeInfo t2) {
assertTrue(t1 + " < " + t2 + " failed", t1.compareTo(t2) < 0);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(TypeInfoTest.class);
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/BatchTest.java 0000644 0001750 0001750 00000067551 11316672660 025752 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.sql.*;
import java.util.*;
import net.sourceforge.jtds.jdbc.*;
/**
* Simple test suite to exercise batch execution.
*
* @version $Id: BatchTest.java,v 1.11.2.6 2009/12/30 13:33:24 ickzon Exp $
*/
public class BatchTest extends DatabaseTestCase {
// Constants to use instead of the JDBC 3.0-only Statement constants
private static int SUCCESS_NO_INFO = -2;
private static int EXECUTE_FAILED = -3;
public BatchTest(String name) {
super(name);
}
/**
* This test should generate an error as the second statement in the batch
* returns a result set.
*/
public void testResultSetError() throws Exception {
Statement stmt = con.createStatement();
stmt.addBatch("create table #testbatch (id int, data varchar(255))");
stmt.addBatch("insert into #testbatch VALUES(1, 'Test line')");
stmt.addBatch("SELECT 'This is an error'");
int x[];
try {
x = stmt.executeBatch();
fail("Expecting BatchUpdateException");
} catch (BatchUpdateException e) {
x = e.getUpdateCounts();
}
assertEquals(3, x.length);
assertEquals(SUCCESS_NO_INFO, x[0]);
assertEquals(1, x[1]);
assertEquals(EXECUTE_FAILED, x[2]);
}
/**
* The first statement in this batch does not return an update count.
* SUCCESS_NO_INFO is expected instead.
*/
public void testNoCount() throws Exception {
Statement stmt = con.createStatement();
stmt.addBatch("create table #testbatch (id int, data varchar(255))");
stmt.addBatch("insert into #testbatch VALUES(1, 'Test line')");
int x[] = stmt.executeBatch();
assertEquals(2, x.length);
assertEquals(SUCCESS_NO_INFO, x[0]);
assertEquals(1, x[1]);
}
/**
* Test batched statements.
*/
public void testBatch() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("create table #testbatch (id int, data varchar(255))");
for (int i = 0; i < 5; i++) {
if (i == 2) {
// This statement will generate an error
stmt.addBatch("INSERT INTO #testbatch VALUES ('xx', 'This is line " + i + "')");
} else {
stmt.addBatch("INSERT INTO #testbatch VALUES (" + i + ", 'This is line " + i + "')");
}
}
int x[];
try {
x = stmt.executeBatch();
} catch (BatchUpdateException e) {
x = e.getUpdateCounts();
}
if (con.getMetaData().getDatabaseProductName().toLowerCase().startsWith("microsoft")
&& ((JtdsDatabaseMetaData) con.getMetaData()).getDatabaseMajorVersion() > 6 ) {
assertEquals(5, x.length);
assertEquals(1, x[0]);
assertEquals(1, x[1]);
assertEquals(EXECUTE_FAILED, x[2]);
assertEquals(EXECUTE_FAILED, x[3]);
assertEquals(EXECUTE_FAILED, x[4]);
} else {
// Sybase or SQL Server 6.5 - Entire batch fails due to data conversion error
// detected in statement 3
assertEquals(5, x.length);
assertEquals(EXECUTE_FAILED, x[0]);
assertEquals(EXECUTE_FAILED, x[1]);
assertEquals(EXECUTE_FAILED, x[2]);
assertEquals(EXECUTE_FAILED, x[3]);
assertEquals(EXECUTE_FAILED, x[4]);
}
// Now without errors
stmt.execute("TRUNCATE TABLE #testbatch");
for (int i = 0; i < 5; i++) {
stmt.addBatch("INSERT INTO #testbatch VALUES (" + i + ", 'This is line " + i + "')");
}
x = stmt.executeBatch();
assertEquals(5, x.length);
assertEquals(1, x[0]);
assertEquals(1, x[1]);
assertEquals(1, x[2]);
assertEquals(1, x[3]);
assertEquals(1, x[4]);
}
/**
* Test batched prepared statements.
*/
public void testPrepStmtBatch() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("create table #testbatch (id int, data varchar(255))");
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #testbatch VALUES (?, ?)");
for (int i = 0; i < 5; i++) {
if (i == 2) {
pstmt.setString(1, "xxx");
} else {
pstmt.setInt(1, i);
}
pstmt.setString(2, "This is line " + i);
pstmt.addBatch();
}
int x[];
try {
x = pstmt.executeBatch();
} catch (BatchUpdateException e) {
x = e.getUpdateCounts();
}
if (con.getMetaData().getDatabaseProductName().toLowerCase().startsWith("microsoft")) {
assertEquals(5, x.length);
assertEquals(1, x[0]);
assertEquals(1, x[1]);
assertEquals(EXECUTE_FAILED, x[2]);
assertEquals(EXECUTE_FAILED, x[3]);
assertEquals(EXECUTE_FAILED, x[4]);
} else {
// Sybase - Entire batch fails due to data conversion error
// detected in statement 3
assertEquals(5, x.length);
assertEquals(EXECUTE_FAILED, x[0]);
assertEquals(EXECUTE_FAILED, x[1]);
assertEquals(EXECUTE_FAILED, x[2]);
assertEquals(EXECUTE_FAILED, x[3]);
assertEquals(EXECUTE_FAILED, x[4]);
}
// Now without errors
stmt.execute("TRUNCATE TABLE #testbatch");
for (int i = 0; i < 5; i++) {
pstmt.setInt(1, i);
pstmt.setString(2, "This is line " + i);
pstmt.addBatch();
}
x = pstmt.executeBatch();
assertEquals(5, x.length);
assertEquals(1, x[0]);
assertEquals(1, x[1]);
assertEquals(1, x[2]);
assertEquals(1, x[3]);
assertEquals(1, x[4]);
}
/**
* Test batched callable statements.
*/
public void testCallStmtBatch() throws Exception {
dropProcedure("jTDS_PROC");
try {
Statement stmt = con.createStatement();
stmt.execute("create table #testbatch (id int, data varchar(255))");
stmt.execute("create proc jTDS_PROC @p1 varchar(10), @p2 varchar(255) as " +
"INSERT INTO #testbatch VALUES (convert(int, @p1), @p2)");
CallableStatement cstmt = con.prepareCall("{call jTDS_PROC (?, ?)}");
for (int i = 0; i < 5; i++) {
cstmt.setString(1, Integer.toString(i));
cstmt.setString(2, "This is line " + i);
cstmt.addBatch();
}
int x[];
try {
x = cstmt.executeBatch();
} catch (BatchUpdateException e) {
x = e.getUpdateCounts();
}
assertEquals(5, x.length);
assertEquals(1, x[0]);
assertEquals(1, x[1]);
assertEquals(1, x[2]);
assertEquals(1, x[3]);
assertEquals(1, x[4]);
// Now with errors
stmt.execute("TRUNCATE TABLE #testbatch");
for (int i = 0; i < 5; i++) {
if (i == 2) {
cstmt.setString(1, "XXX");
} else {
cstmt.setString(1, Integer.toString(i));
}
cstmt.setString(2, "This is line " + i);
cstmt.addBatch();
}
try {
x = cstmt.executeBatch();
} catch (BatchUpdateException e) {
x = e.getUpdateCounts();
}
if (con.getMetaData().getDatabaseProductName().toLowerCase().startsWith("microsoft")) {
assertEquals(5, x.length);
assertEquals(1, x[0]);
assertEquals(1, x[1]);
assertEquals(EXECUTE_FAILED, x[2]);
assertEquals(EXECUTE_FAILED, x[3]);
assertEquals(EXECUTE_FAILED, x[4]);
} else {
assertEquals(5, x.length);
assertEquals(1, x[0]);
assertEquals(1, x[1]);
assertEquals(EXECUTE_FAILED, x[2]);
assertEquals(1, x[3]);
assertEquals(1, x[4]);
}
} finally {
dropProcedure("jTDS_PROC");
}
}
/**
* Test batched callable statements where the call includes literal parameters which prevent the use of RPC calls.
*/
public void testCallStmtBatch2() throws Exception {
dropProcedure("jTDS_PROC");
try {
Statement stmt = con.createStatement();
stmt.execute("create table #testbatch (id int, data varchar(255))");
stmt.execute("create proc jTDS_PROC @p1 varchar(10), @p2 varchar(255) as " +
"INSERT INTO #testbatch VALUES (convert(int, @p1), @p2)");
CallableStatement cstmt = con.prepareCall("{call jTDS_PROC (?, 'literal parameter')}");
for (int i = 0; i < 5; i++) {
if (i == 2) {
cstmt.setString(1, "XXX");
} else {
cstmt.setString(1, Integer.toString(i));
}
cstmt.addBatch();
}
int x[];
try {
x = cstmt.executeBatch();
} catch (BatchUpdateException e) {
x = e.getUpdateCounts();
}
if (con.getMetaData().getDatabaseProductName().toLowerCase().startsWith("microsoft")) {
assertEquals(5, x.length);
assertEquals(1, x[0]);
assertEquals(1, x[1]);
assertEquals(EXECUTE_FAILED, x[2]);
assertEquals(EXECUTE_FAILED, x[3]);
assertEquals(EXECUTE_FAILED, x[4]);
} else {
assertEquals(5, x.length);
assertEquals(1, x[0]);
assertEquals(1, x[1]);
assertEquals(EXECUTE_FAILED, x[2]);
assertEquals(1, x[3]);
assertEquals(1, x[4]);
}
// Now without errors
stmt.execute("TRUNCATE TABLE #testbatch");
for (int i = 0; i < 5; i++) {
cstmt.setString(1, Integer.toString(i));
cstmt.addBatch();
}
try {
x = cstmt.executeBatch();
} catch (BatchUpdateException e) {
x = e.getUpdateCounts();
}
assertEquals(5, x.length);
assertEquals(1, x[0]);
assertEquals(1, x[1]);
assertEquals(1, x[2]);
assertEquals(1, x[3]);
assertEquals(1, x[4]);
} finally {
dropProcedure("jTDS_PROC");
}
}
/**
* Test large batch behavior.
*/
public void testLargeBatch() throws Exception {
final int n = 5000;
getConnection().close();
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #testLargeBatch (val int)");
stmt.executeUpdate("insert into #testLargeBatch (val) values (0)");
PreparedStatement pstmt = con.prepareStatement(
"update #testLargeBatch set val=? where val=?");
for (int i = 0; i < n; i++) {
pstmt.setInt(1, i + 1);
pstmt.setInt(2, i);
pstmt.addBatch();
}
int counts[] =pstmt.executeBatch();
// System.out.println(pstmt.getWarnings());
assertEquals(n, counts.length);
for (int i = 0; i < n; i++) {
assertEquals(1, counts[i]);
}
pstmt.close();
ResultSet rs =
stmt.executeQuery("select count(*) from #testLargeBatch");
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertFalse(rs.next());
rs.close();
stmt.close();
}
/**
* Test for bug [1180169] JDBC escapes not allowed with Sybase addBatch.
*/
public void testBatchEsc() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #TESTBATCH (ts datetime)");
stmt.addBatch("INSERT INTO #TESTBATCH VALUES ({ts '1999-01-01 23:50:00'})");
int counts[] = stmt.executeBatch();
assertEquals(1, counts[0]);
stmt.close();
}
/**
* Test for bug [1371295] SQL Server continues after duplicate key error.
*/
public void testPrepStmtBatchDupKey() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("create table #testbatch (id int, data varchar(255), PRIMARY KEY (id))");
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #testbatch VALUES (?, ?)");
for (int i = 0; i < 5; i++) {
if (i == 2) {
pstmt.setInt(1, 1); // Will cause duplicate key batch will continue
} else {
pstmt.setInt(1, i);
}
pstmt.setString(2, "This is line " + i);
pstmt.addBatch();
}
int x[];
try {
x = pstmt.executeBatch();
} catch (BatchUpdateException e) {
x = e.getUpdateCounts();
}
assertEquals(5, x.length);
assertEquals(1, x[0]);
assertEquals(1, x[1]);
assertEquals(EXECUTE_FAILED, x[2]);
assertEquals(1, x[3]);
assertEquals(1, x[4]);
// Now without errors
stmt.execute("TRUNCATE TABLE #testbatch");
for (int i = 0; i < 5; i++) {
pstmt.setInt(1, i);
pstmt.setString(2, "This is line " + i);
pstmt.addBatch();
}
x = pstmt.executeBatch();
assertEquals(5, x.length);
assertEquals(1, x[0]);
assertEquals(1, x[1]);
assertEquals(1, x[2]);
assertEquals(1, x[3]);
assertEquals(1, x[4]);
}
/**
* Test for bug [1371295] SQL Server continues after duplicate key error.
*/
public void testBatchDupKey() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("create table #testbatch (id int, data varchar(255), PRIMARY KEY (id))");
for (int i = 0; i < 5; i++) {
if (i == 2) {
// This statement will generate an duplicate key error
stmt.addBatch("INSERT INTO #testbatch VALUES (1, 'This is line " + i + "')");
} else {
stmt.addBatch("INSERT INTO #testbatch VALUES (" + i + ", 'This is line " + i + "')");
}
}
int x[];
try {
x = stmt.executeBatch();
} catch (BatchUpdateException e) {
x = e.getUpdateCounts();
}
assertEquals(5, x.length);
assertEquals(1, x[0]);
assertEquals(1, x[1]);
assertEquals(EXECUTE_FAILED, x[2]);
assertEquals(1, x[3]);
assertEquals(1, x[4]);
// Now without errors
stmt.execute("TRUNCATE TABLE #testbatch");
for (int i = 0; i < 5; i++) {
stmt.addBatch("INSERT INTO #testbatch VALUES (" + i + ", 'This is line " + i + "')");
}
x = stmt.executeBatch();
assertEquals(5, x.length);
assertEquals(1, x[0]);
assertEquals(1, x[1]);
assertEquals(1, x[2]);
assertEquals(1, x[3]);
assertEquals(1, x[4]);
}
/**
* Test for PreparedStatement batch with no parameters.
*/
public void testPrepStmtNoParams() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("create table #testbatch (id numeric(10) identity, data varchar(255), PRIMARY KEY (id))");
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #testbatch (data) VALUES ('Same each time')");
for (int i = 0; i < 5; i++) {
pstmt.addBatch();
}
int x[];
try {
x = pstmt.executeBatch();
} catch (BatchUpdateException e) {
x = e.getUpdateCounts();
}
assertEquals(5, x.length);
assertEquals(1, x[0]);
assertEquals(1, x[1]);
assertEquals(1, x[2]);
assertEquals(1, x[3]);
assertEquals(1, x[4]);
}
/**
* Test for PreparedStatement batch with variable parameter types.
*/
public void testPrepStmtVariableParams() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("create table #testbatch (id int, data int, PRIMARY KEY (id))");
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #testbatch VALUES (?, convert(int, ?))");
for (int i = 0; i < 5; i++) {
pstmt.setInt(1, i);
if (i == 2) {
// This statement will require a string param instead of an int
pstmt.setString(2, "123");
} else {
pstmt.setInt(2, 123);
}
pstmt.addBatch();
}
int x[];
try {
x = pstmt.executeBatch();
} catch (BatchUpdateException e) {
x = e.getUpdateCounts();
}
assertEquals(5, x.length);
assertEquals(1, x[0]);
assertEquals(1, x[1]);
assertEquals(1, x[2]);
assertEquals(1, x[3]);
assertEquals(1, x[4]);
ResultSet rs = stmt.executeQuery("SELECT * FROM #testbatch");
assertNotNull(rs);
int i = 0;
while (rs.next()) {
assertEquals(123, rs.getInt(2));
i++;
}
assertEquals(5, i);
}
/**
* Test batched callable statements where the call has no parameters.
*/
public void testCallStmtNoParams() throws Exception {
dropProcedure("jTDS_PROC");
try {
Statement stmt = con.createStatement();
stmt.execute("create table #testbatch (id numeric(10) identity, data varchar(255))");
stmt.execute("create proc jTDS_PROC as " +
"INSERT INTO #testbatch (data) VALUES ('same each time')");
CallableStatement cstmt = con.prepareCall("{call jTDS_PROC}");
for (int i = 0; i < 5; i++) {
cstmt.addBatch();
}
int x[];
try {
x = cstmt.executeBatch();
} catch (BatchUpdateException e) {
x = e.getUpdateCounts();
}
assertEquals(5, x.length);
assertEquals(1, x[0]);
assertEquals(1, x[1]);
assertEquals(1, x[2]);
assertEquals(1, x[3]);
assertEquals(1, x[4]);
} finally {
dropProcedure("jTDS_PROC");
}
}
/**
* Helper thread used by testConcurrentBatching() to execute a batch within a transaction that is
* then rolled back. Starting a couple of these threads concurrently should show whether there are any race
* conditions WRT preparation and execution in the batching implementation.
*/
private class ConcurrentBatchingHelper extends Thread {
/** Connection on which to do the work. */
private Connection con;
/** Container to store any exceptions into. */
private Vector exceptions;
ConcurrentBatchingHelper(Connection con, Vector exceptions) {
this.con = con;
this.exceptions = exceptions;
}
public void run() {
try {
PreparedStatement pstmt = con.prepareStatement(
"insert into #testConcurrentBatch (v1, v2, v3, v4, v5, v6) values (?, ?, ?, ?, ?, ?)");
for (int i = 0; i < 64; ++i) {
// Make sure we end up with 64 different prepares, use the binary representation of i to set each
// of the 6 parameters to either an int or a string.
int mask = i;
for (int j = 1; j <= 6; ++j, mask >>= 1) {
if ((mask & 1) != 0) {
pstmt.setInt(j, i);
} else {
pstmt.setString(j, String.valueOf(i));
}
}
pstmt.addBatch();
}
int x[];
try {
x = pstmt.executeBatch();
} catch (BatchUpdateException e) {
e.printStackTrace();
x = e.getUpdateCounts();
}
if (x.length != 64) {
throw new SQLException("Expected 64 update counts, got " + x.length);
}
for (int i = 0; i < x.length; ++i) {
if (x[i] != 1) {
throw new SQLException("Error at position " + i + ", got " + x[i] + " instead of 1");
}
}
// Rollback the transaction, exposing any race conditions.
con.rollback();
pstmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
exceptions.add(ex);
}
}
}
/**
* Test batched prepared statement concurrency. Batch prepares must not disappear between the moment when they
* were created and when they are executed.
*/
public void testConcurrentBatching() throws Exception {
// Create a connection with a batch size of 1. This should cause prepares and actual batch execution to become
// interspersed (if correct synchronization is not in place) and greatly increase the chance of prepares
// being rolled back before getting executed.
Properties props = new Properties();
props.setProperty(Messages.get(net.sourceforge.jtds.jdbc.Driver.BATCHSIZE), "1");
props.setProperty(Messages.get(net.sourceforge.jtds.jdbc.Driver.PREPARESQL),
String.valueOf(TdsCore.TEMPORARY_STORED_PROCEDURES));
Connection con = getConnection(props);
try {
Statement stmt = con.createStatement();
stmt.execute("create table #testConcurrentBatch (v1 int, v2 int, v3 int, v4 int, v5 int, v6 int)");
stmt.close();
Vector exceptions = new Vector();
con.setAutoCommit(false);
Thread t1 = new ConcurrentBatchingHelper(con, exceptions);
Thread t2 = new ConcurrentBatchingHelper(con, exceptions);
t1.start();
t2.start();
t1.join();
t2.join();
assertEquals(0, exceptions.size());
} finally {
con.close();
}
}
/**
* this is a test for the data truncation problem described in bug [2731952]
*/
public void testDataTruncation() throws SQLException {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #DATATRUNC (id int, data text)");
stmt.close();
// create 2 different strings
StringBuffer sb1 = new StringBuffer(10000);
StringBuffer sb2 = new StringBuffer(100);
for (int i=1; i<=1000; i++) {
sb1.append(" +++ ").append(" ".substring(String.valueOf(i).length())).append(i).append("\n");
}
for (int i=1; i<=10; i++) {
sb2.append(" --- ").append(" ".substring(String.valueOf(i).length())).append(i).append("\n");
}
String string1 = sb1.toString();
String string2 = sb2.toString();
PreparedStatement pstmt = con.prepareStatement("insert into #DATATRUNC (id, data) values (?, ?)");
// insert both values into DB in batch mode
pstmt.setInt(1, 1);
pstmt.setString(2, string1);
pstmt.addBatch();
pstmt.setInt(1, 2);
pstmt.setString(2, string2);
pstmt.addBatch();
assertTrue(Arrays.equals(new int[] {1, 1},pstmt.executeBatch()));
// insert first string again, no batch
pstmt.setInt(1, 3);
pstmt.setString(2, string1);
assertEquals(1,pstmt.executeUpdate());
pstmt.close();
// ensure all 3 entries are still intact
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select data from #DATATRUNC order by id asc");
// 1st value, should be string1
assertTrue(rs.next());
String value = rs.getString(1);
assertEquals(string1.length(), value.length());
assertEquals(string1, value);
// 2nd value, should be string2
assertTrue(rs.next());
value = rs.getString(1);
assertEquals(string2.length(), value.length());
assertEquals(string2, value);
// 3rd value, should be string1
assertTrue(rs.next());
value = rs.getString(1);
assertEquals(string1.length(), value.length());
assertEquals(string1, value);
rs.close();
stmt.close();
}
/**
* test for bug [2827931] that implicitly also tests for bug [1811383]
*
* example for statement that produces multiple update counts unexpectedly:
* IF sessionproperty('ARITHABORT') = 0 SET ARITHABORT ON
*/
public void testBatchUpdateCounts() throws SQLException {
Statement statement = con.createStatement();
statement.execute("CREATE TABLE #BATCHUC (id int)");
statement.addBatch("insert into #BATCHUC values (1)");
statement.addBatch("insert into #BATCHUC values (2);insert into #BATCHUC values (3)");
statement.addBatch("insert into #BATCHUC values (4);insert into #BATCHUC values (5);insert into #BATCHUC values (6)");
// below: create identifiable update counts to show if/how far they have been shifted due to bug [2827931]
statement.addBatch("insert into #BATCHUC select * from #BATCHUC");
statement.addBatch("insert into #BATCHUC select * from #BATCHUC where id=999");
statement.addBatch("insert into #BATCHUC select * from #BATCHUC where id=999");
statement.addBatch("insert into #BATCHUC select * from #BATCHUC where id=999");
statement.addBatch("insert into #BATCHUC select * from #BATCHUC where id=999");
assertEquals(array2String(new int[]{1,2,3,6,0,0,0,0,0,0}),array2String(statement.executeBatch()));
statement.close();
}
private static String array2String(int[] a) {
if (a == null)
return "null";
int iMax = a.length - 1;
if (iMax == -1)
return "[]";
StringBuffer b = new StringBuffer();
b.append('[');
for (int i = 0; ; i++) {
b.append(a[i]);
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
public static void main(String[] args) {
junit.textui.TestRunner.run(BatchTest.class);
}
} libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/TimeZoneTest.java 0000644 0001750 0001750 00000012733 11316672660 026453 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2005 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.sql.*;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import net.sourceforge.jtds.jdbc.Support;
/**
* Tests timezone conversions when setting and getting data to and from the
* database.
*
* @author Mike Hutchinson
*/
public class TimeZoneTest extends TestBase {
public TimeZoneTest(String name) {
super(name);
}
/**
* Test timezone calendar conversions. This test produces the same results
* when run with both jConnect 6.0 and the MS JDBC driver.
*/
public void testTimeZone() throws Exception {
TimeZone zone = TimeZone.getDefault();
try {
Statement stmt = con.createStatement();
stmt.execute(
"CREATE TABLE #TEST (d datetime, t datetime, ts datetime)");
PreparedStatement pstmt =
con.prepareStatement("INSERT INTO #TEST VALUES(?, ?, ?) ");
TimeZone tz1 = TimeZone.getTimeZone("America/New_York");
GregorianCalendar calNY = new GregorianCalendar(tz1);
GregorianCalendar originalCalNY = new GregorianCalendar(tz1);
originalCalNY.setTime(calNY.getTime());
//
// Store date/times with local time zone
//
Date date = Date.valueOf("2005-04-06");
Time time = Time.valueOf("09:55:30");
Timestamp ts = Timestamp.valueOf("2005-04-06 09:55:30.123");
pstmt.setDate(1, date);
pstmt.setTime(2, time);
pstmt.setTimestamp(3, ts);
assertEquals(1, pstmt.executeUpdate());
//
// Store date/times with other time zone
//
pstmt.setDate(1, date, calNY);
assertEquals(originalCalNY, calNY);
pstmt.setTime(2, time, calNY);
assertEquals(originalCalNY, calNY);
pstmt.setTimestamp(3, ts, calNY);
assertEquals(originalCalNY, calNY);
assertEquals(1, pstmt.executeUpdate());
assertEquals(1, pstmt.executeUpdate());
//
// Read back
//
ResultSet rs = stmt.executeQuery("SELECT * FROM #TEST");
assertTrue(rs.next());
//
// Check local time zone gets back what we stored
//
assertEquals("2005-04-06", rs.getDate(1).toString());
assertEquals("09:55:30", rs.getTime(2).toString());
assertEquals("2005-04-06 09:55:30.123",
rs.getTimestamp(3).toString());
assertTrue(rs.next());
//
// Check date/times stored with other zone are changed when read
// back with local.
// The date changes because the JDBC Date has time set to 0:0:0 so
// the change of zone moves us back a day.
// The time moves for me because the JDBC Time has the date set to
// 1970-01-01 and in 1970 the "europe/london" time zone was
// experimenting with permanent daylight saving time! If you are
// running this test anywhere other than the UK you will find that
// the time is the same as the time component of the timestamp.
// Note both the other drivers I tested exhibit the same behaviour.
//
assertEquals(new Date(Support.timeFromZone(date, calNY)).toString(),
rs.getDate(1).toString());
assertEquals(originalCalNY, calNY);
assertEquals(new Time(Support.timeFromZone(time, calNY)).toString(),
rs.getTime(2).toString());
assertEquals(originalCalNY, calNY);
assertEquals(new Timestamp(Support.timeFromZone(ts, calNY)).toString(),
rs.getTimestamp(3).toString());
assertEquals(originalCalNY, calNY);
assertTrue(rs.next());
//
// Check date/times stored with other zone are unchanged when read
// back with other zone
//
assertEquals("2005-04-05", rs.getDate(1, calNY).toString());
assertEquals(originalCalNY, calNY);
assertEquals("09:55:30", rs.getTime(2, calNY).toString());
assertEquals(originalCalNY, calNY);
assertEquals("2005-04-06 09:55:30.123", rs.getTimestamp(3, calNY).toString());
assertEquals(originalCalNY, calNY);
} finally {
TimeZone.setDefault(zone);
}
}
public static void main(String[] args) {
junit.textui.TestRunner.run(TimeZoneTest.class);
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/LargeLOBTest.java 0000644 0001750 0001750 00000007315 11316672660 026310 0 ustar martin martin //jTDS JDBC Driver for Microsoft SQL Server and Sybase
//Copyright (C) 2004 The jTDS Project
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.io.*;
import java.sql.*;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
* @version 1.0
*/
public class LargeLOBTest extends TestBase {
private static final int LOB_LENGTH = 100000000;
/**
* Only run the test suite if the "jTDS.runLargeLOBTest" system property is defined, as the test takes A LOT of time
* to execute.
*/
public static Test suite() {
if (System.getProperty("jTDS.runLargeLOBTest") == null) {
return new TestSuite();
}
return new TestSuite(LargeLOBTest.class);
}
public LargeLOBTest(String name) {
super(name);
}
/*************************************************************************
*************************************************************************
** BLOB TESTS **
*************************************************************************
*************************************************************************/
/**
* Test for bug [945507] closing statement after selecting a large IMAGE - Exception
*/
public void testLargeBlob1() throws Exception {
File data = File.createTempFile("blob", ".tmp");
data.deleteOnExit();
FileOutputStream fos = new FileOutputStream(data);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte buf[] = new byte[256];
for (int i = 0; i < 256; i++) {
buf[i] = (byte) i;
}
for (int i = 0; i < LOB_LENGTH; i += buf.length) {
bos.write(buf);
}
bos.write(buf, 0, LOB_LENGTH % buf.length);
bos.close();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #largeblob1 (data IMAGE)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #largeblob1 (data) VALUES (?)");
FileInputStream fis = new FileInputStream(data);
BufferedInputStream bis = new BufferedInputStream(fis);
// Test PreparedStatement.setBinaryStream()
pstmt.setBinaryStream(1, bis, LOB_LENGTH);
assertTrue(pstmt.executeUpdate() == 1);
pstmt.close();
bis.close();
Statement stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery("SELECT data FROM #largeblob1");
assertTrue(rs.next());
fis = new FileInputStream(data);
bis = new BufferedInputStream(fis);
// Test ResultSet.getBinaryStream()
compareInputStreams(bis, rs.getBinaryStream(1));
bis.close();
assertFalse(rs.next());
stmt2.close();
rs.close();
assertTrue(data.delete());
}
public static void main(String[] args) {
junit.textui.TestRunner.run(LOBTest.class);
}
} libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/UpdateTest.java 0000644 0001750 0001750 00000004417 11316672660 026143 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.sql.*;
/**
* @author Alin Sinpalean
* @version $Id: UpdateTest.java,v 1.9.2.1 2009/08/04 10:33:54 ickzon Exp $
* @created March 17, 2001
*/
public class UpdateTest extends TestBase {
public UpdateTest(String name) {
super(name);
}
public void testTemp() throws Exception {
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmt.execute("CREATE TABLE #temp (pk INT PRIMARY KEY, f_string VARCHAR(30), f_float FLOAT)");
// populate in the traditional way
final int count = 100;
for (int i = 0; i < count; i++) {
stmt.execute(
"INSERT INTO #temp "
+ "VALUES( " + i
+ "," + "'The String " + i + "'"
+ ", " + i + ")"
);
}
dump(stmt.executeQuery("SELECT Count(*) FROM #temp"));
//Navigate around
ResultSet rs = stmt.executeQuery("SELECT * FROM #temp");
assertTrue(rs.first());
assertEquals(1, rs.getRow());
assertTrue(rs.last());
assertEquals(count, rs.getRow());
assertTrue(rs.first());
assertEquals(1, rs.getRow());
rs.close();
stmt.close();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(UpdateTest.class);
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/JDBC3Test.java 0000644 0001750 0001750 00000013466 11316672660 025512 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ParameterMetaData;
import java.sql.Types;
import java.math.BigDecimal;
/**
* Test for miscellaneous JDBC 3.0 features.
*
* @author Alin Sinpalean
* @version $Id: JDBC3Test.java,v 1.3.2.1 2009/08/04 10:33:54 ickzon Exp $
*/
public class JDBC3Test extends TestBase {
public JDBC3Test(String name) {
super(name);
}
/**
* Test return of multiple open result sets from one execute.
*/
public void testMultipleResults() throws Exception {
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
//
// Create 4 test tables
//
for (int rs = 1; rs <= 4; rs++) {
stmt.execute("CREATE TABLE #TESTRS" + rs + " (id int, data varchar(255))");
for (int row = 1; row <= 10; row++) {
assertEquals(1, stmt.executeUpdate("INSERT INTO #TESTRS" + rs +
" VALUES(" + row + ", 'TABLE " + rs + " ROW " + row + "')"));
}
}
assertTrue(stmt.execute(
"SELECT * FROM #TESTRS1\r\n" +
"SELECT * FROM #TESTRS2\r\n" +
"SELECT * FROM #TESTRS3\r\n" +
"SELECT * FROM #TESTRS4\r\n"));
ResultSet rs = stmt.getResultSet();
assertTrue(rs.next());
assertEquals("TABLE 1 ROW 1", rs.getString(2));
// Get RS 2 keeping RS 1 open
assertTrue(stmt.getMoreResults(Statement.KEEP_CURRENT_RESULT));
ResultSet rs2 = stmt.getResultSet();
assertTrue(rs2.next());
assertEquals("TABLE 2 ROW 1", rs2.getString(2));
// Check RS 1 still open and on row 1
assertEquals("TABLE 1 ROW 1", rs.getString(2));
// Read a cached row from RS 1
assertTrue(rs.next());
assertEquals("TABLE 1 ROW 2", rs.getString(2));
// Close RS 2 but keep RS 1 open and get RS 3
assertTrue(stmt.getMoreResults(Statement.CLOSE_CURRENT_RESULT));
ResultSet rs3 = stmt.getResultSet();
assertTrue(rs3.next());
assertEquals("TABLE 3 ROW 1", rs3.getString(2));
// Check RS 2 is closed
try {
assertEquals("TABLE 2 ROW 1", rs2.getString(2));
fail("Expected RS 2 to be closed!");
} catch (SQLException e) {
// Ignore
}
// Check RS 1 is still open
assertEquals("TABLE 1 ROW 2", rs.getString(2));
// Close all result sets and get RS 4
assertTrue(stmt.getMoreResults(Statement.CLOSE_ALL_RESULTS));
ResultSet rs4 = stmt.getResultSet();
assertTrue(rs4.next());
assertEquals("TABLE 4 ROW 1", rs4.getString(2));
// check RS 1 is now closed as well
try {
assertEquals("TABLE 1 ROW 2", rs.getString(2));
fail("Expected RS 1 to be closed!");
} catch (SQLException e) {
// Ignore
}
assertFalse(stmt.getMoreResults());
stmt.close();
}
/**
* Test closing a ResultSet when it's out of scope.
*
* If a finalize() method which tries to call close() is added to
* JtdsResultSet the next() calls will be executed concurrently with any
* other result processing, with no synchronization whatsoever.
*/
public void testSocketConcurrency5() throws Exception {
Statement stmt = con.createStatement();
assertTrue(stmt.execute(
"SELECT 1 SELECT 2, 3"));
ResultSet rs = stmt.getResultSet();
assertTrue(stmt.getMoreResults(Statement.KEEP_CURRENT_RESULT));
ResultSet rs2 = stmt.getResultSet();
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertFalse(rs.next());
rs.close();
assertTrue(rs2.next());
assertEquals(2, rs2.getInt(1));
assertEquals(3, rs2.getInt(2));
assertFalse(rs2.next());
rs2.close();
stmt.close();
}
/**
* Test for bug [1222205] getParameterMetaData returns not implemented.
*/
public void testGetParamMetaData() throws SQLException {
PreparedStatement pstmt = con.prepareStatement("SELECT ?,?,?");
pstmt.setString(1, "TEST");
pstmt.setBigDecimal(2, new BigDecimal("123.45"));
pstmt.setBoolean(3, true);
ParameterMetaData pmd = pstmt.getParameterMetaData();
assertEquals(3, pmd.getParameterCount());
assertEquals(Types.VARCHAR, pmd.getParameterType(1));
assertEquals("java.lang.String", pmd.getParameterClassName(1));
assertEquals(2, pmd.getScale(2));
assertEquals(38, pmd.getPrecision(2));
assertEquals(ParameterMetaData.parameterModeIn,
pmd.getParameterMode(3));
pstmt.close();
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/ReadTextTest.java 0000644 0001750 0001750 00000015750 11316672660 026443 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.sql.*;
import java.io.*;
/**
* Test case to illustrate use of READTEXT for text and image columns.
*
* @version 1.0
*/
public class ReadTextTest extends TestBase {
public ReadTextTest(String name) {
super(name);
}
public void testReadText() throws Exception {
byte[] byteBuf = new byte[5000]; // Just enough to require more than one READTEXT
for (int i = 0; i < byteBuf.length; i++) {
byteBuf[i] = (byte) i;
}
StringBuffer strBuf = new StringBuffer(5000);
for (int i = 0; i < 100; i++) {
strBuf.append("This is a test line of text that is 50 chars ");
if (i < 10) {
strBuf.append('0');
}
strBuf.append(i);
}
String data = strBuf.toString();
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #TEST (id int, t1 text, t2 ntext, t3 image)");
PreparedStatement pstmt = con.prepareStatement("INSERT INTO #TEST (id, t1, t2, t3) VALUES (?, ?, ?, ?)");
pstmt.setInt(1, 1);
try {
pstmt.setAsciiStream(2, new ByteArrayInputStream(strBuf.toString().getBytes("US-ASCII")), strBuf.length());
pstmt.setCharacterStream(3, new StringReader(strBuf.toString()), strBuf.length());
pstmt.setBinaryStream(4, new ByteArrayInputStream(byteBuf), byteBuf.length);
} catch (UnsupportedEncodingException e) {
// Should never happen
}
assertEquals("First insert failed", 1, pstmt.executeUpdate());
pstmt.setInt(1, 2);
try {
pstmt.setCharacterStream(2, new StringReader(strBuf.toString()), strBuf.length());
pstmt.setAsciiStream(3, new ByteArrayInputStream(strBuf.toString().getBytes("US-ASCII")), strBuf.length());
pstmt.setBinaryStream(4, new ByteArrayInputStream(byteBuf), byteBuf.length);
} catch (UnsupportedEncodingException e) {
// Should never happen
}
assertEquals("Second insert failed", 1, pstmt.executeUpdate());
// Read back the normal way
ResultSet rs = stmt.executeQuery("SELECT * FROM #TEST");
validateReadTextResult(rs, data, byteBuf);
// Read back using READTEXT
// FIXME - Trigger use of READTEXT
rs = stmt.executeQuery("SELECT * FROM #TEST");
validateReadTextResult(rs, data, byteBuf);
pstmt.close();
stmt.close();
}
private void validateReadTextResult(ResultSet rs, String data, byte[] byteBuf)
throws Exception {
assertNotNull(rs);
while (rs.next()) {
switch (rs.getInt(1)) {
case 1:
InputStream in = rs.getAsciiStream(2);
compareInputStreams(new ByteArrayInputStream(data.getBytes("ASCII")), in);
Clob clob = rs.getClob(2);
// Check the clob stream 3 times to ensure the stream is being
// reset properly
for (int count = 0; count < 3; count++) {
in = clob.getAsciiStream();
compareInputStreams(new ByteArrayInputStream(data.getBytes("ASCII")), in);
}
Reader rin = rs.getCharacterStream(3);
compareReaders(new StringReader(data), rin);
clob = rs.getClob(3);
// Check the clob stream 3 times to ensure the stream is being
// reset properly
for (int count = 0; count < 3; count++) {
rin = clob.getCharacterStream();
compareReaders(new StringReader(data), rin);
}
in = rs.getBinaryStream(4);
compareInputStreams(new ByteArrayInputStream(byteBuf), in);
Blob blob = rs.getBlob(4);
// Check the blob stream 3 times to ensure the stream is being
// reset properly
for (int count = 0; count < 3; count++) {
in = blob.getBinaryStream();
compareInputStreams(new ByteArrayInputStream(byteBuf), in);
}
break;
case 2:
rin = rs.getCharacterStream(2);
compareReaders(new StringReader(data), rin);
clob = rs.getClob(2);
// Check the clob stream 3 times to ensure the stream is being
// reset properly
for (int count = 0; count < 3; count++) {
rin = clob.getCharacterStream();
compareReaders(new StringReader(data), rin);
}
in = rs.getAsciiStream(3);
compareInputStreams(new ByteArrayInputStream(data.getBytes("ASCII")), in);
clob = rs.getClob(3);
// Check the clob stream 3 times to ensure the stream is being
// reset properly
for (int count = 0; count < 3; count++) {
in = clob.getAsciiStream();
compareInputStreams(new ByteArrayInputStream(data.getBytes("ASCII")), in);
}
in = rs.getBinaryStream(4);
compareInputStreams(new ByteArrayInputStream(byteBuf), in);
blob = rs.getBlob(4);
// Check the blob stream 3 times to ensure the stream is being
// reset properly
for (int count = 0; count < 3; count++) {
in = blob.getBinaryStream();
compareInputStreams(new ByteArrayInputStream(byteBuf), in);
}
break;
}
}
rs.close();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(ReadTextTest.class);
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/DatabaseTestCase.java 0000644 0001750 0001750 00000013374 11316672660 027223 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.sql.*;
import java.util.Map;
import java.math.BigDecimal;
/**
* @author Alin Sinpalean
* @version $Id: DatabaseTestCase.java,v 1.8.6.1 2009/08/04 10:33:54 ickzon Exp $
*/
public abstract class DatabaseTestCase extends TestBase {
private static Map typemap = null;
public DatabaseTestCase(String name) {
super(name);
}
protected void dropTable(String tableName) throws SQLException {
String sobName = "sysobjects";
String tableLike = tableName;
if (tableName.startsWith("#")) {
sobName = "tempdb.dbo.sysobjects";
tableLike = tableName + "%";
}
Statement stmt = con.createStatement();
stmt.executeUpdate(
"if exists (select * from " + sobName + " where name like '" + tableLike + "' and type = 'U') "
+ "drop table " + tableName);
stmt.close();
}
protected void dropProcedure(String procname) throws SQLException {
Statement stmt = con.createStatement();
dropProcedure(stmt, procname);
stmt.close();
}
protected void dropProcedure(Statement stmt, String procname) throws SQLException {
String sobName = "sysobjects";
if (procname.startsWith("#")) {
sobName = "tempdb.dbo.sysobjects";
}
stmt.executeUpdate(
"if exists (select * from " + sobName + " where name like '" + procname + "%' and type = 'P') "
+ "drop procedure " + procname);
}
protected void dropFunction(String procname) throws SQLException {
String sobName = "sysobjects";
Statement stmt = con.createStatement();
stmt.executeUpdate(
"if exists (select * from " + sobName + " where name like '" + procname + "%' and type = 'FN') "
+ "drop function " + procname);
stmt.close();
}
// return -1 if a1ResultSets with over 255 columns.
*/
public void testMoreThan255Columns() throws Exception
{
Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
// create the table
int cols = 260;
StringBuffer create = new StringBuffer("create table #manycolumns (");
for (int i=0; iResultSet if the primary key is updated.
*/
public void testUpdateRowDuplicatesRow() throws Exception
{
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
stmt.executeUpdate(
"create table #updateRowDuplicatesRow (val int primary key)");
stmt.executeUpdate(
"insert into #updateRowDuplicatesRow (val) values (1)");
stmt.executeUpdate(
"insert into #updateRowDuplicatesRow (val) values (2)");
stmt.executeUpdate(
"insert into #updateRowDuplicatesRow (val) values (3)");
ResultSet rs = stmt.executeQuery(
"select val from #updateRowDuplicatesRow order by val");
for (int i = 0; i < 3; i++) {
assertTrue(rs.next());
assertFalse(rs.rowUpdated());
assertFalse(rs.rowInserted());
assertFalse(rs.rowDeleted());
rs.updateInt(1, rs.getInt(1) + 10);
rs.updateRow();
assertFalse(rs.rowUpdated());
assertFalse(rs.rowInserted());
assertTrue(rs.rowDeleted());
}
for (int i = 11; i <= 13; i++) {
assertTrue(rs.next());
assertFalse(rs.rowUpdated());
assertFalse(rs.rowInserted());
assertFalse(rs.rowDeleted());
assertEquals(i, rs.getInt(1));
}
rs.close();
stmt.close();
}
/**
* Test that updated rows are modified in place if the primary key is not
* updated.
*/
public void testUpdateRowUpdatesRow() throws Exception
{
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
stmt.executeUpdate(
"create table #updateRowUpdatesRow (id int primary key, val int)");
stmt.executeUpdate(
"insert into #updateRowUpdatesRow (id, val) values (1, 1)");
stmt.executeUpdate(
"insert into #updateRowUpdatesRow (id, val) values (2, 2)");
stmt.executeUpdate(
"insert into #updateRowUpdatesRow (id, val) values (3, 3)");
ResultSet rs = stmt.executeQuery(
"select id, val from #updateRowUpdatesRow order by id");
for (int i = 0; i < 3; i++) {
assertTrue(rs.next());
assertFalse(rs.rowUpdated());
assertFalse(rs.rowInserted());
assertFalse(rs.rowDeleted());
rs.updateInt(2, rs.getInt(2) + 10);
rs.updateRow();
assertFalse(rs.rowUpdated());
assertFalse(rs.rowInserted());
assertFalse(rs.rowDeleted());
assertEquals(rs.getInt(1) + 10, rs.getInt(2));
}
assertFalse(rs.next());
rs.close();
stmt.close();
}
/**
* Test that deleted rows are not removed but rather marked as deleted.
*/
public void testDeleteRowMarksDeleted() throws Exception
{
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
stmt.executeUpdate(
"create table #deleteRowMarksDeleted (val int primary key)");
stmt.executeUpdate(
"insert into #deleteRowMarksDeleted (val) values (1)");
stmt.executeUpdate(
"insert into #deleteRowMarksDeleted (val) values (2)");
stmt.executeUpdate(
"insert into #deleteRowMarksDeleted (val) values (3)");
ResultSet rs = stmt.executeQuery(
"select val from #deleteRowMarksDeleted order by val");
for (int i = 0; i < 3; i++) {
assertTrue(rs.next());
assertFalse(rs.rowUpdated());
assertFalse(rs.rowInserted());
assertFalse(rs.rowDeleted());
rs.deleteRow();
assertFalse(rs.rowUpdated());
assertFalse(rs.rowInserted());
assertTrue(rs.rowDeleted());
}
assertFalse(rs.next());
rs.close();
stmt.close();
}
/**
* Test for bug [1170777] resultSet.updateRow() fails if no row has been
* changed.
*/
public void testUpdateRowNoChanges() throws Exception {
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
stmt.executeUpdate(
"create table #deleteRowMarksDeleted (val int primary key)");
stmt.executeUpdate(
"insert into #deleteRowMarksDeleted (val) values (1)");
ResultSet rs = stmt.executeQuery(
"select val from #deleteRowMarksDeleted order by val");
assertTrue(rs.next());
// This should not crash; it should be a no-op
rs.updateRow();
rs.refreshRow();
assertEquals(1, rs.getInt(1));
assertFalse(rs.next());
rs.close();
stmt.close();
}
/**
* Test the behavior of sp_cursorfetch with fetch sizes
* greater than 1.
* * Assertions tested: *
ResultSet the requested number of rows is returned,
* starting with row 1 and the error code returned is non-zero (2).
* absolute(-1) works the same as last().
*/
public void testAbsoluteMinusOne() throws Exception {
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
stmt.executeUpdate(
"create table #absoluteMinusOne (val int primary key)");
stmt.executeUpdate(
"insert into #absoluteMinusOne (val) values (1)");
stmt.executeUpdate(
"insert into #absoluteMinusOne (val) values (2)");
stmt.executeUpdate(
"insert into #absoluteMinusOne (val) values (3)");
ResultSet rs = stmt.executeQuery(
"select val from #absoluteMinusOne order by val");
rs.absolute(-1);
assertTrue(rs.isLast());
assertEquals(3, rs.getInt(1));
assertFalse(rs.next());
rs.last();
assertTrue(rs.isLast());
assertEquals(3, rs.getInt(1));
assertFalse(rs.next());
rs.close();
stmt.close();
}
/**
* Test that calling absolute() with very large positive
* values positions the cursor after the last row and with very large
* negative values positions the cursor before the first row.
*/
public void testAbsoluteLargeValue() throws SQLException {
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
stmt.executeUpdate(
"create table #absoluteLargeValue (val int primary key)");
stmt.executeUpdate(
"insert into #absoluteLargeValue (val) values (1)");
stmt.executeUpdate(
"insert into #absoluteLargeValue (val) values (2)");
stmt.executeUpdate(
"insert into #absoluteLargeValue (val) values (3)");
ResultSet rs = stmt.executeQuery(
"select val from #absoluteLargeValue order by val");
assertFalse(rs.absolute(10));
assertEquals(0, rs.getRow());
assertTrue(rs.isAfterLast());
assertFalse(rs.next());
assertEquals(0, rs.getRow());
assertTrue(rs.isAfterLast());
assertFalse(rs.absolute(-10));
assertEquals(0, rs.getRow());
assertTrue(rs.isBeforeFirst());
assertFalse(rs.previous());
assertEquals(0, rs.getRow());
assertTrue(rs.isBeforeFirst());
rs.close();
stmt.close();
}
/**
* Test that calling absolute() with very large positive
* values positions the cursor after the last row and with very large
* negative values positions the cursor before the first row.
*/
public void testRelativeLargeValue() throws SQLException {
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
stmt.executeUpdate(
"create table #relativeLargeValue (val int primary key)");
stmt.executeUpdate(
"insert into #relativeLargeValue (val) values (1)");
stmt.executeUpdate(
"insert into #relativeLargeValue (val) values (2)");
stmt.executeUpdate(
"insert into #relativeLargeValue (val) values (3)");
ResultSet rs = stmt.executeQuery(
"select val from #relativeLargeValue order by val");
assertFalse(rs.relative(10));
assertEquals(0, rs.getRow());
assertTrue(rs.isAfterLast());
assertFalse(rs.next());
assertEquals(0, rs.getRow());
assertTrue(rs.isAfterLast());
assertFalse(rs.relative(-10));
assertEquals(0, rs.getRow());
assertTrue(rs.isBeforeFirst());
assertFalse(rs.previous());
assertEquals(0, rs.getRow());
assertTrue(rs.isBeforeFirst());
rs.close();
stmt.close();
}
/**
* Test that read() works ok on the stream returned by
* ResultSet.getUnicodeStream() (i.e. it doesn't always fill
* the buffer, regardless of whether there's available data or not).
*/
public void testUnicodeStream() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #unicodeStream (val varchar(255))");
stmt.executeUpdate("insert into #unicodeStream (val) values ('test')");
ResultSet rs = stmt.executeQuery("select val from #unicodeStream");
if (rs.next()) {
byte[] buf = new byte[8000];
InputStream is = rs.getUnicodeStream(1);
int length = is.read(buf);
assertEquals(4 * 2, length);
}
rs.close();
stmt.close();
}
/**
* Check whether Statement.setMaxRows() works okay, bug
* [1812686].
*/
public void testMaxRows() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #statementMaxRows (val int)");
stmt.close();
// insert 1000 rows
PreparedStatement pstmt = con.prepareStatement("insert into #statementMaxRows values (?)");
for (int i = 0; i < 1000; i++) {
pstmt.setInt(1, i);
assertEquals(1, pstmt.executeUpdate());
}
pstmt.close();
stmt = con.createStatement();
// set maxRows to 100
stmt.setMaxRows(100);
// select all rows (should only return 100 rows)
ResultSet rs = stmt.executeQuery("select * from #statementMaxRows");
int rows = 0;
while (rs.next()) {
rows++;
}
assertEquals(100, rows);
rs.close();
stmt.close();
}
/**
* Test that Statement.setMaxRows() works on cursor
* ResultSets.
*/
public void testCursorMaxRows() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #cursorMaxRows (val int)");
stmt.close();
// Insert 10 rows
PreparedStatement pstmt = con.prepareStatement(
"insert into #cursorMaxRows (val) values (?)");
for (int i = 0; i < 10; i++) {
pstmt.setInt(1, i);
assertEquals(1, pstmt.executeUpdate());
}
pstmt.close();
// Create a cursor ResultSet
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
// Set maxRows to 5
stmt.setMaxRows(5);
// Select all (should only return 5 rows)
ResultSet rs = stmt.executeQuery("select * from #cursorMaxRows");
rs.last();
assertEquals(5, rs.getRow());
rs.beforeFirst();
int cnt = 0;
while (rs.next()) {
cnt++;
}
assertEquals(5, cnt);
rs.close();
stmt.close();
}
/**
* Test for bug [1075977] setObject() causes SQLException.
*
* Conversion of float values to String adds
* grouping to the value, which cannot then be parsed.
*/
public void testSetObjectScale() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("create table #testsetobj (i int)");
PreparedStatement pstmt =
con.prepareStatement("insert into #testsetobj values(?)");
// next line causes sqlexception
pstmt.setObject(1, new Float(1234.5667), Types.INTEGER, 0);
assertEquals(1, pstmt.executeUpdate());
ResultSet rs = stmt.executeQuery("select * from #testsetobj");
assertTrue(rs.next());
assertEquals("1234", rs.getString(1));
}
/**
* Test that ResultSet.previous() works correctly on cursor
* ResultSets.
*/
public void testCursorPrevious() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #cursorPrevious (val int)");
stmt.close();
// Insert 10 rows
PreparedStatement pstmt = con.prepareStatement(
"insert into #cursorPrevious (val) values (?)");
for (int i = 0; i < 10; i++) {
pstmt.setInt(1, i);
assertEquals(1, pstmt.executeUpdate());
}
pstmt.close();
// Create a cursor ResultSet
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
// Set fetch size to 2
stmt.setFetchSize(2);
// Select all
ResultSet rs = stmt.executeQuery("select * from #cursorPrevious");
rs.last();
int i = 10;
do {
assertEquals(i, rs.getRow());
assertEquals(--i, rs.getInt(1));
} while (rs.previous());
assertTrue(rs.isBeforeFirst());
assertEquals(0, i);
rs.close();
stmt.close();
}
/**
* Test the behavior of the ResultSet/Statement/Connection when the JVM
* runs out of memory (hopefully) in the middle of a packet.
*
ResultSet.TYPE_SCROLL_SENSITIVE+1)
* see others' updates. SQL Server only.
*/
public void testDynamicCursors() throws Exception {
final int ROWS = 4;
dropTable("dynamicCursors");
Connection con2 = getConnection();
try {
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE + 1,
ResultSet.CONCUR_READ_ONLY);
stmt.execute("CREATE TABLE dynamicCursors (id int primary key, data varchar(255))");
for (int i = 0; i < ROWS; i++) {
stmt.executeUpdate("INSERT INTO dynamicCursors VALUES(" + i + ", 'Table A line " + i + "')");
}
// Open cursor
ResultSet rs = stmt.executeQuery("SELECT id, data FROM dynamicCursors");
// If not a MSCursorResultSet, give up as it will not see inserts
if (rs.getClass().getName().indexOf("MSCursorResultSet") == -1) {
rs.close();
stmt.close();
return;
}
// Insert new row from other connection
Statement stmt2 = con2.createStatement();
assertEquals(1, stmt2.executeUpdate(
"INSERT INTO dynamicCursors VALUES(" + ROWS + ", 'Table A line " + ROWS + "')"));
stmt2.close();
// Count rows and make sure the newly inserted row is visible
int cnt;
for (cnt = 0; rs.next(); cnt++);
assertEquals(ROWS + 1, cnt);
rs.close();
stmt.close();
} finally {
dropTable("dynamicCursors");
if (con2 != null) {
con2.close();
}
}
}
/**
* Test for bug [1232733] setFetchSize(0) causes exception.
*/
public void testZeroFetchSize() throws Exception {
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(0);
ResultSet rs = stmt.executeQuery("SELECT 1 UNION SELECT 2");
assertTrue(rs.next());
rs.setFetchSize(0);
assertTrue(rs.next());
assertFalse(rs.next());
rs.close();
stmt.close();
}
/**
* Test for bug [1329765] Pseudo column ROWSTAT is back with SQL 2005
* (September CTP).
*/
public void testRowstat() throws Exception {
PreparedStatement stmt = con.prepareStatement("SELECT 'STRING' str",
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery();
assertEquals(1, rs.getMetaData().getColumnCount());
assertTrue(rs.next());
assertFalse(rs.next());
rs.close();
stmt.close();
}
/**
* Test for bug [2051585], TDS Protocol error when 2 ResultSets on the
* same connection are being iterated at the same time.
*/
public void testConcurrentResultSets() throws Exception {
con.setAutoCommit(false);
final int rows = 100;
final int threads = 100;
// prepare test data
Statement stmt = con.createStatement();
stmt.execute("create table #conrs (id int,data varchar(20))");
for (int r=0; r < rows; r++) {
assertEquals(1, stmt.executeUpdate("insert into #conrs values(" + r + ",'test" + r + "')"));
}
stmt.close();
final Thread[] workers = new Thread[threads];
final List errors = new ArrayList();
for (int i=0; i < threads; i++) {
workers[i] = new Thread("thread " + i) {
public void run() {
int i=0;
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from #conrs order by id asc");
for ( ; i < rows; i++) {
assertTrue("premature end of result, only " + i + "of " + rows + " rows present", rs.next());
assertEquals("resultset contains wrong row:", i, rs.getInt(1));
assertEquals("resultset contains wrong column value:", "test" + i, rs.getString(2));
// random delays should ensure that threads are not executed one after another
if (Math.random() < 0.01) {
Thread.sleep(1);
}
}
rs.close();
st.close();
}
catch (Throwable t) {
synchronized (errors) {
errors.add(new Exception(this.getName() + " at row " + i + ": " + t.getMessage()));
}
}
}
};
}
// start all threads
for (int i=0; i < threads; i++) {
workers[i].start();
}
// wait for the threads to finish
for (int i=0; i < threads; i++) {
workers[i].join();
}
assertEquals("[]", array2String(errors.toArray()));
con.setAutoCommit(true);
}
private static String array2String(Object[] a) {
if (a == null)
return "null";
int iMax = a.length - 1;
if (iMax == -1)
return "[]";
StringBuffer b = new StringBuffer();
b.append('[');
for (int i = 0; ; i++) {
b.append(String.valueOf(a[i]));
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
/**
* Test for bug [1855125], numeric overflow not reported by jTDS.
*/
public void testNumericOverflow() throws SQLException {
Statement st = con.createStatement();
st.execute("create table #test(data numeric(30,10))");
assertEquals(1, st.executeUpdate("insert into #test values (10000000000000000000.0000)"));
ResultSet rs = st.executeQuery("select * from #test");
assertTrue(rs.next());
try {
byte b = rs.getByte(1);
assertTrue("expected numeric overflow error, got " + b, false);
} catch (SQLException e) {
assertEquals(e.getSQLState(), "22003");
}
try {
short s = rs.getShort(1);
assertTrue("expected numeric overflow error, got " + s, false);
} catch (SQLException e) {
assertEquals(e.getSQLState(), "22003");
}
try {
int i = rs.getInt(1);
assertTrue("expected numeric overflow error, got " + i, false);
} catch (SQLException e) {
assertEquals(e.getSQLState(), "22003");
}
try {
long l = rs.getLong(1);
assertTrue("expected numeric overflow error, got " + l, false);
} catch (SQLException e) {
assertEquals(e.getSQLState(), "22003");
}
rs.close();
st.close();
}
/**
* Test for bug [2860742], getByte() causes overflow error for negative
* values.
*/
public void testNegativeOverflow() throws SQLException
{
Statement st = con.createStatement();
st.execute("create table #testNegativeOverflow(data int)");
int [] values = new int [] { -1, -128, -129, 127, 128};
boolean[] overflow = new boolean[] {false, false, true, false, true};
for (int i = 0; i < values.length; i++) {
assertEquals(1, st.executeUpdate("insert into #testNegativeOverflow values (" + values[i] + ")"));
}
ResultSet rs = st.executeQuery("select * from #testNegativeOverflow");
for (int i = 0; i < values.length; i++) {
assertTrue(rs.next());
try {
byte b = rs.getByte(1);
assertFalse("expected numeric overflow error for value " + values[i] + ", got " + b, overflow[i]);
} catch (SQLException e) {
assertTrue("unexpected numeric overflow for value " + values[i], overflow[i]);
}
}
rs.close();
st.close();
}
/**
* Test for bug [1840116], Select statement very slow with date parameter.
*/
public void testDatePerformance() throws SQLException {
Statement st = con.createStatement();
st.execute("create table #test(data datetime)");
st.close();
PreparedStatement ps = con.prepareStatement("insert into #test values(?)");
final int iterations = 10000;
final String dateString = "2009-09-03";
// test date value
Date date = Date.valueOf(dateString);
System.gc();
long start = System.currentTimeMillis();
// insert test data using prepared statement
for (int i = 0; i < iterations; i ++) {
ps.setDate(1, date);
ps.executeUpdate();
}
long prep = System.currentTimeMillis() - start;
System.out.println("prepared: " + prep + " ms");
ps.close();
// delete test data
st = con.createStatement();
assertEquals(iterations, st.executeUpdate("delete from #test"));
st.close();
st = con.createStatement();
System.gc();
start = System.currentTimeMillis();
// insert test data using prepared statement
for (int i = 0; i < iterations; i ++) {
st.executeUpdate("insert into #test values(" + dateString + ")");
}
long unprep = System.currentTimeMillis() - start;
System.out.println("inlined : " + unprep + " ms");
st.close();
// prepared statement should be faster
assertTrue(prep < unprep);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(ResultSetTest.class);
}
} libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/CallableStatementJDBC3Test.java 0000644 0001750 0001750 00000010424 11316672660 031006 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.sql.*;
/**
* Test the JDBC 3.0 features of CallableStatement.
*
* @author Alin Sinpalean
* @created 04/07/2004
*/
public class CallableStatementJDBC3Test extends TestBase {
public CallableStatementJDBC3Test(String name) {
super(name);
}
/**
* Test named parameters.
*/
public void testNamedParameters0001() throws Exception {
final String data = "New {order} plus {1} more";
final String outData = "test";
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #csn1 (data VARCHAR(32))");
stmt.close();
stmt = con.createStatement();
stmt.execute("create procedure #sp_csn1 @data VARCHAR(32) OUT as "
+ "INSERT INTO #csn1 (data) VALUES(@data) "
+ "SET @data = '" + outData + "'"
+ "RETURN 13");
stmt.close();
CallableStatement cstmt = con.prepareCall("{?=call #sp_csn1(?)}");
cstmt.registerOutParameter("@return_status", Types.INTEGER);
cstmt.setString("@data", data);
cstmt.registerOutParameter("@data", Types.VARCHAR);
assertEquals(1, cstmt.executeUpdate());
assertFalse(cstmt.getMoreResults());
assertEquals(-1, cstmt.getUpdateCount());
assertEquals(outData, cstmt.getString("@data"));
cstmt.close();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT data FROM #csn1");
assertTrue(rs.next());
assertEquals(data, rs.getString(1));
assertTrue(!rs.next());
rs.close();
stmt.close();
}
/**
* Test for bug [946171] null boolean in CallableStatement bug
*/
public void testCallableRegisterOutParameter1() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("create procedure #rop1 @bool bit, @whatever int OUTPUT as\r\n "
+ "begin\r\n"
+ "set @whatever = 1\r\n"
+ "end");
stmt.close();
try {
CallableStatement cstmt = con.prepareCall("{call #rop1(?,?)}");
cstmt.setNull(1, Types.BOOLEAN);
cstmt.registerOutParameter(2, Types.INTEGER);
cstmt.execute();
assertTrue(cstmt.getInt(2) == 1);
cstmt.close();
} finally {
stmt = con.createStatement();
stmt.execute("drop procedure #rop1");
stmt.close();
}
}
/**
* Test for bug [992715] wasnull() always returns false
*/
public void testCallableRegisterOutParameter2() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("create procedure #rop2 @bool bit, @whatever varchar(1) OUTPUT as\r\n "
+ "begin\r\n"
+ "set @whatever = null\r\n"
+ "end");
stmt.close();
CallableStatement cstmt = con.prepareCall("{call #rop2(?,?)}");
cstmt.setNull(1, Types.BOOLEAN);
cstmt.registerOutParameter(2, Types.VARCHAR);
cstmt.execute();
assertTrue(cstmt.getString(2) == null);
assertTrue(cstmt.wasNull());
cstmt.close();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(CallableStatementJDBC3Test.class);
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/SanityTest.java 0000644 0001750 0001750 00000017760 11316672660 026175 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.sql.*;
/**
* Some simple tests just to make sure everything is working properly.
*
* @author Alin Sinpalean
* @version $Id: SanityTest.java,v 1.8.2.1 2009/08/04 10:33:54 ickzon Exp $
* @created 9 August 2001
*/
public class SanityTest extends TestBase {
public SanityTest(String name) {
super(name);
}
/**
* A simple test to make sure everything seems to be OK
*/
public void testSanity() throws Exception {
Statement stmt = con.createStatement();
makeTestTables(stmt);
makeObjects(stmt, 5);
stmt.close();
}
/**
* Basic test of cursor mechanisms.
*/
public void testCursorStatements() throws Exception {
Statement stmt = con.createStatement();
makeTestTables(stmt);
makeObjects(stmt, 5);
ResultSet rs;
assertEquals("Expected an update count", false,
stmt.execute( "DECLARE cursor1 SCROLL CURSOR FOR"
+ "\nSELECT * FROM #test"));
assertEquals("Expected an update count", false,
stmt.execute("OPEN cursor1"));
rs = stmt.executeQuery("FETCH LAST FROM cursor1");
dump(rs);
rs.close();
rs = stmt.executeQuery("FETCH FIRST FROM cursor1");
dump(rs);
rs.close();
stmt.execute("CLOSE cursor1");
stmt.execute("DEALLOCATE cursor1");
stmt.close();
}
public void testCursorRSCreate() throws Exception {
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
makeTestTables(stmt);
makeObjects(stmt, 5);
ResultSet rs = stmt.executeQuery("Select * from #test order by 1");
// Move to last row (5)
rs.last();
assertEquals(5, rs.getRow());
assertEquals(4, rs.getInt(1));
assertEquals(false, rs.isBeforeFirst());
assertEquals(false, rs.isFirst());
assertEquals(true, rs.isLast());
assertEquals(false, rs.isAfterLast());
// Move before first row
rs.beforeFirst();
assertEquals(0, rs.getRow());
try {
rs.getInt(1);
fail("There should be no current row.");
} catch (SQLException ex) {
// This is ok, there's no row
}
assertEquals(true, rs.isBeforeFirst());
assertEquals(false, rs.isFirst());
assertEquals(false, rs.isLast());
assertEquals(false, rs.isAfterLast());
// Try to move 3 rows ahead (should end up on row 3 -- the spec,
// says that relative(1) is identical to next() and relative(-1) is
// identical to previous(), but the Javadoc says that they are
// different). Weird stuff...
rs.relative(3);
assertEquals(3, rs.getRow());
assertEquals(2, rs.getInt(1));
assertEquals(false, rs.isBeforeFirst());
assertEquals(false, rs.isFirst());
assertEquals(false, rs.isLast());
assertEquals(false, rs.isAfterLast());
// Move after last row
rs.afterLast();
assertEquals(0, rs.getRow());
try {
rs.getInt(1);
fail("There should be no current row.");
} catch (SQLException ex) {
// This is ok, there's no row
}
assertEquals(false, rs.isBeforeFirst());
assertEquals(false, rs.isFirst());
assertEquals(false, rs.isLast());
assertEquals(true, rs.isAfterLast());
// Move to first row
rs.first();
assertEquals(1, rs.getRow());
assertEquals(0, rs.getInt(1));
assertEquals(false, rs.isBeforeFirst());
assertEquals(true, rs.isFirst());
assertEquals(false, rs.isLast());
assertEquals(false, rs.isAfterLast());
// Move to row 4
rs.absolute(4);
assertEquals(4, rs.getRow());
assertEquals(3, rs.getInt(1));
assertEquals(false, rs.isBeforeFirst());
assertEquals(false, rs.isFirst());
assertEquals(false, rs.isLast());
assertEquals(false, rs.isAfterLast());
// Move 2 rows back
rs.relative(-2);
assertEquals(2, rs.getRow());
assertEquals(1, rs.getInt(1));
assertEquals(false, rs.isBeforeFirst());
assertEquals(false, rs.isFirst());
assertEquals(false, rs.isLast());
assertEquals(false, rs.isAfterLast());
rs.close();
stmt.close();
}
public void testCursorRSScroll() throws Exception {
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
makeTestTables(stmt);
makeObjects(stmt, 5);
ResultSet rs = stmt.executeQuery("Select * from #test");
while (rs.next());
rs.close();
stmt.close();
}
/*
* Check that image fields that have once been set to a non
* null value return null when updated to null.
* Fix bug [1774322] Sybase nulled text fields return not null.
*/
public void testNullImage() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #TEST (id int primary key not null, img image null)");
stmt.executeUpdate("INSERT INTO #TEST VALUES (1, null)");
ResultSet rs = stmt.executeQuery("SELECT * FROM #TEST");
rs.next();
assertTrue(rs.getBytes(2) == null);
stmt.executeUpdate("UPDATE #TEST SET img = '0x0123' WHERE id = 1");
rs = stmt.executeQuery("SELECT * FROM #TEST");
rs.next();
assertTrue(rs.getBytes(2) != null);
stmt.executeUpdate("UPDATE #TEST SET img = null WHERE id = 1");
rs = stmt.executeQuery("SELECT * FROM #TEST");
rs.next();
assertTrue(rs.getBytes(2) == null);
stmt.close();
}
/*
* Check that text fields that have once been set to a non
* null value return null when updated to null.
* Fix bug [1774322] Sybase nulled text fields return not null.
*/
public void testNullText() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #TEST (id int primary key not null, txt text null)");
stmt.executeUpdate("INSERT INTO #TEST VALUES (1, null)");
ResultSet rs = stmt.executeQuery("SELECT * FROM #TEST");
rs.next();
assertTrue(rs.getString(2) == null);
stmt.executeUpdate("UPDATE #TEST SET txt = ' ' WHERE id = 1");
rs = stmt.executeQuery("SELECT * FROM #TEST");
rs.next();
assertTrue(rs.getString(2) != null);
stmt.executeUpdate("UPDATE #TEST SET txt = null WHERE id = 1");
rs = stmt.executeQuery("SELECT * FROM #TEST");
rs.next();
assertTrue(rs.getString(2) == null);
stmt.close();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(SanityTest.class);
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/ConnectionJDBC2UnitTest.java 0000644 0001750 0001750 00000033475 11316672660 030373 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.sql.*;
import java.util.Properties;
import java.util.Enumeration;
import junit.framework.Test;
import junit.framework.TestSuite;
import net.sourceforge.jtds.jdbc.ConnectionJDBC2;
import net.sourceforge.jtds.jdbc.Driver;
import net.sourceforge.jtds.jdbc.DefaultProperties;
import net.sourceforge.jtds.jdbc.Messages;
/**
* Unit test for the {@link ConnectionJDBC2} class.
*
* @author David Kilzer
* @author Alin Sinpalean
* @version $Id: ConnectionJDBC2UnitTest.java,v 1.11 2007/07/08 18:08:54 bheineman Exp $
*/
public class ConnectionJDBC2UnitTest extends UnitTestBase {
/**
* Construct a test suite for this class.
*
* The test suite includes the tests in this class, and adds tests
* from {@link DefaultPropertiesTestLibrary} after creating an
* anonymous {@link DefaultPropertiesTester} object.
*
* @return The test suite to run.
*/
public static Test suite() {
final TestSuite testSuite = new TestSuite(ConnectionJDBC2UnitTest.class);
testSuite.addTest(
ConnectionJDBC2UnitTest.Test_ConnectionJDBC2_unpackProperties.suite(
"test_unpackProperties_DefaultProperties"));
return testSuite;
}
/**
* Constructor.
*
* @param name The name of the test.
*/
public ConnectionJDBC2UnitTest(String name) {
super(name);
}
/**
* Test that an {@link java.sql.SQLException} is thrown when
* parsing invalid integer (and long) properties.
*/
public void test_unpackProperties_invalidIntegerProperty() {
assertSQLExceptionForBadWholeNumberProperty(Driver.PORTNUMBER);
assertSQLExceptionForBadWholeNumberProperty(Driver.SERVERTYPE);
assertSQLExceptionForBadWholeNumberProperty(Driver.PREPARESQL);
assertSQLExceptionForBadWholeNumberProperty(Driver.PACKETSIZE);
assertSQLExceptionForBadWholeNumberProperty(Driver.LOGINTIMEOUT);
assertSQLExceptionForBadWholeNumberProperty(Driver.LOBBUFFER);
}
/**
* Assert that an SQLException is thrown when
* {@link ConnectionJDBC2#unpackProperties(Properties)} is called
* with an invalid integer (or long) string set on a property.
*
* Note that because Java 1.3 is still supported, the
* {@link RuntimeException} that is caught may not contain the
* original {@link Throwable} cause, only the original message.
*
* @param key The message key used to retrieve the property name.
*/
private void assertSQLExceptionForBadWholeNumberProperty(final String key) {
final ConnectionJDBC2 instance =
(ConnectionJDBC2) invokeConstructor(
ConnectionJDBC2.class, new Class[]{}, new Object[]{});
Properties properties =
(Properties) invokeStaticMethod(
Driver.class, "parseURL",
new Class[]{String.class, Properties.class},
new Object[]{"jdbc:jtds:sqlserver://servername", new Properties()});
properties =
(Properties) invokeStaticMethod(
DefaultProperties.class, "addDefaultProperties",
new Class[]{ Properties.class},
new Object[]{ properties});
properties.setProperty(Messages.get(key), "1.21 Gigawatts");
try {
invokeInstanceMethod(
instance, "unpackProperties",
new Class[]{Properties.class},
new Object[]{properties});
fail("RuntimeException expected");
}
catch (RuntimeException e) {
assertEquals("Unexpected exception message",
Messages.get("error.connection.badprop", Messages.get(key)),
e.getMessage());
}
}
/**
* Class used to test net.sourceforge.jtds.jdbc.ConnectionJDBC2.unpackProperties(Properties).
*/
public static class Test_ConnectionJDBC2_unpackProperties
extends DefaultPropertiesTestLibrary {
/**
* Construct a test suite for this library.
*
* @param name The name of the tests.
* @return The test suite.
*/
public static Test suite(String name) {
return new TestSuite(
ConnectionJDBC2UnitTest.Test_ConnectionJDBC2_unpackProperties.class, name);
}
/**
* Default constructor.
*/
public Test_ConnectionJDBC2_unpackProperties() {
setTester(
new DefaultPropertiesTester() {
public void assertDefaultProperty(
String message, String url, Properties properties, String fieldName,
String key, String expected) {
// FIXME: Hack for ConnectionJDBC2
{
if ("sendStringParametersAsUnicode".equals(fieldName)) {
fieldName = "useUnicode";
}
else if ("cacheMetaData".equals(fieldName)) {
fieldName = "useMetadataCache";
}
}
Properties parsedProperties =
(Properties) invokeStaticMethod(
Driver.class, "parseURL",
new Class[]{ String.class, Properties.class},
new Object[]{ url, properties});
parsedProperties =
(Properties) invokeStaticMethod(
DefaultProperties.class, "addDefaultProperties",
new Class[]{ Properties.class},
new Object[]{ parsedProperties});
ConnectionJDBC2 instance =
(ConnectionJDBC2) invokeConstructor(
ConnectionJDBC2.class, new Class[]{}, new Object[]{});
invokeInstanceMethod(
instance, "unpackProperties",
new Class[]{Properties.class},
new Object[]{parsedProperties});
String actual = String.valueOf(
invokeInstanceMethod(instance, "get" + ucFirst(fieldName),
new Class[]{}, new Object[]{}));
// FIXME: Another hack for ConnectionJDBC2
{
if ("tdsVersion".equals(fieldName)) {
expected = String.valueOf(DefaultProperties.getTdsVersion(expected));
}
}
assertEquals(message, expected, actual);
}
}
);
}
}
/**
* Creates a Connection, overriding the default properties
* with the ones provided.
*
* @param override the overriding properties
* @return a Connection object
*/
private Connection getConnectionOverrideProperties(Properties override)
throws Exception {
// Get properties, override with provided values
Properties props = (Properties) TestBase.props.clone();
for (Enumeration e = override.keys(); e.hasMoreElements();) {
String key = (String) e.nextElement();
props.setProperty(key, override.getProperty(key));
}
// Obtain connection
Class.forName(props.getProperty("driver"));
String url = props.getProperty("url");
return DriverManager.getConnection(url, props);
}
/**
* Test correct behavior of the charset property.
* Values should be stored and retrieved using the requested charset rather
* than the server's as long as Unicode is not used.
*/
public void testForceCharset1() throws Exception {
// Set charset to Cp1251 and Unicode parameters to false
Properties props = new Properties();
props.setProperty(Messages.get(Driver.CHARSET), "Cp1251");
props.setProperty(Messages.get(Driver.SENDSTRINGPARAMETERSASUNICODE),
"false");
// Obtain connection
Connection con = getConnectionOverrideProperties(props);
try {
// Test both sending and retrieving of values
String value = "\u0410\u0411\u0412";
PreparedStatement pstmt = con.prepareStatement("select ?");
pstmt.setString(1, value);
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(value, rs.getString(1));
assertFalse(rs.next());
rs.close();
pstmt.close();
} finally {
con.close();
}
}
/**
* Test correct behavior of the charset property.
* Stored procedure output parameters should be decoded using the specified
* charset rather than the server's as long as they are non-Unicode.
*/
public void testForceCharset2() throws Exception {
// Set charset to Cp1251 and Unicode parameters to false
Properties props = new Properties();
props.setProperty(Messages.get(Driver.CHARSET), "Cp1251");
props.setProperty(Messages.get(Driver.SENDSTRINGPARAMETERSASUNICODE),
"false");
// Obtain connection
Connection con = getConnectionOverrideProperties(props);
try {
Statement stmt = con.createStatement();
assertEquals(0,
stmt.executeUpdate("create procedure #testForceCharset2 "
+ "@inParam varchar(10), @outParam varchar(10) output as "
+ "set @outParam = @inParam"));
stmt.close();
// Test both sending and retrieving of parameters
String value = "\u0410\u0411\u0412";
CallableStatement cstmt =
con.prepareCall("{call #testForceCharset2(?, ?)}");
cstmt.setString(1, value);
cstmt.registerOutParameter(2, Types.VARCHAR);
assertEquals(0, cstmt.executeUpdate());
assertEquals(value, cstmt.getString(2));
cstmt.close();
} finally {
con.close();
}
}
/**
* Test for bug [1296482] setAutoCommit() behaviour.
*
* The behaviour of setAutoCommit() on ConnectionJDBC2 is inconsistent with
* the Sun JDBC 3.0 Specification. JDBC 3.0 Specification, section 10.1.1:
* "If the value of auto-commit is changed in the middle of a * transaction, the current transaction is committed."*/ public void testAutoCommit() throws Exception { Connection con = getConnectionOverrideProperties(new Properties()); try { Statement stmt = con.createStatement(); // Create temp table assertEquals(0, stmt.executeUpdate( "create table #testAutoCommit (i int)")); // Manual commit mode con.setAutoCommit(false); // Insert one row assertEquals(1, stmt.executeUpdate( "insert into #testAutoCommit (i) values (0)")); // Set commit mode to manual again; should have no effect con.setAutoCommit(false); // Rollback the transaction; should roll back the insert con.rollback(); // Insert one more row assertEquals(1, stmt.executeUpdate( "insert into #testAutoCommit (i) values (1)")); // Set commit mode to automatic; should commit everything con.setAutoCommit(true); // Go back to manual commit mode con.setAutoCommit(false); // Rollback transaction; should do nothing con.rollback(); // And back to auto commit mode again con.setAutoCommit(true); // Now see if the second row is there ResultSet rs = stmt.executeQuery("select i from #testAutoCommit"); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertFalse(rs.next()); // We're done, close everything rs.close(); stmt.close(); } finally { con.close(); } } } libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/StatementTest.java 0000644 0001750 0001750 00000006146 11316672660 026666 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase // Copyright (C) 2004 The jTDS Project // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package net.sourceforge.jtds.test; import java.sql.SQLException; import java.sql.Statement; /** * @version 1.0 */ public class StatementTest extends TestBase { public StatementTest(String name) { super(name); } /** * Test for bug [1694194], queryTimeout does not work on MSSQL2005 when * property 'useCursors' is set to 'true'. Furthermore, the test also * checks timeout with a query that cannot use a cursor.
*
* This test requires property 'queryTimeout' to be set to true.
*/
public void testQueryTimeout() throws Exception {
Statement st = con.createStatement();
st.setQueryTimeout(1);
st.execute("create procedure #testTimeout as begin waitfor delay '00:00:30'; select 1; end");
long start = System.currentTimeMillis();
try {
// this query doesn't use a cursor
st.executeQuery("exec #testTimeout");
fail("query did not time out");
} catch (SQLException e) {
assertEquals("HYT00", e.getSQLState());
assertEquals(1000, System.currentTimeMillis() - start, 10);
}
st.execute("create table #dummy1(A varchar(200))");
st.execute("create table #dummy2(B varchar(200))");
st.execute("create table #dummy3(C varchar(200))");
// create test data
con.setAutoCommit(false);
for(int i = 0; i < 100; i++) {
st.execute("insert into #dummy1 values('" + i + "')");
st.execute("insert into #dummy2 values('" + i + "')");
st.execute("insert into #dummy3 values('" + i + "')");
}
con.commit();
con.setAutoCommit(true);
start = System.currentTimeMillis();
try {
// this query can use a cursor
st.executeQuery("select * from #dummy1, #dummy2, #dummy3 order by A desc, B asc, C desc");
fail("query did not time out");
} catch (SQLException e) {
assertEquals("HYT00", e.getSQLState());
assertEquals(1000, System.currentTimeMillis() - start, 10);
}
st.close();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(StatementTest.class);
}
} libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/DefaultPropertiesUnitTest.java 0000644 0001750 0001750 00000026240 11316672660 031220 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import net.sourceforge.jtds.jdbc.DefaultProperties;
import net.sourceforge.jtds.jdbc.Messages;
import net.sourceforge.jtds.jdbc.Driver;
import java.util.Properties;
import java.util.Map;
import java.util.HashMap;
/**
* Unit tests for the {@link net.sourceforge.jtds.jdbc.DefaultProperties} class.
*
* @author David D. Kilzer
* @version $Id: DefaultPropertiesUnitTest.java,v 1.9 2007/07/08 18:08:54 bheineman Exp $
*/
public class DefaultPropertiesUnitTest extends UnitTestBase {
/**
* Constructor.
*
* @param name The name of the test.
*/
public DefaultPropertiesUnitTest(String name) {
super(name);
}
/**
* Tests that
* DefaultProperties.addDefaultPropertyIfNotSet(java.util.Properties, java.lang.String, java.lang.String)
* sets a default property if the property is not already set.
*/
public void test_addDefaultPropertyIfNotSet_PropertyNotSet() {
final Properties properties = new Properties();
final String key = Driver.DATABASENAME;
final String defaultValue = "foobar";
invokeStaticMethod(
DefaultProperties.class, "addDefaultPropertyIfNotSet",
new Class[]{Properties.class, String.class, String.class},
new Object[]{properties, key, defaultValue});
assertEquals(defaultValue, properties.get(Messages.get(key)));
}
/**
* Tests that
* DefaultProperties.addDefaultPropertyIfNotSet(java.util.Properties, java.lang.String, java.lang.String)
* does not set a default property if the property is already set.
*/
public void test_addDefaultPropertyIfNotSet_PropertyAlreadySet() {
final Properties properties = new Properties();
final String key = Driver.DATABASENAME;
final String presetValue = "barbaz";
final String defaultValue = "foobar";
properties.setProperty(Messages.get(key), presetValue);
invokeStaticMethod(DefaultProperties.class, "addDefaultPropertyIfNotSet",
new Class[]{Properties.class, String.class, String.class},
new Object[]{properties, key, defaultValue});
assertEquals(presetValue, properties.get(Messages.get(key)));
}
/**
* Tests that
* DefaultProperties.addDefaultPropertyIfNotSet(java.util.Properties, java.lang.String, java.lang.String, java.util.Map)
* does not set a default property if the defaultKey is not set.
*/
public void test_addDefaultPropertyIfNotSet_DefaultKeyNotSet() {
final Properties properties = new Properties();
final String defaultKey = Driver.SERVERTYPE;
final String key = Driver.PORTNUMBER;
final HashMap defaults = new HashMap();
invokeStaticMethod(DefaultProperties.class, "addDefaultPropertyIfNotSet",
new Class[]{Properties.class, String.class, String.class, Map.class},
new Object[]{properties, key, defaultKey, defaults});
assertEquals(0, properties.size());
}
/**
* Tests that
* DefaultProperties.addDefaultPropertyIfNotSet(java.util.Properties, java.lang.String, java.lang.String, java.util.Map)
* sets a default property if the property is not already set.
*/
public void test_addDefaultPropertyIfNotSet_DefaultKeySet_PropertyNotSet() {
final Properties properties = new Properties();
final String defaultKey = Driver.SERVERTYPE;
final String defaultKeyValue = "foobar";
properties.put(Messages.get(defaultKey), defaultKeyValue);
final String key = Driver.PORTNUMBER;
final String defaultValue = "2004";
final HashMap defaults = new HashMap();
defaults.put(defaultKeyValue, defaultValue);
invokeStaticMethod(DefaultProperties.class, "addDefaultPropertyIfNotSet",
new Class[]{Properties.class, String.class, String.class, Map.class},
new Object[]{properties, key, defaultKey, defaults});
assertEquals(defaultValue, properties.get(Messages.get(key)));
}
/**
* Tests that
* DefaultProperties.addDefaultPropertyIfNotSet(java.util.Properties, java.lang.String, java.lang.String, java.util.Map)
* does not set a default property if the property is already set.
*/
public void test_addDefaultPropertyIfNotSet_DefaultKeySet_PropertyAlreadySet() {
final Properties properties = new Properties();
final String defaultKey = Driver.SERVERTYPE;
final String defaultKeyValue = "foobar";
properties.put(Messages.get(defaultKey), defaultKeyValue);
final String key = Driver.PORTNUMBER;
final String presetValue = "2020";
properties.put(Messages.get(key), presetValue);
final String defaultValue = "2004";
final HashMap defaults = new HashMap();
defaults.put(defaultKeyValue, defaultValue);
invokeStaticMethod(DefaultProperties.class, "addDefaultPropertyIfNotSet",
new Class[]{Properties.class, String.class, String.class, Map.class},
new Object[]{properties, key, defaultKey, defaults});
assertEquals(presetValue, properties.get(Messages.get(key)));
}
public void test_getServerType_intToString_Null() {
final String message = "Did not return null for unknown server type ";
final int[] testValues = new int[]{ -99, -1, 0, 3, 99 };
for (int i = 0; i < testValues.length; i++) {
assertNull(
message + String.valueOf(testValues[i]),
DefaultProperties.getServerType(testValues[i]));
}
}
public void test_getServerType_intToString_SQLSERVER() {
assertEquals(
"Server type for SQL Server did not map correctly",
DefaultProperties.SERVER_TYPE_SQLSERVER,
DefaultProperties.getServerType(Driver.SQLSERVER));
}
public void test_getServerType_intToString_SYBASE() {
assertEquals("Server type for Sybase did not map correctly",
DefaultProperties.SERVER_TYPE_SYBASE,
DefaultProperties.getServerType(Driver.SYBASE));
}
public void test_getServerType_StringToInteger_Null() {
final String message = "Did not return null for unknown server type: ";
final String[] testValues = new String[]{ null, "", "SQLServer", "Sybase", "sibase", "sq1server" };
for (int i = 0; i < testValues.length; i++) {
assertNull(
message + String.valueOf(testValues[i]),
DefaultProperties.getServerType(testValues[i]));
}
}
public void test_getServerType_StringToInteger_SQLSERVER() {
assertEquals(
"Server type for SQL Server did not map correctly",
new Integer(Driver.SQLSERVER),
DefaultProperties.getServerType(DefaultProperties.SERVER_TYPE_SQLSERVER));
}
public void test_getServerType_StringToInteger_SYBASE() {
assertEquals("Server type for Sybase did not map correctly",
new Integer(Driver.SYBASE),
DefaultProperties.getServerType(DefaultProperties.SERVER_TYPE_SYBASE));
}
public void test_getTdsVersion_StringToInteger_Null() {
final String message = "Did not return null for unknown TDS version: ";
final String[] testValues = new String[]{ null, "", "4.0", "5.2", "0.0", "8:0" };
for (int i = 0; i < testValues.length; i++) {
assertNull(
message + String.valueOf(testValues[i]),
DefaultProperties.getTdsVersion(testValues[i]));
}
}
public void test_getTdsVersion_StringToInteger_TDS42() {
assertEquals(
"Tds version for TDS 4.2 did not map correctly",
new Integer(Driver.TDS42),
DefaultProperties.getTdsVersion(DefaultProperties.TDS_VERSION_42));
}
public void test_getTdsVersion_StringToInteger_TDS50() {
assertEquals(
"Tds version for TDS 5.0 did not map correctly",
new Integer(Driver.TDS50),
DefaultProperties.getTdsVersion(DefaultProperties.TDS_VERSION_50));
}
public void test_getTdsVersion_StringToInteger_TDS70() {
assertEquals(
"Tds version for TDS 7.0 did not map correctly",
new Integer(Driver.TDS70),
DefaultProperties.getTdsVersion(DefaultProperties.TDS_VERSION_70));
}
public void test_getTdsVersion_StringToInteger_TDS80() {
assertEquals(
"Tds version for TDS 8.0 did not map correctly",
new Integer(Driver.TDS80),
DefaultProperties.getTdsVersion(DefaultProperties.TDS_VERSION_80));
}
public void test_getNamedPipePath_DEFAULT() {
assertEquals(
"Default named pipe path for default (0) did not map correctly",
DefaultProperties.NAMED_PIPE_PATH_SQLSERVER,
DefaultProperties.getNamedPipePath(0));
}
public void test_getNamedPipePath_INVALID() {
try {
DefaultProperties.getNamedPipePath(3);
fail("IllegalArgumentException was expected to be thrown");
}
catch (IllegalArgumentException expected) {
}
}
public void test_getNamedPipePath_SQLSERVER() {
assertEquals(
"Default named pipe path for SQL Server did not map correctly",
DefaultProperties.NAMED_PIPE_PATH_SQLSERVER,
DefaultProperties.getNamedPipePath(DefaultProperties.getServerType(DefaultProperties.SERVER_TYPE_SQLSERVER).intValue()));
}
public void test_getNamedPipePath_SYBASE() {
assertEquals(
"Default named pipe path for Sybase did not map correctly",
DefaultProperties.NAMED_PIPE_PATH_SYBASE,
DefaultProperties.getNamedPipePath(DefaultProperties.getServerType(DefaultProperties.SERVER_TYPE_SYBASE).intValue()));
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/JtdsObjectFactoryUnitTest.java 0000644 0001750 0001750 00000016305 11316672660 031143 0 ustar martin martin //jTDS JDBC Driver for Microsoft SQL Server and Sybase
//Copyright (C) 2004 The jTDS Project
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.util.Hashtable;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.Reference;
import javax.naming.Name;
import junit.framework.Test;
import junit.framework.TestSuite;
import net.sourceforge.jtds.jdbc.Support;
import net.sourceforge.jtds.jdbcx.JtdsDataSource;
import net.sourceforge.jtds.jdbcx.JtdsObjectFactory;
/**
* Unit tests for the {@link JtdsObjectFactory} class.
*
* @author David D. Kilzer
* @author Alin Sinpalean
* @version $Id: JtdsObjectFactoryUnitTest.java,v 1.12 2007/07/12 21:20:03 bheineman Exp $
*/
public class JtdsObjectFactoryUnitTest extends UnitTestBase {
/**
* Construct a test suite for this class.
*
Connection concurrency by running
* PreparedStatements and rollbacks at the same time to see
* whether handles are not lost in the process.
*/
public void testMultiThread() throws Exception {
TestMultiThread.startThreads(con);
}
/**
* Test for bug [1094621] Decimal conversion error: A prepared statement
* with a decimal parameter that is -1E38 will fail as a result of the
* driver generating a parameter specification of decimal(38,10) rather
* than decimal(38,0).
*/
public void testBigDecBadParamSpec() throws Exception
{
Statement stmt = con.createStatement();
stmt.execute(
"create table #test (id int primary key, val decimal(38,0))");
BigDecimal bd =
new BigDecimal("99999999999999999999999999999999999999");
PreparedStatement pstmt =
con.prepareStatement("insert into #test values(?,?)");
pstmt.setInt(1, 1);
pstmt.setBigDecimal(2, bd);
assertEquals(1, pstmt.executeUpdate()); // Worked OK
pstmt.setInt(1, 2);
pstmt.setBigDecimal(2, bd.negate());
assertEquals(1, pstmt.executeUpdate()); // Failed
}
/**
* Test for bug [1111516 ] Illegal Parameters in PreparedStatement.
*/
public void testIllegalParameters() throws Exception
{
Statement stmt = con.createStatement();
stmt.execute("create table #test (id int)");
PreparedStatement pstmt =
con.prepareStatement("select top ? * from #test");
pstmt.setInt(1, 10);
try {
pstmt.executeQuery();
// This won't fail in unprepared mode (prepareSQL == 0)
// fail("Expecting an exception to be thrown.");
} catch (SQLException ex) {
assertTrue("37000".equals(ex.getSQLState())
|| "42000".equals(ex.getSQLState()));
}
pstmt.close();
}
/**
* Test for bug [1180777] collation-related execption on update.
*
* If a statement prepare fails the statement should still be executed
* (unprepared) and a warning should be added to the connection (the
* prepare failed, this is a connection event even if it happened on
* statement execute).
*/
public void testPrepareFailWarning() throws SQLException {
try {
PreparedStatement pstmt = con.prepareStatement(
"CREATE VIEW prepFailWarning AS SELECT 1 AS value");
pstmt.execute();
// Check that a warning was generated on the connection.
// Although not totally correct (the warning should be generated on
// the statement) the warning is generated while preparing the
// statement, so it belongs to the connection.
assertNotNull(con.getWarnings());
pstmt.close();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM prepFailWarning");
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertFalse(rs.next());
rs.close();
stmt.close();
} finally {
Statement stmt = con.createStatement();
stmt.execute("DROP VIEW prepFailWarning");
stmt.close();
}
}
/**
* Test that preparedstatement logic copes with commit modes and
* database changes.
*/
public void testPrepareModes() throws Exception {
//
// To see in detail what is happening enable logging and study the prepare
// statements that are being executed.
// For example if maxStatements=0 then the log should show that each
// statement is prepared and then unprepared at statement close.
// If maxStatements < 4 then you will see statements being unprepared
// when the cache is full.
//
// DriverManager.setLogStream(System.out);
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #TEST (id int primary key, data varchar(255))");
//
// Statement prepared with auto commit = true
//
PreparedStatement pstmt1 = con.prepareStatement("INSERT INTO #TEST (id, data) VALUES (?,?)");
pstmt1.setInt(1, 1);
pstmt1.setString(2, "Line one");
assertEquals(1, pstmt1.executeUpdate());
//
// Move to manual commit mode
//
con.setAutoCommit(false);
//
// Ensure a new transaction is started
//
ResultSet rs = stmt.executeQuery("SELECT * FROM #TEST");
assertNotNull(rs);
rs.close();
//
// With Sybase this execution should cause a new proc to be created
// as we are now in chained mode
//
pstmt1.setInt(1, 2);
pstmt1.setString(2, "Line two");
assertEquals(1, pstmt1.executeUpdate());
//
// Statement prepared with auto commit = false
//
PreparedStatement pstmt2 = con.prepareStatement("SELECT * FROM #TEST WHERE id = ?");
pstmt2.setInt(1, 2);
rs = pstmt2.executeQuery();
assertNotNull(rs);
assertTrue(rs.next());
assertEquals("Line two", rs.getString("data"));
//
// Change catalog
//
String oldCat = con.getCatalog();
con.setCatalog("master");
//
// Executiion from another database should cause SQL Server to create
// a new handle or store proc
//
pstmt2.setInt(1, 1);
rs = pstmt2.executeQuery();
assertNotNull(rs);
assertTrue(rs.next());
assertEquals("Line one", rs.getString("data"));
//
// Now change back to original database
//
con.setCatalog(oldCat);
//
// Roll back transaction which should cause SQL Server procs (but not
// handles to be lost) causing statement to be prepared again.
//
pstmt2.setInt(1, 1);
rs = pstmt2.executeQuery();
assertNotNull(rs);
assertTrue(rs.next());
assertEquals("Line one", rs.getString("data"));
//
// Now return to auto commit mode
//
con.setAutoCommit(true);
//
// With Sybase statement will be prepared again as now in chained off mode
//
pstmt2.setInt(1, 1);
rs = pstmt2.executeQuery();
assertNotNull(rs);
assertTrue(rs.next());
assertEquals("Line one", rs.getString("data"));
pstmt2.close();
pstmt1.close();
stmt.close();
//
// Now we create a final prepared statement to demonstate that
// the cache is flushed correctly when the number of statements
// exceeds the cachesize. For example setting maxStatements=1
// will cause three statements to be unprepared when this statement
// is closed
//
pstmt1 = con.prepareStatement("SELECT id, data FROM #TEST");
pstmt1.executeQuery();
pstmt1.close();
}
/**
* Test that statements which cannot be prepared are remembered.
*/
public void testNoPrepare() throws Exception {
// DriverManager.setLogStream(System.out);
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #TEST (id int primary key, data text)");
//
// Statement cannot be prepared on Sybase due to text field
//
PreparedStatement pstmt1 = con.prepareStatement("INSERT INTO #TEST (id, data) VALUES (?,?)");
pstmt1.setInt(1, 1);
pstmt1.setString(2, "Line one");
assertEquals(1, pstmt1.executeUpdate());
//
// This time should not try and prepare
//
pstmt1.setInt(1, 2);
pstmt1.setString(2, "Line two");
assertEquals(1, pstmt1.executeUpdate());
pstmt1.close();
}
/**
* Tests that float (single precision - 32 bit) values are not converted to
* double (thus loosing precision).
*/
public void testFloatValues() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #floatTest (v real)");
stmt.executeUpdate("insert into #floatTest (v) values (2.3)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement(
"select * from #floatTest where v = ?");
pstmt.setFloat(1, 2.3f);
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(2.3f, rs.getFloat(1), 0);
assertTrue(rs.getObject(1) instanceof Float);
assertEquals(2.3f, ((Float) rs.getObject(1)).floatValue(), 0);
// Just make sure that conversion to double will break this
assertFalse(2.3 - rs.getDouble(1) == 0);
assertFalse(rs.next());
rs.close();
pstmt.close();
}
public void testNegativeScale() throws Exception {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #testNegativeScale (val decimal(28,10))");
PreparedStatement pstmt = con.prepareStatement(
"INSERT INTO #testNegativeScale VALUES(?)");
pstmt.setBigDecimal(1, new BigDecimal("2.9E7"));
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
ResultSet rs = stmt.executeQuery("SELECT * FROM #testNegativeScale");
assertNotNull(rs);
assertTrue(rs.next());
assertEquals(29000000, rs.getBigDecimal(1).intValue());
stmt.close();
}
/**
* Test for bug [1623668] Lost apostrophes in statement parameter values(prepareSQL=0)
*/
public void testPrepareSQL0() throws Exception {
Properties props = new Properties();
props.setProperty("prepareSQL", "0");
Connection con = getConnection(props);
try {
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE #prepareSQL0 (position int, data varchar(32))");
stmt.close();
PreparedStatement ps = con.prepareStatement("INSERT INTO #prepareSQL0 (position, data) VALUES (?, ?)");
String data1 = "foo'foo";
String data2 = "foo''foo";
String data3 = "foo'''foo";
ps.setInt(1, 1);
ps.setString(2, data1);
ps.executeUpdate();
ps.setInt(1, 2);
ps.setString(2, data2);
ps.executeUpdate();
ps.setInt(1, 3);
ps.setString(2, data3);
ps.executeUpdate();
ps.close();
ps = con.prepareStatement("SELECT data FROM #prepareSQL0 ORDER BY position");
ResultSet rs = ps.executeQuery();
rs.next();
assertEquals(data1, rs.getString(1));
rs.next();
assertEquals(data2, rs.getString(1));
rs.next();
assertEquals(data3, rs.getString(1));
rs.close();
} finally {
con.close();
}
}
/**
* Test for bug [2814376] varchar-type is truncated in non-unicode
* environment.
*/
public void testMultiByteCharTruncation() throws Exception {
String encoding = "SJIS";
final int chars = 8000;
final String ch = new String("\u3042");
// create string with bytecount > charcount
StringBuffer sb = new StringBuffer();
for(int i = 0; i < chars; i++)
sb.append(ch);
final String text = sb.toString();
final int ID = 1;
final int length = text.getBytes(encoding).length;
// ensure string contains multi-byte chars
assertTrue(text.getBytes(encoding).length > chars);
// create connection with charset/sendStringParametersAsUnicode properties set
Properties newProps = new Properties(props);
newProps.put("charset", encoding);
newProps.put("sendStringParametersAsUnicode", "false");
Connection con = DriverManager.getConnection(newProps.getProperty("url"), newProps);
// create temporary table
Statement st = con.createStatement();
st.execute("create table #testUnicodeTrunc (id int primary key, data text)");
st.close();
// insert test date into table
PreparedStatement ps1 = con.prepareStatement("insert into #testUnicodeTrunc values(?,?)");
ps1.setInt(1, ID);
ps1.setString(2, text);
assertEquals(1, ps1.executeUpdate());
// read back test data
PreparedStatement ps2 = con.prepareStatement("select data from #testUnicodeTrunc where id = " + ID);
ResultSet rs = ps2.executeQuery();
// ensure the value is read back from DB without data loss
assertTrue(rs.next());
int rl = rs.getString(1).getBytes(encoding).length;
assertEquals("data truncated", length, rl);
assertEquals("data corrupted",text, rs.getString(1));
ps1.close();
ps2.close();
}
/**
* Test for bug [1374127], Arithmetic overflow at sql_variant.
*/
public void testArithmeticOverflow() throws Exception {
Statement st = con.createStatement();
st.execute("create table #testArithemicOverflow (id int primary key, data sql_variant)");
st.execute("insert into #testArithemicOverflow values (1,1)");
st.close();
long seed = System.currentTimeMillis();
Random r = new Random(seed);
Float value = new Float(0.000803f);
PreparedStatement ps1 = con.prepareStatement("update #testArithemicOverflow set data = ? where id = ?");
PreparedStatement ps2 = con.prepareStatement("select data from #testArithemicOverflow where id = ?");
try {
for (int i = 0; i < 1000; i++) {
if (i > 0) {
value = new Float(r.nextFloat() * Float.MAX_VALUE * (r.nextBoolean() ? 1 : -1));
}
ps1.setFloat(1, value.floatValue());
ps1.setInt(2, 1);
assertEquals(1, ps1.executeUpdate());
ps2.setInt(1, 1);
ResultSet rs = ps2.executeQuery();
assertTrue(rs.next());
assertEquals(value, new Float(rs.getFloat(1)));
rs.close();
}
} catch (Throwable t) {
System.out.println("seed " + seed + ", value " + value);
fail(t.getMessage());
} finally {
ps1.close();
ps2.close();
}
}
public static void main(String[] args) {
junit.textui.TestRunner.run(PreparedStatementTest.class);
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/MetaDataTestCase.java 0000644 0001750 0001750 00000004301 11316672660 027165 0 ustar martin martin //jTDS JDBC Driver for Microsoft SQL Server and Sybase
//Copyright (C) 2004 The jTDS Project
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
/**
* Base class for meta data test cases.
*
* @author David Eaves
* @version $Id: MetaDataTestCase.java,v 1.1 2005/01/05 12:24:14 alin_sinpalean Exp $
*/
public abstract class MetaDataTestCase extends DatabaseTestCase {
public MetaDataTestCase(String name) {
super(name);
}
/**
* Utility method to check column names and number.
*
* @param rs the result set to check
* @param names the list of column names to compare to result set
* @return the boolean value true if the columns match
*/
protected boolean checkColumnNames(ResultSet rs, String[] names)
throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
if (rsmd.getColumnCount() < names.length) {
System.out.println("Cols=" + rsmd.getColumnCount());
return false;
}
for (int i = 1; i <= names.length; i++) {
if (names[i - 1].length() > 0
&& !rsmd.getColumnLabel(i).equals(names[i - 1])) {
System.out.println(
names[i - 1] + " = " + rsmd.getColumnLabel(i));
return false;
}
}
return true;
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/UnitTestBase.java 0000644 0001750 0001750 00000027301 11316672660 026430 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Field;
import junit.framework.Assert;
import junit.framework.TestCase;
import net.sourceforge.jtds.jdbc.Support;
/**
* Base class for unit tests which do not connect to a database.
*
* @author David D. Kilzer
* @version $Id: UnitTestBase.java,v 1.12 2005/12/22 17:24:07 ddkilzer Exp $
*/
public abstract class UnitTestBase extends TestCase {
/**
* Constructor.
*
* @param name The name of the test.
*/
public UnitTestBase(final String name) {
super(name);
}
/**
* Invoke a constructor on a class using reflection.
*
* @param klass The class.
* @param classes The classes in the parameter list.
* @param objects The objects to be used as parameters.
* @return The object constructed.
*/
public static Object invokeConstructor(final Class klass, final Class[] classes, final Object[] objects) {
try {
Constructor constructor;
try {
constructor = klass.getDeclaredConstructor(classes);
}
catch (NoSuchMethodException e) {
constructor = klass.getConstructor(classes);
}
constructor.setAccessible(true);
return constructor.newInstance(objects);
}
catch (NoSuchMethodException e) {
RuntimeException runtimeException = new RuntimeException(e.getMessage());
Support.linkException(runtimeException, e);
throw runtimeException;
}
catch (InstantiationException e) {
RuntimeException runtimeException = new RuntimeException(e.getMessage());
Support.linkException(runtimeException, e);
throw runtimeException;
}
catch (IllegalAccessException e) {
RuntimeException runtimeException = new RuntimeException(e.getMessage());
Support.linkException(runtimeException, e);
throw runtimeException;
}
catch (InvocationTargetException e) {
RuntimeException runtimeException = new RuntimeException(e.getTargetException().getMessage());
Support.linkException(runtimeException, e);
throw runtimeException;
}
}
/**
* Get the value of an instance field on an object using reflection.
*
* @param instance The instance of the object.
* @param fieldName The name of the field.
* @return The object returned by getting the field.
*/
public static Object invokeGetInstanceField(final Object instance, final String fieldName) {
try {
Field field;
try {
field = instance.getClass().getField(fieldName);
}
catch (NoSuchFieldException e) {
field = instance.getClass().getDeclaredField(fieldName);
}
field.setAccessible(true);
return field.get(instance);
}
catch (NoSuchFieldException e) {
RuntimeException runtimeException = new RuntimeException(e.getMessage());
Support.linkException(runtimeException, e);
throw runtimeException;
}
catch (IllegalAccessException e) {
RuntimeException runtimeException = new RuntimeException(e.getMessage());
Support.linkException(runtimeException, e);
throw runtimeException;
}
}
/**
* Set the value of an instance field on an object using reflection.
*
* @param instance The instance of the object.
* @param fieldName The name of the field.
* @param fieldValue The value to set the field to.
*/
public static void invokeSetInstanceField(final Object instance, final String fieldName, final Object fieldValue) {
try {
Field field;
try {
field = instance.getClass().getField(fieldName);
}
catch (NoSuchFieldException e) {
field = instance.getClass().getDeclaredField(fieldName);
}
field.setAccessible(true);
field.set(instance, fieldValue);
}
catch (NoSuchFieldException e) {
RuntimeException runtimeException = new RuntimeException(e.getMessage());
Support.linkException(runtimeException, e);
throw runtimeException;
}
catch (IllegalAccessException e) {
RuntimeException runtimeException = new RuntimeException(e.getMessage());
Support.linkException(runtimeException, e);
throw runtimeException;
}
}
/**
* Invoke an instance method on an object using reflection.
*
* @param instance The instance of the object.
* @param methodName The name of the method.
* @param classes The classes in the parameter list.
* @param objects The objects to be used as parameters.
* @return The object returned by invoking the method.
*/
public static Object invokeInstanceMethod(
final Object instance, final String methodName, final Class[] classes, final Object[] objects) {
try {
Method method;
try {
method = instance.getClass().getDeclaredMethod(methodName, classes);
}
catch (NoSuchMethodException e) {
method = instance.getClass().getMethod(methodName, classes);
}
method.setAccessible(true);
return method.invoke(instance, objects);
}
catch (NoSuchMethodException e) {
RuntimeException runtimeException = new RuntimeException(e.getMessage());
Support.linkException(runtimeException, e);
throw runtimeException;
}
catch (IllegalAccessException e) {
RuntimeException runtimeException = new RuntimeException(e.getMessage());
Support.linkException(runtimeException, e);
throw runtimeException;
}
catch (InvocationTargetException e) {
RuntimeException runtimeException = new RuntimeException(e.getTargetException().getMessage());
Support.linkException(runtimeException, e);
throw runtimeException;
}
}
/**
* Invoke a static method on a class using reflection.
*
* @param klass The class.
* @param methodName The name of the method.
* @param classes The classes in the parameter list.
* @param objects The objects to be used as parameters.
* @return The object returned by invoking the method.
*/
public static Object invokeStaticMethod(
final Class klass, final String methodName, final Class[] classes, final Object[] objects) {
try {
Method method;
try {
method = klass.getDeclaredMethod(methodName, classes);
}
catch (NoSuchMethodException e) {
method = klass.getMethod(methodName, classes);
}
method.setAccessible(true);
return method.invoke(klass, objects);
}
catch (NoSuchMethodException e) {
RuntimeException runtimeException = new RuntimeException(e.getMessage());
Support.linkException(runtimeException, e);
throw runtimeException;
}
catch (IllegalAccessException e) {
RuntimeException runtimeException = new RuntimeException(e.getMessage());
Support.linkException(runtimeException, e);
throw runtimeException;
}
catch (InvocationTargetException e) {
RuntimeException runtimeException = new RuntimeException(e.getTargetException().getMessage());
Support.linkException(runtimeException, e);
throw runtimeException;
}
}
/**
* Compare two arrays element-by-element.
*
* The default JUnit {@link Assert#assertEquals(String, Object, Object)} method
* does not handle them properly.
*
* @param message The message to print upon failure.
* @param expected The expected value.
* @param actual The actual value.
*/
protected void assertEquals(String message, Object[] expected, Object[] actual) {
if (expected == null && actual == null) {
return;
}
if (expected == null || actual == null) {
failNotEquals(message, expected, actual);
}
if (expected.length != actual.length) {
failNotEquals(message, expected, actual);
}
for (int i = 0; i < expected.length; i++) {
if (expected[i] == null || !expected[i].equals(actual[i])) {
failNotEquals(message, expected, actual);
}
}
}
/**
* @see Assert#failNotEquals(java.lang.String, java.lang.Object, java.lang.Object)
*/
private void failNotEquals(String message, Object[] expected, Object[] actual) {
fail((String) invokeStaticMethod(Assert.class, "format",
new Class[]{String.class, Object.class, Object.class},
new Object[]{message, format(expected), format(actual)}));
}
/**
* Format an Object[] object to a String.
*
* @param object The object to be formatted.
* @return Formatted string representing the object.
*/
private String format(Object[] object) {
StringBuffer buf = new StringBuffer();
if (object == null || object.length < 1) {
buf.append(object);
} else {
buf.append('{');
buf.append(object[0]);
for (int i = 1; i < object.length; i++) {
buf.append(',');
if (object[i] instanceof Object[]) {
buf.append(format((Object[]) object[i]));
}
else {
buf.append(object[i]);
}
}
buf.append('}');
}
return buf.toString();
}
/**
* Changes the first character of a string to uppercase.
*
* @param s The string to be processed.
* @return The value of s if it is null or zero length,
* else the string with the first character changed to uppercase.
*/
protected static String ucFirst(String s) {
if (s == null || s.length() == 0) return s;
if (s.length() == 1) {
return s.toUpperCase();
}
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/MessagesPropertiesUnitTest.java 0000644 0001750 0001750 00000012674 11316672660 031411 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2005 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import junit.framework.Test;
import junit.framework.TestSuite;
import net.sourceforge.jtds.jdbc.Messages;
import java.util.Enumeration;
import java.util.ResourceBundle;
/**
* Unit tests for the Messages.properties file.
*
* @author David D. Kilzer
* @version $Id: MessagesPropertiesUnitTest.java,v 1.3 2005/09/23 21:44:08 ddkilzer Exp $
*/
public class MessagesPropertiesUnitTest extends UnitTestBase {
/**
* Construct a test suite for this class.
*
* @return The test suite to run.
*/
public static Test suite() {
final TestSuite testSuite = new TestSuite(MessagesPropertiesUnitTest.class.getName());
final ResourceBundle messages = (ResourceBundle) invokeStaticMethod(
Messages.class, "loadResourceBundle", new Class[]{}, new Object[]{});
final Enumeration keysEnumeration = messages.getKeys();
while (keysEnumeration.hasMoreElements()) {
String key = (String) keysEnumeration.nextElement();
if (key.startsWith("prop.desc.")) {
final String propertyName = key.substring("prop.desc.".length());
testSuite.addTest(new TestDescriptionHasProperty(propertyName, messages));
}
else if (key.startsWith("prop.")) {
final String propertyName = key.substring("prop.".length());
testSuite.addTest(new TestPropertyHasDescription(propertyName, messages));
}
}
return testSuite;
}
/**
* Constructor.
*
* @param name The name of the test.
*/
public MessagesPropertiesUnitTest(final String name) {
super(name);
}
/**
* Tests that a given description key has a matching property key in
* Messages.properties.
*/
public static class TestDescriptionHasProperty extends UnitTestBase {
private final ResourceBundle messages;
private final String property;
/**
* Constructor.
*
* @param property The property name to test.
* @param messages The resource bundle containing all of the messages.
*/
public TestDescriptionHasProperty(String property, ResourceBundle messages) {
super("testDescriptionHasProperty_" + property);
this.property = property;
this.messages = messages;
}
/**
* Provides a null test suite so that JUnit will not try to instantiate this class directly.
*
* @return The test suite (always null).
*/
public static final Test suite() {
return null;
}
/**
* Runs the test that a given description key has a matching property key in
* Messages.properties.
*
* @throws Throwable on error.
*/
protected void runTest() throws Throwable {
String property = (String) messages.getObject("prop." + this.property);
assertTrue(property.trim().length() > 0);
}
}
/**
* Tests that a given property key has a matching description key in
* Messages.properties.
*/
public static class TestPropertyHasDescription extends UnitTestBase {
private final ResourceBundle messages;
private final String property;
/**
* Constructor.
*
* @param property The property name to test.
* @param messages The resource bundle containing all of the messages.
*/
public TestPropertyHasDescription(String property, ResourceBundle messages) {
super("testPropertyHasDescription_" + property);
this.property = property;
this.messages = messages;
}
/**
* Provides a null test suite so that JUnit will not try to instantiate this class directly.
*
* @return The test suite (always null).
*/
public static final Test suite() {
return null;
}
/**
* Runs the test that a given property key has a matching description key in
* Messages.properties.
*
* @throws Throwable on error.
*/
protected void runTest() throws Throwable {
String description = (String) messages.getObject("prop.desc." + this.property);
assertTrue(description.trim().length() > 0);
}
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/DriverUnitTest.java 0000644 0001750 0001750 00000032633 11316672660 027015 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import junit.framework.Test;
import junit.framework.TestSuite;
import net.sourceforge.jtds.jdbc.DefaultProperties;
import net.sourceforge.jtds.jdbc.Driver;
import net.sourceforge.jtds.jdbc.Messages;
import net.sourceforge.jtds.jdbc.TdsCore;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
/**
* Unit tests for the {@link Driver} class.
*
* @author David D. Kilzer
* @version $Id: DriverUnitTest.java,v 1.20 2007/07/08 18:08:54 bheineman Exp $
*/
public class DriverUnitTest extends UnitTestBase {
/**
* Construct a test suite for this class.
*
* The test suite includes the tests in this class, and adds tests
* from {@link DefaultPropertiesTestLibrary} after creating
* anonymous {@link DefaultPropertiesTester} objects.
*
* @return The test suite to run.
*/
public static Test suite() {
TestSuite testSuite = new TestSuite(DriverUnitTest.class);
testSuite.addTest(
Test_Driver_setupConnectProperties.suite("test_setupConnectProperties_DefaultProperties"));
testSuite.addTest(
Test_Driver_getPropertyInfo.suite("test_getPropertyInfo_DefaultProperties"));
return testSuite;
}
/**
* Constructor.
*
* @param name The name of the test.
*/
public DriverUnitTest(final String name) {
super(name);
}
/**
* Tests that passing in a null properties argument to
* {@link Driver#getPropertyInfo(String, Properties)}
* causes the url to be parsed, which then throws a {@link SQLException}.
*/
public void test_getPropertyInfo_ThrowsSQLExceptionWithNullProperties() {
try {
new Driver().getPropertyInfo("wxyz:", null);
fail("Expected SQLException to be throw");
}
catch (SQLException e) {
// Expected
}
}
/**
* Tests that passing in a non-null properties argument to
* {@link Driver#getPropertyInfo(String, Properties)}
* causes the url to be parsed, which then throws a {@link SQLException}.
*/
public void test_getPropertyInfo_ThrowsSQLExceptionWithNonNullProperties() {
try {
new Driver().getPropertyInfo("wxyz:", new Properties());
fail("Expected SQLException to be throw");
}
catch (SQLException e) {
// Expected
}
}
/**
* Tests that the {@link DriverPropertyInfo} array returned from
* {@link Driver#getPropertyInfo(String, Properties)}
* matches the list of properties defined in Messages.properties.
*/
public void test_getPropertyInfo_MatchesMessagesProperties() {
final Map infoMap = new HashMap();
loadDriverPropertyInfoMap(infoMap);
final Map propertyMap = new HashMap();
final Map descriptionMap = new HashMap();
invokeStaticMethod(
Messages.class, "loadDriverProperties",
new Class[]{Map.class, Map.class},
new Object[]{propertyMap, descriptionMap});
assertEquals(
"Properties list size (expected) does not equal DriverPropertyInfo array length (actual)",
propertyMap.size(), infoMap.keySet().size());
assertEquals(
"Description list size (expected) does not equal DriverPropertyInfo array length (actual)",
descriptionMap.size(), infoMap.keySet().size());
for (Iterator iterator = propertyMap.keySet().iterator(); iterator.hasNext();) {
final String key = (String) iterator.next();
final DriverPropertyInfo driverPropertyInfo =
(DriverPropertyInfo) infoMap.get(propertyMap.get(key));
assertNotNull("No DriverPropertyInfo object exists for property '" + key + "'", driverPropertyInfo);
assertEquals(
"Property description (expected) does not match DriverPropertyInfo description (actual)",
descriptionMap.get(key), driverPropertyInfo.description);
}
}
/**
* Tests that the {@link DriverPropertyInfo} array returned from
* {@link Driver#getPropertyInfo(String, Properties)} contains
* the correct choices value on each of the objects.
*/
public void test_getPropertyInfo_Choices() {
String[] expectedBooleanChoices = new String[]{
String.valueOf(true),
String.valueOf(false),
};
String[] expectedPrepareSqlChoices = new String[]{
String.valueOf(TdsCore.UNPREPARED),
String.valueOf(TdsCore.TEMPORARY_STORED_PROCEDURES),
String.valueOf(TdsCore.EXECUTE_SQL),
String.valueOf(TdsCore.PREPARE)
};
String[] expectedServerTypeChoices = new String[]{
String.valueOf(Driver.SQLSERVER),
String.valueOf(Driver.SYBASE),
};
String[] expectedTdsChoices = new String[]{
DefaultProperties.TDS_VERSION_42,
DefaultProperties.TDS_VERSION_50,
DefaultProperties.TDS_VERSION_70,
DefaultProperties.TDS_VERSION_80,
};
Map expectedChoicesMap = new HashMap();
expectedChoicesMap.put(Messages.get(Driver.LASTUPDATECOUNT), expectedBooleanChoices);
expectedChoicesMap.put(Messages.get(Driver.NAMEDPIPE), expectedBooleanChoices);
expectedChoicesMap.put(Messages.get(Driver.PREPARESQL), expectedPrepareSqlChoices);
expectedChoicesMap.put(Messages.get(Driver.SERVERTYPE), expectedServerTypeChoices);
expectedChoicesMap.put(Messages.get(Driver.TDS), expectedTdsChoices);
expectedChoicesMap.put(Messages.get(Driver.SENDSTRINGPARAMETERSASUNICODE), expectedBooleanChoices);
expectedChoicesMap.put(Messages.get(Driver.CACHEMETA), expectedBooleanChoices);
expectedChoicesMap.put(Messages.get(Driver.USECURSORS), expectedBooleanChoices);
expectedChoicesMap.put(Messages.get(Driver.USELOBS), expectedBooleanChoices);
final Map infoMap = new HashMap();
loadDriverPropertyInfoMap(infoMap);
final Iterator iterator = infoMap.keySet().iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
DriverPropertyInfo info = (DriverPropertyInfo) infoMap.get(key);
if (expectedChoicesMap.containsKey(key)) {
assertEquals("Choices did not match for key " + key,
((String[]) expectedChoicesMap.get(key)), info.choices);
}
else {
assertNull("Expected choices to be null for key " + key,
expectedChoicesMap.get(key));
}
}
}
/**
* Tests that the {@link DriverPropertyInfo} array returned from
* {@link Driver#getPropertyInfo(String, Properties)} contains
* the correct required value on each of the objects.
*/
public void test_getPropertyInfo_Required() {
Map requiredTrueMap = new HashMap();
requiredTrueMap.put(Messages.get(Driver.SERVERNAME), Boolean.TRUE);
requiredTrueMap.put(Messages.get(Driver.SERVERTYPE), Boolean.TRUE);
final Map infoMap = new HashMap();
loadDriverPropertyInfoMap(infoMap);
final Iterator iterator = infoMap.keySet().iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
DriverPropertyInfo info = (DriverPropertyInfo) infoMap.get(key);
if (requiredTrueMap.containsKey(key)) {
assertTrue("The 'required' field is not true for key " + key, info.required);
}
else {
assertFalse("The 'required' field is not false for key " + key, info.required);
}
}
}
/**
* Retrieve the {@link DriverPropertyInfo} array from
* {@link Driver#getPropertyInfo(String, Properties)} and convert it
* into a {@link Map} using the name property for the keys.
*
* @param driverPropertyInfoMap The map of {@link DriverPropertyInfo} objects to be populated.
*/
private void loadDriverPropertyInfoMap(final Map driverPropertyInfoMap) {
try {
final DriverPropertyInfo[] driverPropertyInfoArray = new Driver().getPropertyInfo(
"jdbc:jtds:sqlserver://servername/databasename", new Properties());
for (int i = 0; i < driverPropertyInfoArray.length; i++) {
DriverPropertyInfo driverPropertyInfo = driverPropertyInfoArray[i];
driverPropertyInfoMap.put(driverPropertyInfo.name, driverPropertyInfo);
}
}
catch (SQLException e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* Class used to test Driver.setupConnectProperties(String, java.util.Properties).
*/
public static class Test_Driver_setupConnectProperties extends DefaultPropertiesTestLibrary {
/**
* Construct a test suite for this library.
*
* @param name The name of the tests.
* @return The test suite.
*/
public static Test suite(String name) {
return new TestSuite(Test_Driver_setupConnectProperties.class, name);
}
/**
* Default constructor.
*/
public Test_Driver_setupConnectProperties() {
setTester(
new DefaultPropertiesTester() {
public void assertDefaultProperty(
String message, String url, Properties properties, String fieldName,
String key, String expected) {
Properties results =
(Properties) invokeInstanceMethod(
new Driver(), "setupConnectProperties",
new Class[]{String.class, Properties.class},
new Object[]{url, properties});
assertEquals(message, expected, results.getProperty(Messages.get(key)));
}
}
);
}
}
/**
* Class used to test {@link Driver#getPropertyInfo(String, Properties)}.
*/
public static class Test_Driver_getPropertyInfo extends DefaultPropertiesTestLibrary {
/**
* Construct a test suite for this library.
*
* @param name The name of the tests.
* @return The test suite.
*/
public static Test suite(String name) {
return new TestSuite(Test_Driver_getPropertyInfo.class, name);
}
/**
* Default constructor.
*/
public Test_Driver_getPropertyInfo() {
setTester(
new DefaultPropertiesTester() {
public void assertDefaultProperty(
String message, String url, Properties properties, String fieldName,
String key, String expected) {
try {
boolean found = false;
String messageKey = Messages.get(key);
DriverPropertyInfo[] infoArray = new Driver().getPropertyInfo(url, properties);
for (int i = 0; i < infoArray.length; i++) {
DriverPropertyInfo info = infoArray[i];
if (info.name.equals(messageKey)) {
assertEquals(message, expected, info.value);
found = true;
}
}
if (!found) {
fail("DriverPropertyInfo for '" + messageKey + "' not found!");
}
}
catch (SQLException e) {
throw new RuntimeException(e.getMessage());
}
}
}
);
}
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/DefaultPropertiesTester.java 0000644 0001750 0001750 00000003523 11316672660 030706 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.util.Properties;
/**
* Abstract class used to test the default properties set on a variety of methods.
*
* Implements the Command pattern.
*
* @author David D. Kilzer
* @version $Id: DefaultPropertiesTester.java,v 1.3 2004/08/24 17:45:07 bheineman Exp $
*/
public abstract class DefaultPropertiesTester {
/**
* Asserts that a default property is set properly.
*
* @param message The message to display if the default property is not set.
* @param url The JDBC url.
* @param properties The initial properties set before testing the method.
* @param fieldName The field name of the object if using reflection.
* @param key The message key used to obtain the property name.
* @param expected The expected value.
*/
public abstract void assertDefaultProperty(
String message, String url, Properties properties, String fieldName, String key, String expected);
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/TlsTest.java 0000644 0001750 0001750 00000003745 11316672660 025466 0 ustar martin martin //jTDS JDBC Driver for Microsoft SQL Server and Sybase
//Copyright (C) 2004 The jTDS Project
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* Test for SSL TLS.
*
* @author Mike Hutchinson
* @version $Id: TlsTest.java,v 1.1 2005/04/15 13:03:43 alin_sinpalean Exp $
*/
public class TlsTest extends DatabaseTestCase {
public TlsTest(String name) {
super(name);
}
/**
* Test for problem resuming TLS session with SQL Server (bug [1102505] SSL
* TLS resume failure).
*/
public void testTLSResume() throws Exception {
// This connection will have established the session key
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT 'Hello'");
rs.next();
assertEquals("Hello", rs.getString(1));
con.close();
// This connection will attempt to resume the TLS session
con = getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT 'World'");
rs.next();
assertEquals("World", rs.getString(1));
}
public static void main(String[] args) {
junit.textui.TestRunner.run(TlsTest.class);
}
}
libjtds-java-1.2.5.orig/src/test/net/sourceforge/jtds/test/XaTest.java 0000644 0001750 0001750 00000036555 11316672660 025301 0 ustar martin martin //jTDS JDBC Driver for Microsoft SQL Server and Sybase
//Copyright (C) 2004 The jTDS Project
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.XAConnection;
import javax.sql.XADataSource;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import net.sourceforge.jtds.jdbc.Messages;
import net.sourceforge.jtds.jdbc.Driver;
import net.sourceforge.jtds.jdbcx.JtdsDataSource;
import net.sourceforge.jtds.jdbcx.JtdsXid;
/**
* Test suite for XA Distributed Transactions. These tests are derived from
* examples found in the following article at
* DevX.
*
* @version $Id: XaTest.java,v 1.5 2004/12/03 16:52:09 alin_sinpalean Exp $
*/
public class XaTest extends DatabaseTestCase {
public XaTest(String name) {
super(name);
}
/**
* Obtain an XADataSource.
*
* @return the XADataSource.
* @throws SQLException if an error condition occurs
*/
public XADataSource getDataSource() throws SQLException {
JtdsDataSource xaDS = new JtdsDataSource();
String user = props.getProperty(Messages.get(Driver.USER));
String pwd = props.getProperty(Messages.get(Driver.PASSWORD));
String host = props.getProperty(Messages.get(Driver.SERVERNAME));
String port = props.getProperty(Messages.get(Driver.PORTNUMBER));
String database = props.getProperty(Messages.get(Driver.DATABASENAME));
String xaMode = props.getProperty(Messages.get(Driver.XAEMULATION));
String tds = props.getProperty(Messages.get(Driver.TDS));
String serverType = props.getProperty(Messages.get(Driver.SERVERTYPE));
int portn;
try {
portn = Integer.parseInt(port);
} catch (NumberFormatException e) {
portn = 1433;
}
xaDS.setServerName(host);
xaDS.setPortNumber(portn);
xaDS.setUser(user);
xaDS.setPassword(pwd);
xaDS.setDatabaseName(database);
xaDS.setXaEmulation(xaMode.equalsIgnoreCase("true"));
xaDS.setTds(tds);
xaDS.setServerType("2".equals(serverType)? 2: 1);
return xaDS;
}
/**
* Test to demonstrate the XA_COMMIT function.
*
* @throws Exception if an error condition occurs
*/
public void testXaCommit() throws Exception {
Connection con2 = null;
XAConnection xaCon = null;
try {
dropTable("jTDS_XATEST");
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE jTDS_XATEST (id int primary key, data varchar(255))");
assertNotNull(stmt.executeQuery("SELECT * FROM jTDS_XATEST"));
stmt.close();
XADataSource xaDS = getDataSource();
XAResource xaRes;
Xid xid;
xaCon = xaDS.getXAConnection();
xaRes = xaCon.getXAResource();
con2 = xaCon.getConnection();
stmt = con2.createStatement();
xid = new JtdsXid(new byte[]{0x01}, new byte[]{0x02});
xaRes.start(xid, XAResource.TMNOFLAGS);
stmt.executeUpdate("INSERT INTO jTDS_XATEST VALUES (1, 'TEST LINE')");
xaRes.end(xid, XAResource.TMSUCCESS);
int ret = xaRes.prepare(xid);
if (ret == XAResource.XA_OK) {
xaRes.commit(xid, false);
}
stmt.close();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM jTDS_XATEST");
assertNotNull(rs);
assertTrue(rs.next());
stmt.close();
} finally {
if (con2 != null) {
con2.close();
}
if (xaCon != null) {
xaCon.close();
}
dropTable("jTDS_XATEST");
}
}
/**
* Test to demonstrate the single phase XA_COMMIT function.
*
* @throws Exception if an error condition occurs
*/
public void testXaOnePhaseCommit() throws Exception {
Connection con2 = null;
XAConnection xaCon = null;
try {
dropTable("jTDS_XATEST");
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE jTDS_XATEST (id int primary key, data varchar(255))");
assertNotNull(stmt.executeQuery("SELECT * FROM jTDS_XATEST"));
stmt.close();
XADataSource xaDS = getDataSource();
XAResource xaRes;
Xid xid;
xaCon = xaDS.getXAConnection();
xaRes = xaCon.getXAResource();
con2 = xaCon.getConnection();
stmt = con2.createStatement();
xid = new JtdsXid(new byte[]{0x01}, new byte[]{0x02});
xaRes.start(xid, XAResource.TMNOFLAGS);
stmt.executeUpdate("INSERT INTO jTDS_XATEST VALUES (1, 'TEST LINE')");
xaRes.end(xid, XAResource.TMSUCCESS);
xaRes.commit(xid, true);
stmt.close();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM jTDS_XATEST");
assertNotNull(rs);
assertTrue(rs.next());
stmt.close();
} finally {
if (con2 != null) {
con2.close();
}
if (xaCon != null) {
xaCon.close();
}
dropTable("jTDS_XATEST");
}
}
/**
* Test to demonstrate the use of the XA_ROLLBACK command.
*
* @throws Exception if an error condition occurs
*/
public void testXaRollback() throws Exception {
Connection con2 = null;
XAConnection xaCon = null;
try {
dropTable("jTDS_XATEST");
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE jTDS_XATEST (id int primary key, data varchar(255))");
assertNotNull(stmt.executeQuery("SELECT * FROM jTDS_XATEST"));
stmt.close();
XADataSource xaDS = getDataSource();
XAResource xaRes;
Xid xid;
xaCon = xaDS.getXAConnection();
xaRes = xaCon.getXAResource();
con2 = xaCon.getConnection();
stmt = con2.createStatement();
xid = new JtdsXid(new byte[]{0x01}, new byte[]{0x02});
xaRes.start(xid, XAResource.TMNOFLAGS);
stmt.executeUpdate("INSERT INTO jTDS_XATEST VALUES (1, 'TEST LINE')");
xaRes.end(xid, XAResource.TMSUCCESS);
xaRes.rollback(xid);
stmt.close();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM jTDS_XATEST");
assertNotNull(rs);
assertFalse(rs.next());
stmt.close();
} finally {
if (con2 != null) {
con2.close();
}
if (xaCon != null) {
xaCon.close();
}
dropTable("jTDS_XATEST");
}
}
/**
* Demonstrate interleaving local transactions and distributed
* transactions.
*
* @throws Exception if an error condition occurs
*/
public void testLocalTran() throws Exception {
if ("true".equalsIgnoreCase(props.getProperty(Messages.get(Driver.XAEMULATION)))) {
// Emulation mode does not support suspending transactions.
return;
}
Connection con2 = null;
XAConnection xaCon = null;
try {
dropTable("jTDS_XATEST");
dropTable("jTDS_XATEST2");
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE jTDS_XATEST (id int primary key, data varchar(255))");
stmt.execute("CREATE TABLE jTDS_XATEST2 (id int primary key, data varchar(255))");
assertNotNull(stmt.executeQuery("SELECT * FROM jTDS_XATEST"));
assertNotNull(stmt.executeQuery("SELECT * FROM jTDS_XATEST2"));
stmt.close();
XADataSource xaDS = getDataSource();
XAResource xaRes;
Xid xid;
xaCon = xaDS.getXAConnection();
xaRes = xaCon.getXAResource();
con2 = xaCon.getConnection();
stmt = con2.createStatement();
xid = new JtdsXid(new byte[]{0x01}, new byte[]{0x02});
xaRes.start(xid, XAResource.TMNOFLAGS);
stmt.executeUpdate("INSERT INTO jTDS_XATEST VALUES (1, 'TEST LINE')");
xaRes.end(xid, XAResource.TMSUSPEND);
stmt.executeUpdate("INSERT INTO jTDS_XATEST2 VALUES (1, 'TEST LINE')");
xaRes.start(xid, XAResource.TMRESUME);
stmt.executeUpdate("INSERT INTO jTDS_XATEST VALUES (2, 'TEST LINE 2')");
xaRes.end(xid, XAResource.TMSUCCESS);
xaRes.rollback(xid);
stmt.close();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM jTDS_XATEST");
assertNotNull(rs);
assertFalse(rs.next());
rs = stmt.executeQuery("SELECT * FROM jTDS_XATEST2");
assertNotNull(rs);
assertTrue(rs.next());
stmt.close();
} finally {
if (con2 != null) {
con2.close();
}
if (xaCon != null) {
xaCon.close();
}
dropTable("jTDS_XATEST");
dropTable("jTDS_XATEST2");
}
}
/**
* Test to demonstrate the use of the XA_JOIN command.
*
* @throws Exception if an error condition occurs
*/
public void testXAJoinTran() throws Exception {
if ("true".equalsIgnoreCase(props.getProperty(Messages.get(Driver.XAEMULATION)))) {
// Emulation mode does not joining transactions.
return;
}
Connection con2 = null;
Connection con3 = null;
XAConnection xaCon = null;
XAConnection xaCon2 = null;
try {
dropTable("jTDS_XATEST");
dropTable("jTDS_XATEST2");
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE jTDS_XATEST (id int primary key, data varchar(255))");
stmt.execute("CREATE TABLE jTDS_XATEST2 (id int primary key, data varchar(255))");
assertNotNull(stmt.executeQuery("SELECT * FROM jTDS_XATEST"));
assertNotNull(stmt.executeQuery("SELECT * FROM jTDS_XATEST2"));
stmt.close();
XADataSource xaDS = getDataSource();
XAResource xaRes;
XAResource xaRes2;
Xid xid;
xaCon = xaDS.getXAConnection();
xaRes = xaCon.getXAResource();
xaCon2 = xaDS.getXAConnection();
xaRes2 = xaCon2.getXAResource();
con2 = xaCon.getConnection();
con3 = xaCon2.getConnection();
stmt = con2.createStatement();
Statement stmt2 = con3.createStatement();
xid = new JtdsXid(new byte[]{0x01}, new byte[]{0x02});
xaRes.start(xid, XAResource.TMNOFLAGS);
stmt.executeUpdate("INSERT INTO jTDS_XATEST VALUES (1, 'TEST LINE')");
assertTrue(xaRes.isSameRM(xaRes2));
xaRes2.start(xid, XAResource.TMJOIN);
stmt2.executeUpdate("INSERT INTO jTDS_XATEST2 VALUES (1, 'TEST LINE 2')");
xaRes.end(xid, XAResource.TMSUCCESS);
xaRes2.end(xid, XAResource.TMSUCCESS);
int ret = xaRes.prepare(xid);
if (ret == XAResource.XA_OK) {
xaRes.commit(xid, false);
}
stmt.close();
stmt2.close();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM jTDS_XATEST");
assertNotNull(rs);
assertTrue(rs.next());
rs = stmt.executeQuery("SELECT * FROM jTDS_XATEST2");
assertNotNull(rs);
assertTrue(rs.next());
stmt.close();
} finally {
if (con2 != null) {
con2.close();
}
if (con3 != null) {
con3.close();
}
if (xaCon != null) {
xaCon.close();
}
if (xaCon2 != null) {
xaCon2.close();
}
dropTable("jTDS_XATEST");
dropTable("jTDS_XATEST2");
}
}
/**
* Test to demonstrate the use of the XA_RECOVER command.
*
* @throws Exception if an error condition occurs
*/
public void testXARecover() throws Exception {
XAConnection xaCon = null;
try {
dropTable("jTDS_XATEST");
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE jTDS_XATEST (id int primary key, data varchar(255))");
assertNotNull(stmt.executeQuery("SELECT * FROM jTDS_XATEST"));
stmt.close();
XADataSource xaDS = getDataSource();
xaCon = xaDS.getXAConnection();
Connection con2 = xaCon.getConnection();
XAResource xaRes = xaCon.getXAResource();
stmt = con2.createStatement();
Xid xid;
xid = new JtdsXid(new byte[]{0x01}, new byte[]{0x02});
xaRes.start(xid, XAResource.TMNOFLAGS);
stmt.executeUpdate("INSERT INTO jTDS_XATEST VALUES (1, 'TEST LINE')");
xaRes.end(xid, XAResource.TMSUCCESS);
xaRes.prepare(xid);
stmt.close();
con2.close();
xaCon.close();
xaCon = xaDS.getXAConnection();
xaRes = xaCon.getXAResource();
Xid[] list = xaRes.recover(XAResource.TMSTARTRSCAN);
for (int i = 0; i < list.length; i++) {
//System.out.println("Xid="+list[i].toString());
try {
xaRes.rollback(list[i]);
} catch (XAException e) {
// System.out.println("Forgetting");
xaRes.forget(list[i]);
}
}
} finally {
if (xaCon != null) {
xaCon.close();
}
dropTable("jTDS_XATEST");
}
}
public static void main(String[] args) {
junit.textui.TestRunner.run(XaTest.class);
}
}
libjtds-java-1.2.5.orig/src/tools/ 0000755 0001750 0001750 00000000000 11316672660 016335 5 ustar martin martin libjtds-java-1.2.5.orig/src/tools/net/ 0000755 0001750 0001750 00000000000 11316672660 017123 5 ustar martin martin libjtds-java-1.2.5.orig/src/tools/net/sourceforge/ 0000755 0001750 0001750 00000000000 11316672660 021446 5 ustar martin martin libjtds-java-1.2.5.orig/src/tools/net/sourceforge/jtds/ 0000755 0001750 0001750 00000000000 11316672660 022412 5 ustar martin martin libjtds-java-1.2.5.orig/src/tools/net/sourceforge/jtds/tools/ 0000755 0001750 0001750 00000000000 11316672660 023552 5 ustar martin martin libjtds-java-1.2.5.orig/src/tools/net/sourceforge/jtds/tools/TestAllPipeInstancesAreBusy.java 0000644 0001750 0001750 00000012340 11316672660 031746 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2005 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.tools;
import junit.framework.TestCase;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.io.PrintWriter;
/**
* JUnit test class to expose the "All pipe instances are busy" error.
*
* Run this class from two or more different computers (Linux and/or Windows)
* so that multiple requests for the named pipe are hitting the server at the
* same time. There are many factors that exacerbate the issue, although
* using SQL Server 6.5, slow (higher latency) TCP/IP connections and adding
* more computers hitting the server simultaneously seem to be the top three.
*
* See also
* INF: Multiple Named Pipes Connections May Cause Error 17832 on
* Microsoft's knowledgebase web site.
*
* @author David D. Kilzer
* @version $Id: TestAllPipeInstancesAreBusy.java,v 1.2 2005/09/06 22:57:08 ddkilzer Exp $
*/
public class TestAllPipeInstancesAreBusy extends TestCase {
private static final Properties CONNECTION_PROPERTIES = new Properties();
private static final String CONNECTION_URL = "jdbc:jtds:sqlserver://HOSTNAME/DATABASENAME;namedPipe=true;TDS=4.2";
public static void main(String[] args) {
new TestAllPipeInstancesAreBusy("main").testAllPipeInstancesAreBusy();
}
static {
//DriverManager.setLogWriter(new PrintWriter(System.err));
try {
// Register the driver
Class.forName("net.sourceforge.jtds.jdbc.Driver");
}
catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public TestAllPipeInstancesAreBusy(String name) {
super(name);
}
/**
* Test method that creates concurrentCount threads, then calls
* {@link #connectToDatabaseAndClose()} to connect to the database. This keeps
* the computer running this method very busy trying to establish connections
* to the database. One computer is not enough to cause the "All pipe
* instances are busy" error, though.
*/
public void testAllPipeInstancesAreBusy() {
final int concurrentCount = 100;
final ConnectionRunnable[] cr = new ConnectionRunnable[concurrentCount];
final Thread[] t = new Thread[concurrentCount];
for (int i = 0; i < concurrentCount; i++) {
cr[i] = new ConnectionRunnable("r" + String.valueOf(i));
t[i] = new Thread(cr[i]);
}
for (int i = 0; i < concurrentCount; i++) {
t[i].start();
}
try {
for (int i = 0; i < concurrentCount; i++) {
t[i].join();
}
}
catch (InterruptedException e) {
e.printStackTrace(System.err);
throw new RuntimeException(e);
}
boolean result = true;
for (int i = 0; i < concurrentCount; i++) {
result = result && cr[i].isPassed();
}
if (!result) {
throw new AssertionError();
}
}
/**
* Connects to the database, does (optional) work, then disconnects.
*
* @throws SQLException on error.
*/
private void connectToDatabaseAndClose() throws SQLException {
DriverManager.getConnection(CONNECTION_URL, CONNECTION_PROPERTIES).close();
}
/**
* Class instantiated for each thread that calls
* {@link TestAllPipeInstancesAreBusy#connectToDatabaseAndClose()}
* continuously.
*/
private class ConnectionRunnable implements Runnable {
private boolean passed;
private String name;
private int count;
public ConnectionRunnable(String name) {
this.name = name;
}
public void run() {
try {
passed = true;
count = 0;
while (true) {
connectToDatabaseAndClose();
count++;
}
}
catch (Exception e) {
System.err.print(name + ": " + count + ": ");
e.printStackTrace(System.err);
passed = false;
}
}
public boolean isPassed() {
return passed;
}
}
}
libjtds-java-1.2.5.orig/src/tools/net/sourceforge/jtds/tools/SqlForwarder.java 0000644 0001750 0001750 00000011047 11316672660 027033 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.tools;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author Alin Sinpalean
* @version $Id: SqlForwarder.java,v 1.2.6.1 2009/08/04 10:33:50 ickzon Exp $
*/
public class SqlForwarder {
String host = "localhost";
String logfile = null;
int port = 1433;
int listenPort = 1444;
int lognum = 0;
byte[] readPacket(InputStream input) throws IOException {
byte[] hdr = new byte[8];
int len = input.read(hdr);
if (len < 8) {
return null;
}
int packetlen = ((((int) hdr[2]) & 0xff) << 8) + (((int) hdr[3]) & 0xff);
byte[] data = new byte[packetlen];
while (len < packetlen) {
len += input.read(data, len, packetlen - len);
}
for (int i = 0; i < 8; i++) {
data[i] = hdr[i];
}
return data;
}
class ConnectionThread extends Thread {
Socket client;
Socket server;
ConnectionThread(Socket client, Socket server) {
this.client = client;
this.server = server;
}
public void run() {
try {
InputStream input[] = new InputStream[2];
input[0] = client.getInputStream();
input[1] = server.getInputStream();
OutputStream output[] = new OutputStream[2];
output[0] = server.getOutputStream();
output[1] = client.getOutputStream();
PacketLogger log;
if (logfile == null) {
log = new PacketLogger("filter" + lognum++ + ".log");
} else {
log = new PacketLogger(logfile + lognum++ + ".log");
}
int direction = 0;
while (true) {
byte[] data = readPacket(input[direction]);
if (data == null) {
break;
}
output[direction].write(data);
log.log(data);
if (data[1] != 0) {
direction = 1 - direction;
}
}
client.close();
server.close();
} catch (IOException unused) {
}
}
}
SqlForwarder() {
}
void run() throws IOException {
System.out.println("Listening on port " + listenPort + "; Connecting to " + host + " at port " + port);
ServerSocket srv = new ServerSocket(listenPort);
while (true) {
Socket client = srv.accept();
Socket server = new Socket(host, port);
ConnectionThread t = new ConnectionThread(client, server);
t.start();
}
}
void parseArgs(String args[]) throws NumberFormatException {
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.equals("-server")) {
i++;
host = args[i];
} else if (arg.equals("-port")) {
i++;
port = Integer.parseInt(args[i]);
} else if (arg.equals("-listen")) {
i++;
listenPort = Integer.parseInt(args[i]);
} else if (arg.equals("-log")) {
i++;
logfile = args[i];
}
}
}
public static void main(String args[])
throws IOException {
SqlForwarder app = new SqlForwarder();
app.parseArgs(args);
app.run();
}
}
libjtds-java-1.2.5.orig/src/tools/net/sourceforge/jtds/tools/SQLProxy.java 0000644 0001750 0001750 00000011355 11316672660 026123 0 ustar martin martin // jTDS JDBC Driver for Microsoft SQL Server and Sybase
// Copyright (C) 2004 The jTDS Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package net.sourceforge.jtds.tools;
import java.io.*;
import java.net.*;
/**
* @author Alin Sinpalean
* @version $Id: SQLProxy.java,v 1.1.8.1 2009/08/04 10:33:50 ickzon Exp $
*/
public class SQLProxy
{
static final int LOCAL_PORT = 1433;
static final String SERVER = "server";
static final int SERVER_PORT = 1433;
public static void main(String args[]) throws IOException
{
ServerSocket sock = new ServerSocket(LOCAL_PORT);
while( true )
{
Socket s = sock.accept();
new DumpThread(s).start();
}
}
}
class DumpThread extends Thread
{
private Socket client, server;
private byte[] buf = new byte[4096];
DumpThread(Socket client)
{
this.client = client;
}
String hex(int value, int len)
{
String res = Integer.toHexString(value);
while( res.length() < len )
res = '0' + res;
return res.toUpperCase();
}
String packetType(int value)
{
switch( value )
{
case 0x01:
return "4.2 or 7.0 query";
case 0x02:
return "4.2 or 7.0 login packet";
case 0x04:
return "Server response";
case 0x06:
return "Cancel";
case 0x0F:
return "5.0 query";
case 0x10:
return "7.0 login packet";
default:
return "Unknown (0x"+hex(value, 2)+')';
}
}
int passByte(InputStream in, OutputStream out) throws IOException
{
int res = in.read();
out.write(res);
return res;
}
void skip(int len, InputStream in, OutputStream out) throws IOException
{
while( len > 0 )
{
int rd = in.read(buf, 0, len>buf.length ? buf.length : len);
// for( int i=0; i