net.sourceforge.jtds.jdbc

Class TdsCore


public class TdsCore
extends java.lang.Object

This class implements the Sybase / Microsoft TDS protocol.

Implementation notes:

  1. This class, together with TdsData, encapsulates all of the TDS specific logic required by the driver.
  2. This is a ground up reimplementation of the TDS protocol and is rather simpler, and hopefully easier to understand, than the original.
  3. The layout of the various Login packets is derived from the original code and freeTds work, and incorporates changes including the ability to login as a TDS 5.0 user.
  4. All network I/O errors are trapped here, reported to the log (if active) and the parent Connection object is notified that the connection should be considered closed.
  5. Rather than having a large number of classes one for each token, useful information about the current token is gathered together in the inner TdsToken class.
  6. As the rest of the driver interfaces to this code via higher-level method calls there should be know need for knowledge of the TDS protocol to leak out of this class. It is for this reason that all the TDS Token constants are private.
Version:
$Id: TdsCore.java,v 1.115 2007/07/08 17:28:23 bheineman Exp $
Authors:
Mike Hutchinson
Matt Brinkley
Alin Sinpalean
FreeTDS project

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.
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
static int
EXECUTE_SQL
Prepare SQL using sp_executesql
static byte
LOGIN_PKT
TDS 4.2 or 5.0 Login packet.
static int
MAX_PKT_SIZE
Maximum network packet size.
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.
static byte
NTLMAUTH_PKT
TDS 7.0 NTLM Authentication packet.
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.
static byte
RPC_PKT
TDS Remote Procedure Call.
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.
static byte
SYBQUERY_PKT
TDS 5.0 Query packet.
(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.
private static byte
TDS5_DYNAMIC_TOKEN
TDS 5.0 Dynamic SQL token.
private static byte
TDS5_PARAMFMT2_TOKEN
TDS 5.0 Parameter format token.
private static byte
TDS5_PARAMFMT_TOKEN
TDS 5.0 parameter descriptor 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 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_DONEINPROC_TOKEN
TDS done in procedure token.
private static byte
TDS_DONEPROC_TOKEN
TDS done procedure token.
private static byte
TDS_DONE_TOKEN
TDS done token.
private static byte
TDS_ENVCHANGE_TOKEN
TDS environment change 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_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.
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
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.
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.
private boolean
fatalError
Indicates that a fatal error has occured and the connection will close.
private static 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.
private SQLDiagnostic
messages
The head of the diagnostic messages chain.
private int
nextParam
The index of the next output parameter to populate.
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.
private ParamInfo
returnParam
The return parameter meta data object for the current procedure call.
private Integer
returnStatus
The stored procedure return status.
private Object[]
rowData
The array of column data objects in the current row.
private int
serverType
The make of SQL Server (Sybase/Microsoft).
private SharedSocket
socket
The Shared network socket object.
private int
sslMode
Indicates type of SSL connection.
private static SSPIJNIClient
sspiJNIClient
A reference to ntlm.SSPIJNIClient.
private TdsCore.TableMetaData[]
tables
The array of table names associated with this result.
private static HashMap
tds8SpNames
Map of system stored procedures that have shortcuts in TDS8.
private int
tdsVersion
The TDS version being supported by this connection.

Constructor Summary

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(String sql, 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(String sql, String procName, ParamInfo[] parameters, boolean noMetaData, boolean sendNow)
Execute SQL using TDS 4.2 protocol.
private void
executeSQL50(String sql, String procName, ParamInfo[] parameters)
Execute SQL using TDS 5.0 protocol.
private void
executeSQL70(String sql, String procName, ParamInfo[] parameters, boolean noMetaData, boolean sendNow)
Execute SQL using TDS 7.0 protocol.
(package private) SQLException
getBatchCounts(ArrayList counts, SQLException sqlEx)
Obtain the counts from a batch of SQL updates.
(package private) ColInfo[]
getColumns()
Retrieve the current result set column descriptors.
private static 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(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) Integer
getReturnStatus()
Retrieve the return status for the current stored procedure.
(package private) 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(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(String serverName, String database, String user, String password, String domain, String charset, String appName, String progName, String wsid, String language, String macAddress, int packetSize)
Login to the SQL Server.
(package private) String
microsoftPrepare(String sql, ParamInfo[] params, boolean needCursor, int resultSetType, int resultSetConcurrency)
Prepares the SQL for use with Microsoft server.
(package private) void
negotiateSSL(String instance, String ssl)
Negotiate SSL settings with SQL 2000+ server.
private void
nextToken()
Read the next TDS token from the response stream.
private void
putLoginString(String txt, int len)
Write a TDS login packet string.
private int
readPreLoginPacket()
Process the pre login acknowledgement from the server.
private void
send42LoginPkt(String serverName, String user, String password, String charset, String appName, String progName, String wsid, String language, int packetSize)
TDS 4.2 Login Packet.
private void
send50LoginPkt(String serverName, String user, String password, String charset, String appName, String progName, String wsid, String language, int packetSize)
TDS 5.0 Login Packet.
private void
sendMSLoginPkt(String serverName, String database, String user, String password, String domain, String appName, String progName, String wsid, String language, String macAddress, int netPacketSize)
Send a TDS 7 login packet.
private void
sendNtlmChallengeResponse(byte[] nonce, String user, String password, String domain)
Send the response to the NTLM authentication challenge.
private void
sendPreLoginPacket(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(String sql)
Submit a simple SQL statement to the server and process all output.
(package private) String
sybasePrepare(String sql, ParamInfo[] params)
Creates a light weight stored procedure on a Sybase server.
(package private) void
sybaseUnPrepare(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 String
tds7CryptPass(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.

Field Details

ASYNC_CANCEL

private static final int ASYNC_CANCEL
Cancel has been generated by Statement.cancel().
Field Value:
0

CANCEL_PKT

public static final byte CANCEL_PKT
TDS Cancel packet.
Field Value:
6

DEFAULT_MIN_PKT_SIZE_TDS70

public static final int DEFAULT_MIN_PKT_SIZE_TDS70
Default minimum network packet size for TDS 7.0 and newer.
Field Value:
4096

DONE_CANCEL

(package private) static final byte DONE_CANCEL
Done: Cancel acknowledgement.
Field Value:
32

DONE_END_OF_RESPONSE

private static final 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).
Field Value:
-128

DONE_ERROR

private static final byte DONE_ERROR
Done: command caused an error.
Field Value:
2

DONE_MORE_RESULTS

private static final byte DONE_MORE_RESULTS
Done: more results are expected.
Field Value:
1

DONE_ROW_COUNT

private static final byte DONE_ROW_COUNT
Done: There is a valid row count.
Field Value:
16

EMPTY_PARAMETER_INFO

private static final ParamInfo[] EMPTY_PARAMETER_INFO
Used to optimize the getParameters() call

EXECUTE_SQL

public static final int EXECUTE_SQL
Prepare SQL using sp_executesql
Field Value:
2

LOGIN_PKT

public static final byte LOGIN_PKT
TDS 4.2 or 5.0 Login packet.
Field Value:
2

MAX_PKT_SIZE

public static final int MAX_PKT_SIZE
Maximum network packet size.
Field Value:
32768

MIN_PKT_SIZE

public static final int MIN_PKT_SIZE
Minimum network packet size.
Field Value:
512

MSDTC_PKT

public static final byte MSDTC_PKT
TDS MSDTC packet.
Field Value:
14

MSLOGIN_PKT

public static final byte MSLOGIN_PKT
TDS 7.0 Login packet.
Field Value:
16

NTLMAUTH_PKT

public static final byte NTLMAUTH_PKT
TDS 7.0 NTLM Authentication packet.
Field Value:
17

PKT_HDR_LEN

public static final int PKT_HDR_LEN
The size of the packet header.
Field Value:
8

PRELOGIN_PKT

public static final byte PRELOGIN_PKT
SQL 2000 prelogin negotiation packet.
Field Value:
18

PREPARE

public static final int PREPARE
Prepare SQL using sp_prepare and sp_execute
Field Value:
3

QUERY_PKT

public static final byte QUERY_PKT
TDS 4.2 or 7.0 Query packet.
Field Value:
1

REPLY_PKT

public static final byte REPLY_PKT
TDS Reply packet.
Field Value:
4

RPC_PKT

public static final byte RPC_PKT
TDS Remote Procedure Call.
Field Value:
3

SSL_CLIENT_FORCE_ENCRYPT

public static final int SSL_CLIENT_FORCE_ENCRYPT
SSL Mode - Client requested force encryption.
Field Value:
1

SSL_ENCRYPT_LOGIN

public static final int SSL_ENCRYPT_LOGIN
SSL Mode - Login packet must be encrypted.
Field Value:
0

SSL_NO_ENCRYPT

public static final int SSL_NO_ENCRYPT
SSL Mode - No server certificate installed.
Field Value:
2

SSL_SERVER_FORCE_ENCRYPT

public static final int SSL_SERVER_FORCE_ENCRYPT
SSL Mode - Server requested force encryption.
Field Value:
3

SYBQUERY_PKT

public static final byte SYBQUERY_PKT
TDS 5.0 Query packet.
Field Value:
15

SYB_BIGINT

(package private) static final int SYB_BIGINT
Sybase 15+ bigint.
Field Value:
64

SYB_BITNULL

(package private) static final int SYB_BITNULL
Sybase nullable bit type.
Field Value:
4

SYB_DATETIME

(package private) static final int SYB_DATETIME
Sybase date and time data types.
Field Value:
2

SYB_EXTCOLINFO

(package private) static final int SYB_EXTCOLINFO
Sybase extended column meta data.
Field Value:
8

SYB_LONGDATA

(package private) static final int SYB_LONGDATA
Sybase char and binary > 255.
Field Value:
1

SYB_UNICODE

(package private) static final int SYB_UNICODE
Sybase univarchar etc.
Field Value:
16

SYB_UNITEXT

(package private) static final int SYB_UNITEXT
Sybase 15+ unitext.
Field Value:
32

TDS5_DYNAMIC_TOKEN

private static final byte TDS5_DYNAMIC_TOKEN
TDS 5.0 Dynamic SQL token.
Field Value:
-25

TDS5_PARAMFMT2_TOKEN

private static final byte TDS5_PARAMFMT2_TOKEN
TDS 5.0 Parameter format token.
Field Value:
32

TDS5_PARAMFMT_TOKEN

private static final byte TDS5_PARAMFMT_TOKEN
TDS 5.0 parameter descriptor token.
Field Value:
-20

TDS5_PARAMS_TOKEN

private static final byte TDS5_PARAMS_TOKEN
TDS 5.0 parameter value token.
Field Value:
-41

TDS5_WIDE_RESULT

private static final byte TDS5_WIDE_RESULT
TSD 5.0 Wide result set token.
Field Value:
97

TDS7_COMP_RESULT_TOKEN

private static final byte TDS7_COMP_RESULT_TOKEN
TDS 7.0 Computed Result set column meta data token.
Field Value:
-120

TDS7_RESULT_TOKEN

private static final byte TDS7_RESULT_TOKEN
TDS 7.0 Result set column meta data token.
Field Value:
-127

TDS_ALTROW

private static final byte TDS_ALTROW
TDS Computed result set data row token.
Field Value:
-45

TDS_AUTH_TOKEN

private static final byte TDS_AUTH_TOKEN
TDS 7.0 NTLM authentication challenge token.
Field Value:
-19

TDS_CAP_TOKEN

private static final byte TDS_CAP_TOKEN
TDS 5.0 capabilities token.
Field Value:
-30

TDS_CLOSE_TOKEN

private static final byte TDS_CLOSE_TOKEN
TDS 5.0 Close token.
Field Value:
113

TDS_COLFMT_TOKEN

private static final byte TDS_COLFMT_TOKEN
TDS 4.2 Column meta data token.
Field Value:
-95

TDS_COLINFO_TOKEN

private static final byte TDS_COLINFO_TOKEN
TDS Cursor results column infomation token.
Field Value:
-91

TDS_COLNAME_TOKEN

private static final byte TDS_COLNAME_TOKEN
TDS 4.2 Column names token.
Field Value:
-96

TDS_COMP_NAMES_TOKEN

private static final byte TDS_COMP_NAMES_TOKEN
TDS Computed result set names token.
Field Value:
-89

TDS_COMP_RESULT_TOKEN

private static final byte TDS_COMP_RESULT_TOKEN
TDS Computed result set token.
Field Value:
-88

TDS_CONTROL_TOKEN

private static final byte TDS_CONTROL_TOKEN
TDS control token.
Field Value:
-82

TDS_DBRPC_TOKEN

private static final byte TDS_DBRPC_TOKEN
TDS 5.0 RPC token.
Field Value:
-26

TDS_DONEINPROC_TOKEN

private static final byte TDS_DONEINPROC_TOKEN
TDS done in procedure token.
Field Value:
-1

TDS_DONEPROC_TOKEN

private static final byte TDS_DONEPROC_TOKEN
TDS done procedure token.
Field Value:
-2

TDS_DONE_TOKEN

private static final byte TDS_DONE_TOKEN
TDS done token.
Field Value:
-3

TDS_ENVCHANGE_TOKEN

private static final byte TDS_ENVCHANGE_TOKEN
TDS environment change token.
Field Value:
-29

TDS_ENV_CHARSET

private static final byte TDS_ENV_CHARSET
Environment change: charset changed.
Field Value:
3

TDS_ENV_DATABASE

private static final byte TDS_ENV_DATABASE
Environment change: database changed.
Field Value:
1

TDS_ENV_LANG

private static final byte TDS_ENV_LANG
Environment change: language changed.
Field Value:
2

TDS_ENV_LCID

private static final byte TDS_ENV_LCID
Environment change: locale changed.
Field Value:
5

TDS_ENV_PACKSIZE

private static final byte TDS_ENV_PACKSIZE
Environment change: network packet size changed.
Field Value:
4

TDS_ENV_SQLCOLLATION

private static final byte TDS_ENV_SQLCOLLATION
Environment change: TDS 8 collation changed.
Field Value:
7

TDS_ERROR_TOKEN

private static final byte TDS_ERROR_TOKEN
TDS error result token.
Field Value:
-86

TDS_INFO_TOKEN

private static final byte TDS_INFO_TOKEN
TDS Information message token.
Field Value:
-85

TDS_LANG_TOKEN

private static final byte TDS_LANG_TOKEN
TDS 5.0 Language token.
Field Value:
33

TDS_LOGINACK_TOKEN

private static final byte TDS_LOGINACK_TOKEN
TDS Login acknowledgement token.
Field Value:
-83

TDS_MSG50_TOKEN

private static final byte TDS_MSG50_TOKEN
TDS 5.0 message token.
Field Value:
-27

TDS_OFFSETS_TOKEN

private static final byte TDS_OFFSETS_TOKEN
TDS DBLIB Offsets token.
Field Value:
120

TDS_OPTIONCMD_TOKEN

private static final byte TDS_OPTIONCMD_TOKEN
TDS Optional command token.
Field Value:
-90

TDS_ORDER_TOKEN

private static final byte TDS_ORDER_TOKEN
TDS Order by columns token.
Field Value:
-87

TDS_PARAM_TOKEN

private static final byte TDS_PARAM_TOKEN
TDS Output parameter value token.
Field Value:
-84

TDS_PROCID

private static final byte TDS_PROCID
TDS Procedure ID token.
Field Value:
124

TDS_RESULT_TOKEN

private static final byte TDS_RESULT_TOKEN
TDS 5.0 Result set column meta data token.
Field Value:
-18

TDS_RETURNSTATUS_TOKEN

private static final byte TDS_RETURNSTATUS_TOKEN
TDS Procedure call return status token.
Field Value:
121

TDS_ROW_TOKEN

private static final byte TDS_ROW_TOKEN
TDS Result set data row token.
Field Value:
-47

TDS_TABNAME_TOKEN

private static final byte TDS_TABNAME_TOKEN
TDS Table name token.
Field Value:
-92

TEMPORARY_STORED_PROCEDURES

public static final int TEMPORARY_STORED_PROCEDURES
Prepare SQL using temporary stored procedures
Field Value:
1

TIMEOUT_CANCEL

private static final int TIMEOUT_CANCEL
Cancel has been generated by a query timeout.
Field Value:
1

UNPREPARED

public static final int UNPREPARED
Do not prepare SQL
Field Value:
0

cancelMonitor

private final int[] cancelMonitor

cancelPending

private boolean cancelPending
Indicates pending cancel that needs to be cleared.

columns

private ColInfo[] columns
The array of column meta data objects for this result set.

connection

private final ConnectionJDBC2 connection
The Connection object that created this object.

connectionLock

private Semaphore connectionLock
Mutual exclusion lock on connection.

currentToken

private TdsCore.TdsToken currentToken
The descriptor object for the current TDS token.

endOfResponse

private boolean endOfResponse
True if the server response is fully read.

endOfResults

private boolean endOfResults
True if the current result set is at end of file.

fatalError

private boolean fatalError
Indicates that a fatal error has occured and the connection will close.

hostName

private static String hostName
Name of the client host (it can take quite a while to find it out if DNS is configured incorrectly).

in

private final ResponseStream in
The input server response stream.

inBatch

private boolean inBatch
Indicates processing a batch.

isClosed

private boolean isClosed
Indicates that this object is closed.

messages

private final SQLDiagnostic messages
The head of the diagnostic messages chain.

nextParam

private int nextParam
The index of the next output parameter to populate.

ntlmAuthSSO

private boolean ntlmAuthSSO
Flag that indicates if logon() should try to use Windows Single Sign On using SSPI.

out

private final RequestStream out
The output server request stream.

parameters

private ParamInfo[] parameters
The array of parameter meta data objects for the current procedure call.

returnParam

private ParamInfo returnParam
The return parameter meta data object for the current procedure call.

returnStatus

private Integer returnStatus
The stored procedure return status.

rowData

private Object[] rowData
The array of column data objects in the current row.

serverType

private final int serverType
The make of SQL Server (Sybase/Microsoft).

socket

private final SharedSocket socket
The Shared network socket object.

sslMode

private int sslMode
Indicates type of SSL connection.

sspiJNIClient

private static SSPIJNIClient sspiJNIClient
A reference to ntlm.SSPIJNIClient.

tables

private TdsCore.TableMetaData[] tables
The array of table names associated with this result.

tds8SpNames

private static HashMap tds8SpNames
Map of system stored procedures that have shortcuts in TDS8.

tdsVersion

private int tdsVersion
The TDS version being supported by this connection.

Constructor Details

TdsCore

(package private)  TdsCore(ConnectionJDBC2 connection,
                           SQLDiagnostic messages)
Construct a TdsCore object.
Parameters:
connection - The connection which owns this object.
messages - The SQLDiagnostic messages chain.

Method Details

cancel

(package private)  void cancel(boolean timeout)
Send (only) one cancel packet to the server.
Parameters:
timeout - true if this is a query timeout cancel

checkOpen

private void checkOpen()
            throws SQLException
Check that the connection is still open.

cleanUp

public void cleanUp()
Releases parameter and result set data and metadata to free up memory.

This is useful before the TdsCore is cached for reuse.


clearResponseQueue

(package private)  void clearResponseQueue()
            throws SQLException
Empty the server response queue.

close

(package private)  void close()
            throws SQLException
Close the TdsCore connection object and associated streams.

closeConnection

(package private)  void closeConnection()
Inform the server that this connection is closing.

Used by Sybase a no-op for Microsoft.


consumeOneResponse

(package private)  void consumeOneResponse()
            throws SQLException
Consume packets from the server response queue up to (and including) the first response terminator.

enlistConnection

(package private)  byte[] enlistConnection(int type,
                                           byte[] oleTranID)
            throws SQLException
Enlist the current connection in a distributed transaction or request the location of the MSDTC instance controlling the server we are connected to.
Parameters:
type - set to 0 to request TM address or 1 to enlist connection
oleTranID - the 40 OLE transaction ID
Returns:
a byte[] array containing the TM address data

executeSQL

(package private)  void executeSQL(String sql,
                                   String procName,
                                   ParamInfo[] parameters,
                                   boolean noMetaData,
                                   int timeOut,
                                   int maxRows,
                                   int maxFieldSize,
                                   boolean sendNow)
            throws SQLException
Send an SQL statement with optional parameters to the server.
Parameters:
sql - SQL statement to execute
procName - stored procedure to execute or null
parameters - parameters for call or null
noMetaData - suppress meta data for cursor calls
timeOut - optional query timeout or 0
maxRows - 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

executeSQL42

private void executeSQL42(String sql,
                          String procName,
                          ParamInfo[] parameters,
                          boolean noMetaData,
                          boolean sendNow)
            throws IOException,
                   SQLException
Execute SQL using TDS 4.2 protocol.
Parameters:
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.

executeSQL50

private void executeSQL50(String sql,
                          String procName,
                          ParamInfo[] parameters)
            throws IOException,
                   SQLException
Execute SQL using TDS 5.0 protocol.
Parameters:
sql - The SQL statement to execute.
procName - Stored procedure to execute or null.
parameters - Parameters for call or null.

executeSQL70

private void executeSQL70(String sql,
                          String procName,
                          ParamInfo[] parameters,
                          boolean noMetaData,
                          boolean sendNow)
            throws IOException,
                   SQLException
Execute SQL using TDS 7.0 protocol.
Parameters:
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.

getBatchCounts

(package private)  SQLException getBatchCounts(ArrayList counts,
                                               SQLException sqlEx)
Obtain the counts from a batch of SQL updates.

If an error occurs Sybase will continue processing a batch consisting of TDS_LANGUAGE records whilst SQL Server will usually stop after the first error except when the error is caused by a duplicate key. Sybase will also stop after the first error when executing RPC calls. Care is taken to ensure that SQLExceptions are chained because there could be several errors reported in a batch.

Parameters:
counts - the ArrayList containing the update counts
sqlEx - any previous SQLException(s) encountered
Returns:
updated SQLException or null if no error has yet occured

getColumns

(package private)  ColInfo[] getColumns()
Retrieve the current result set column descriptors.
Returns:
The column descriptors as a ColInfo[].

getHostName

private static String getHostName()
Tries to figure out what client name we should identify ourselves as. Gets the hostname of this machine,
Returns:
name to use as the client

getIntFromBuffer

private static int getIntFromBuffer(byte[] buf,
                                    int offset)

getMACAddress

private static byte[] getMACAddress(String macString)
Converts a user supplied MAC address into a byte array.
Parameters:
macString - the MAC address as a hex string
Returns:
the MAC address as a byte[]

getMessages

public SQLDiagnostic getMessages()
Returns the diagnostic chain for this instance.

getMoreResults

(package private)  boolean getMoreResults()
            throws SQLException
Get the next result set or update count from the TDS stream.
Returns:
boolean if the next item is a result set.

getNextRow

(package private)  boolean getNextRow()
            throws SQLException
Retrieve the next data row from the result set.
Returns:
false if at the end of results, true otherwise

getParameters

(package private)  ParamInfo[] getParameters()
Retrieve the parameter meta data from a Sybase prepare.
Returns:
The parameter descriptors as a ParamInfo[].

getReturnStatus

(package private)  Integer getReturnStatus()
Retrieve the return status for the current stored procedure.
Returns:
The return status as an Integer.

getRowData

(package private)  Object[] getRowData()
Retrieve the current result set data items.
Returns:
the row data as an Object array

getShortFromBuffer

private static int getShortFromBuffer(byte[] buf,
                                      int offset)

getTdsVersion

(package private)  int getTdsVersion()
Retrieve the TDS protocol version.
Returns:
The protocol version as an int.

getUpdateCount

(package private)  int getUpdateCount()
Retrieve the update count from the current TDS token.
Returns:
The update count as an int.

isDataInResultSet

(package private)  boolean isDataInResultSet()
            throws SQLException
Retrieve the status of result set.

This does a quick read ahead and is needed to support the isLast() method in the ResultSet.

Returns:
boolean - true if there is more data in the result set.

isEndOfResponse

(package private)  boolean isEndOfResponse()
Retrieve the status of the response stream.
Returns:
boolean true if the response has been entirely consumed

isPreparedProcedureName

public static boolean isPreparedProcedureName(String procName)
Returns true if the specified procName is a sp_prepare or sp_prepexec handle; returns false otherwise.
Parameters:
procName - Stored procedure to execute or null.
Returns:
true if the specified procName is a sp_prepare or sp_prepexec handle; false otherwise.

isResultSet

(package private)  boolean isResultSet()
Retrieve the status of the next result item.
Returns:
boolean true if the next item is a result set.

isRowData

(package private)  boolean isRowData()
Retrieve the status of the next result item.
Returns:
boolean true if the next item is row data.

isUpdateCount

(package private)  boolean isUpdateCount()
Retrieve the status of the next result item.
Returns:
boolean true if the next item is an update count.

login

(package private)  void login(String serverName,
                              String database,
                              String user,
                              String password,
                              String domain,
                              String charset,
                              String appName,
                              String progName,
                              String wsid,
                              String language,
                              String macAddress,
                              int packetSize)
            throws SQLException
Login to the SQL Server.
Parameters:
serverName - server host name
database - required database
user - user name
password - user password
domain - Windows NT domain (or null)
charset - required server character set
appName - application name
progName - library name
wsid - workstation ID
language - language to use for server messages
macAddress - client network MAC address
packetSize - required network packet size

microsoftPrepare

(package private)  String microsoftPrepare(String sql,
                                           ParamInfo[] params,
                                           boolean needCursor,
                                           int resultSetType,
                                           int resultSetConcurrency)
            throws SQLException
Prepares the SQL for use with Microsoft server.
Parameters:
sql - the SQL statement to prepare.
params - the actual parameter list
needCursor - true if a cursorprepare is required
resultSetType - value of the resultSetType parameter when the Statement was created
resultSetConcurrency - value of the resultSetConcurrency parameter whenthe Statement was created
Returns:
name of the procedure or prepared statement handle.

negotiateSSL

(package private)  void negotiateSSL(String instance,
                                     String ssl)
            throws IOException,
                   SQLException
Negotiate SSL settings with SQL 2000+ server.

Server returns the following values for SSL mode:

    0 = Certificate installed encrypt login packet only.
  1. 1 = Certificate installed client requests force encryption.
  2. 2 = No certificate no encryption possible.
  3. 3 = Server requests force encryption.
Parameters:
instance - The server instance name.
ssl - The SSL URL property value.

nextToken

private void nextToken()
            throws SQLException
Read the next TDS token from the response stream.

putLoginString

private void putLoginString(String txt,
                            int len)
            throws IOException
Write a TDS login packet string. Text followed by padding followed by a byte sized length.

readPreLoginPacket

private int readPreLoginPacket()
            throws IOException
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:

    0 = Certificate installed encrypt login packet only.
  1. 1 = Certificate installed client requests force encryption.
  2. 2 = No certificate no encryption possible.
  3. 3 = Server requests force encryption.
Returns:
The server side SSL mode.

send42LoginPkt

private void send42LoginPkt(String serverName,
                            String user,
                            String password,
                            String charset,
                            String appName,
                            String progName,
                            String wsid,
                            String language,
                            int packetSize)
            throws IOException
TDS 4.2 Login Packet.
Parameters:
serverName - server host name
user - user name
password - user password
charset - required server character set
appName - application name
progName - program name
wsid - workstation ID
language - server language for messages
packetSize - required network packet size

send50LoginPkt

private void send50LoginPkt(String serverName,
                            String user,
                            String password,
                            String charset,
                            String appName,
                            String progName,
                            String wsid,
                            String language,
                            int packetSize)
            throws IOException
TDS 5.0 Login Packet.

Parameters:
serverName - server host name
user - user name
password - user password
charset - required server character set
appName - application name
progName - library name
wsid - workstation ID
language - server language for messages
packetSize - required network packet size

sendMSLoginPkt

private void sendMSLoginPkt(String serverName,
                            String database,
                            String user,
                            String password,
                            String domain,
                            String appName,
                            String progName,
                            String wsid,
                            String language,
                            String macAddress,
                            int netPacketSize)
            throws IOException,
                   SQLException
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 ntlmauth.dll is on the path.

Parameters:
serverName - server host name
database - required database
user - user name
password - user password
domain - Windows NT domain (or null)
appName - application name
progName - program name
wsid - workstation ID
language - server language for messages
macAddress - client network MAC address
netPacketSize - TDS packet size to use

sendNtlmChallengeResponse

private void sendNtlmChallengeResponse(byte[] nonce,
                                       String user,
                                       String password,
                                       String domain)
            throws java.io.IOException
Send the response to the NTLM authentication challenge.
Parameters:
nonce - The secret to hash with password.
user - The user name.
password - The user password.
domain - The Windows NT Dommain.

sendPreLoginPacket

private void sendPreLoginPacket(String instance,
                                boolean forceEncryption)
            throws IOException
Send the SQL Server 2000 pre login packet.

Packet contains; netlib version, ssl mode, instance and process ID.

Parameters:
instance -
forceEncryption -

setColumns

(package private)  void setColumns(ColInfo[] columns)
Sets the column meta data.
Parameters:
columns - the column descriptor array

setRowCountAndTextSize

private void setRowCountAndTextSize(int rowCount,
                                    int textSize)
            throws SQLException
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).
Parameters:
rowCount - the number of rows to return or 0 for no limit or -1 to leave as is
textSize - the maximum number of bytes in a TEXT column to return or -1 to leave as is

startBatch

(package private)  void startBatch()

submitSQL

(package private)  void submitSQL(String sql)
            throws SQLException
Submit a simple SQL statement to the server and process all output.
Parameters:
sql - the statement to execute

sybasePrepare

(package private)  String sybasePrepare(String sql,
                                        ParamInfo[] params)
            throws SQLException
Creates a light weight stored procedure on a Sybase server.
Parameters:
sql - SQL statement to prepare
params - the actual parameter list
Returns:
name of the procedure

sybaseUnPrepare

(package private)  void sybaseUnPrepare(String procName)
            throws SQLException
Drops a Sybase temporary stored procedure.
Parameters:
procName - the temporary procedure name

tds4ColFormatToken

private void tds4ColFormatToken()
            throws IOException,
                   ProtocolException
Process a TDS 4.2 column format token.

tds4ColNamesToken

private void tds4ColNamesToken()
            throws IOException
Process a TDS 4.2 column names token.

Note: Will be followed by a COL_FMT token.


tds5DynamicToken

private void tds5DynamicToken()
            throws IOException
Process TDS5 dynamic SQL aknowledgements.

tds5ErrorToken

private void tds5ErrorToken()
            throws IOException
Process a TDS 5 error or informational message.

tds5ParamFmt2Token

private void tds5ParamFmt2Token()
            throws IOException,
                   ProtocolException
Process TDS 5 Sybase 12+ Dynamic results parameter descriptor.

When returning output parameters this token will be followed by a TDS5_PARAMS_TOKEN with the actual data.


tds5ParamFmtToken

private void tds5ParamFmtToken()
            throws IOException,
                   ProtocolException
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.


tds5ParamsToken

private void tds5ParamsToken()
            throws IOException,
                   ProtocolException,
                   SQLException
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.

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.


tds5ResultToken

private void tds5ResultToken()
            throws IOException,
                   ProtocolException
Process a TDS 5.0 result set packet.

tds5WideResultToken

private void tds5WideResultToken()
            throws IOException,
                   ProtocolException
Process Sybase 12+ wide result token which provides enhanced column meta data.

tds7CryptPass

private static String tds7CryptPass(String pw)
A very poor man's "encryption".
Parameters:
pw - password to encrypt
Returns:
encrypted password

tds7ResultToken

private void tds7ResultToken()
            throws IOException,
                   ProtocolException,
                   SQLException
Process a TDS 7.0 result set token.

tdsCapabilityToken

private void tdsCapabilityToken()
            throws IOException,
                   ProtocolException
Processes a TDS 5.0 capability token.

Sent after login to describe the server's capabilities.


tdsColumnInfoToken

private void tdsColumnInfoToken()
            throws IOException,
                   ProtocolException
Process a column infomation token.

Sent by select for browse or cursor functions.


tdsControlToken

private void tdsControlToken()
            throws IOException
Process a control token (function unknown).

tdsDoneToken

private void tdsDoneToken()
            throws IOException
Process a DONE, DONEINPROC or DONEPROC token.

tdsEnvChangeToken

private void tdsEnvChangeToken()
            throws IOException,
                   SQLException
Process an environment change packet.

tdsErrorToken

private void tdsErrorToken()
            throws IOException
Process a TD4/TDS7 error or informational message.

tdsInvalidToken

private void tdsInvalidToken()
            throws IOException,
                   ProtocolException
Report unsupported TDS token in input stream.

tdsLoginAckToken

private void tdsLoginAckToken()
            throws IOException
Process a login acknowledgement packet.

tdsNtlmAuthToken

private void tdsNtlmAuthToken()
            throws IOException,
                   ProtocolException
Process a NTLM Authentication challenge.

tdsOffsetsToken

private void tdsOffsetsToken()
            throws IOException
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 "set offsets from on".


tdsOrderByToken

private void tdsOrderByToken()
            throws IOException
Process an order by token.

Sent to describe columns in an order by clause.


tdsOutputParamToken

private void tdsOutputParamToken()
            throws IOException,
                   ProtocolException,
                   SQLException
Process output parameters. Normally the output parameters are preceded by a TDS type 79 (procedure return value) record; however there are at least two situations with TDS version 8 where this is not the case:
  1. For the return value of a SQL 2000+ user defined function.
  2. For a remote procedure call (server.database.user.procname) where the 79 record is only sent if a result set is also returned by the remote procedure. In this case the 79 record just acts as marker for the start of the output parameters. The actual return value is in an output param 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.

tdsProcIdToken

private void tdsProcIdToken()
            throws IOException
Process procedure ID token.

Used by DBLIB to obtain the object id of a stored procedure.


tdsReturnStatusToken

private void tdsReturnStatusToken()
            throws IOException,
                   SQLException
Process stored procedure return status token.

tdsRowToken

private void tdsRowToken()
            throws IOException,
                   ProtocolException
Process a row data token.

tdsTableNameToken

private void tdsTableNameToken()
            throws IOException,
                   ProtocolException
Process a table name token.

Sent by select for browse or cursor functions.


wait

private void wait(int timeOut)
            throws IOException,
                   SQLException
Waits for the first byte of the server response.
Parameters:
timeOut - the timeout period in seconds or 0

Generated on September 18 2009