Class TdsCore
Implementation notes:
- This class, together with TdsData, encapsulates all of the TDS specific logic required by the driver.
- This is a ground up reimplementation of the TDS protocol and is rather simpler, and hopefully easier to understand, than the original.
- 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.
- 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.
- 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.
- 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.
- Author:
- Mike Hutchinson, Matt Brinkley, Alin Sinpalean, Holger Rehn, FreeTDS project
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static class
Inner static class used to hold table meta data.private static class
Inner static class used to hold information about TDS tokens read. -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate boolean
flag set totrue
whenever a TDS_ERROR token is receivedprivate GSSContext
private static final byte
TDS 7.0 Computed Result set column meta data token.private static final int
Cancel has been generated byStatement.cancel()
.static final byte
TDS Cancel packet.private final int[]
Synchronization monitor forcancelPending
.private boolean
Indicates pending cancel that needs to be cleared.private ColInfo[]
The array of column meta data objects for this result set.private ColInfo[]
The array of column meta data objects for the computed columns of this result set.private Object[]
The array of computed column data objects in the current row.private final JtdsConnection
The Connection object that created this object.private Semaphore
Mutual exclusion lock on connection.private final TdsCore.TdsToken
The descriptor object for the current TDS token.static final int
Default minimum network packet size for TDS 7.0 and newer.(package private) static final byte
Done: Cancel acknowledgment.private static final byte
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: command caused an error.private static final byte
Done: more results are expected.private static final byte
Done: There is a valid row count.private static final ParamInfo[]
Used to optimize thegetParameters()
callprivate boolean
True if the server response is fully read.private boolean
True if the current result set is at end of file.static final int
Prepare SQL using sp_executesqlprivate boolean
Indicates that a fatal error has occurred and the connection will close.private static String
Name of the client host (it can take quite a while to find it out if DNS is configured incorrectly).private final ResponseStream
The input server response stream.private boolean
Indicates processing a batch.private boolean
Indicates that this object is closed.static final byte
TDS 4.2 or 5.0 Login packet.static final int
Maximum network packet size.private final SQLDiagnostic
The head of the diagnostic messages chain.static final int
Minimum network packet size.static final byte
TDS MSDTC packet.static final byte
TDS 7.0 Login packet.private int
The index of the next output parameter to populate.(package private) byte[]
The nonce from an NTLM challenge packet.static final byte
TDS 7.0 NTLM Authentication packet.private boolean
Flag that indicates if logon() should try to use Windows Single Sign On using SSPI or Kerberos SSO via Java native GSSAPI.(package private) byte[]
NTLM authentication message.(package private) byte[]
target info for NTLM messageprivate final RequestStream
The output server request stream.private ParamInfo[]
The array of parameter meta data objects for the current procedure call.static final int
The size of the packet header.static final byte
SQL 2000 prelogin negotiation packet.static final int
Prepare SQL using sp_prepare and sp_executestatic final byte
TDS 4.2 or 7.0 Query packet.static final byte
TDS Reply packet.private ParamInfo
The return parameter meta data object for the current procedure call.private Integer
The stored procedure return status.private Object[]
The array of column data objects in the current row.static final byte
TDS Remote Procedure Call.private final int
The make of SQL Server (Sybase/Microsoft).private final SharedSocket
The Shared network socket object.static final int
SSL Mode - Client requested force encryption.static final int
SSL Mode - Login packet must be encrypted.static final int
SSL Mode - No server certificate installed.static final int
SSL Mode - Server requested force encryption.private int
Indicates type of SSL connection.private static SSPIJNIClient
A reference to ntlm.SSPIJNIClient.(package private) static final int
Sybase 15+ bigint.(package private) static final int
Sybase nullable bit type.(package private) static final int
Sybase date and time data types.(package private) static final int
Sybase extended column meta data.(package private) static final int
Sybase char and binary > 255.(package private) static final int
Sybase univarchar etc.(package private) static final int
Sybase 15+ unitext.static final byte
TDS 5.0 Query packet.private TdsCore.TableMetaData[]
The array of table names associated with this result.private static final byte
TDS Computed result set data row token.private static final byte
TDS 7.0 NTLM authentication challenge token.private static final byte
TDS 5.0 capabilities token.private static final byte
TDS 5.0 Close token.private static final byte
TDS 4.2 Column meta data token.private static final byte
TDS Cursor results column infomation token.private static final byte
TDS 4.2 Column names token.private static final byte
TDS Computed result set names token.private static final byte
TDS Computed result set token.private static final byte
TDS control token.private static final byte
TDS 5.0 RPC token.private static final byte
TDS done token.private static final byte
TDS done in procedure token.private static final byte
TDS done procedure token.private static final byte
Environment change: charset changed.private static final byte
Environment change: database changed.private static final byte
Environment change: language changed.private static final byte
Environment change: locale changed.private static final byte
Environment change: network packet size changed.private static final byte
Environment change: TDS 8 collation changed.private static final byte
TDS environment change token.private static final byte
TDS error result token.private static final byte
TDS Information message token.private static final byte
TDS 5.0 Language token.private static final byte
TDS Login acknowledgement token.private static final byte
TDS 5.0 message token.private static final byte
TDS DBLIB Offsets token.private static final byte
TDS Order by columns token.private static final byte
TDS Output parameter value token.private static final byte
TDS Procedure ID token.private static final byte
TDS 5.0 Result set column meta data token.private static final byte
TDS Procedure call return status token.private static final byte
TDS Result set data row token.private static final byte
TDS Table name token.private static final byte
TDS 5.0 Dynamic SQL token.private static final byte
TDS 5.0 parameter descriptor token.private static final byte
TDS 5.0 Parameter format token.private static final byte
TDS 5.0 parameter value token.private static final byte
TSD 5.0 Wide result set token.private static final byte
TDS 7.0 Result set column meta data token.private static HashMap
Map of system stored procedures that have shortcuts in TDS8.private int
The TDS version being supported by this connection.static final int
Prepare SQL using temporary stored proceduresprivate static final int
Cancel has been generated by a query timeout.static final int
Do not prepare SQL -
Constructor Summary
ConstructorsConstructorDescriptionTdsCore
(JtdsConnection connection, SQLDiagnostic messages) Construct a TdsCore object. -
Method Summary
Modifier and TypeMethodDescription(package private) void
cancel
(boolean timeout) Send (only) one cancel packet to the server.private void
Check that the connection is still open.void
cleanUp()
Releases parameter and result set data and metadata to free up memory.(package private) void
Empty the server response queue.(package private) void
close()
Close theTdsCore
connection object and associated streams.(package private) void
Inform the server that this connection is closing.(package private) void
Consume packets from the server response queue up to (and including) the first response terminator.private byte[]
Initializes the GSS context and creates the initial token.(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[]
Retrieve the current result set column descriptors.(package private) ColInfo[]
Retrieve the current computed result set column descriptors, if any.(package private) Object[]
Retrieve and clear the current computed result set data items, if any.private static String
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.Returns the diagnostic chain for this instance.(package private) boolean
Get the next result set or update count from the TDS stream.(package private) boolean
Retrieve the next data row from the result set.(package private) ParamInfo[]
Retrieve the parameter meta data from a Sybase prepare.(package private) Integer
Retrieve the return status for the current stored procedure.(package private) Object[]
Retrieve the current result set data items.private static int
getShortFromBuffer
(byte[] buf, int offset) (package private) int
Retrieve the TDS protocol version.(package private) int
Retrieve the update count from the current TDS token.(package private) boolean
Retrieve the status of result set.(package private) boolean
Retrieve the status of the response stream.static boolean
isPreparedProcedureName
(String procName) Returnstrue
if the specifiedprocName
is a sp_prepare or sp_prepexec handle; returnsfalse
otherwise.(package private) boolean
Retrieve the status of the next result item.(package private) boolean
Retrieve the status of the next result item.(package private) boolean
Retrieve the status of the next result item.(package private) static boolean
Checks whether theos.name
system property contains "windows".(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
Read the next TDS token from the response stream.private void
putLoginString
(String txt, int len) Write a TDS login packet string.private int
Process the pre login acknowledgment 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
Send the next GSS authentication token.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
(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
Notifies theTdsCore
that a batch is starting.(package private) void
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
Process a TDS 4.2 column format token.private void
Process a TDS 4.2 column names token.private void
Process TDS5 dynamic SQL aknowledgements.private void
Process a TDS 5 error or informational message.private void
Process TDS 5 Sybase 12+ Dynamic results parameter descriptor.private void
Process TDS 5 Dynamic results parameter descriptors.private void
Process TDS 5.0 Params Token.private void
Process a TDS 5.0 result set packet.private void
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
Process a TDS 7.0 result set token.private void
Processes a TDS 5.0 capability token.private void
Process a column infomation token.private void
Process meta data for the computed result set complementing the current result set.private void
Process computed row data.private void
Process a control token (function unknown).private void
Process a DONE, DONEINPROC or DONEPROC token.private void
Process an environment change packet.private void
Process a TD4/TDS7 error or informational message.private void
Receive a GSS token.private void
Report unsupported TDS token in input stream.private void
Process a login acknowledgement packet.private void
Process a NTLM Authentication challenge.private void
Process offsets token.private void
Process an order by token.private void
Process output parameters.private void
Process procedure ID token.private void
Process stored procedure return status token.private void
Process a row data token.private void
Process a table name token.private void
wait
(int timeOut) Waits for the first byte of the server response.
-
Field Details
-
MIN_PKT_SIZE
public static final int MIN_PKT_SIZEMinimum network packet size.- See Also:
-
DEFAULT_MIN_PKT_SIZE_TDS70
public static final int DEFAULT_MIN_PKT_SIZE_TDS70Default minimum network packet size for TDS 7.0 and newer.- See Also:
-
MAX_PKT_SIZE
public static final int MAX_PKT_SIZEMaximum network packet size.- See Also:
-
PKT_HDR_LEN
public static final int PKT_HDR_LENThe size of the packet header.- See Also:
-
QUERY_PKT
public static final byte QUERY_PKTTDS 4.2 or 7.0 Query packet.- See Also:
-
LOGIN_PKT
public static final byte LOGIN_PKTTDS 4.2 or 5.0 Login packet.- See Also:
-
RPC_PKT
public static final byte RPC_PKTTDS Remote Procedure Call.- See Also:
-
REPLY_PKT
public static final byte REPLY_PKTTDS Reply packet.- See Also:
-
CANCEL_PKT
public static final byte CANCEL_PKTTDS Cancel packet.- See Also:
-
MSDTC_PKT
public static final byte MSDTC_PKTTDS MSDTC packet.- See Also:
-
SYBQUERY_PKT
public static final byte SYBQUERY_PKTTDS 5.0 Query packet.- See Also:
-
MSLOGIN_PKT
public static final byte MSLOGIN_PKTTDS 7.0 Login packet.- See Also:
-
NTLMAUTH_PKT
public static final byte NTLMAUTH_PKTTDS 7.0 NTLM Authentication packet.- See Also:
-
PRELOGIN_PKT
public static final byte PRELOGIN_PKTSQL 2000 prelogin negotiation packet.- See Also:
-
SSL_ENCRYPT_LOGIN
public static final int SSL_ENCRYPT_LOGINSSL Mode - Login packet must be encrypted.- See Also:
-
SSL_CLIENT_FORCE_ENCRYPT
public static final int SSL_CLIENT_FORCE_ENCRYPTSSL Mode - Client requested force encryption.- See Also:
-
SSL_NO_ENCRYPT
public static final int SSL_NO_ENCRYPTSSL Mode - No server certificate installed.- See Also:
-
SSL_SERVER_FORCE_ENCRYPT
public static final int SSL_SERVER_FORCE_ENCRYPTSSL Mode - Server requested force encryption.- See Also:
-
TDS5_PARAMFMT2_TOKEN
private static final byte TDS5_PARAMFMT2_TOKENTDS 5.0 Parameter format token.- See Also:
-
TDS_LANG_TOKEN
private static final byte TDS_LANG_TOKENTDS 5.0 Language token.- See Also:
-
TDS5_WIDE_RESULT
private static final byte TDS5_WIDE_RESULTTSD 5.0 Wide result set token.- See Also:
-
TDS_CLOSE_TOKEN
private static final byte TDS_CLOSE_TOKENTDS 5.0 Close token.- See Also:
-
TDS_OFFSETS_TOKEN
private static final byte TDS_OFFSETS_TOKENTDS DBLIB Offsets token.- See Also:
-
TDS_RETURNSTATUS_TOKEN
private static final byte TDS_RETURNSTATUS_TOKENTDS Procedure call return status token.- See Also:
-
TDS_PROCID
private static final byte TDS_PROCIDTDS Procedure ID token.- See Also:
-
TDS7_RESULT_TOKEN
private static final byte TDS7_RESULT_TOKENTDS 7.0 Result set column meta data token.- See Also:
-
ALTMETADATA_TOKEN
private static final byte ALTMETADATA_TOKENTDS 7.0 Computed Result set column meta data token.- See Also:
-
TDS_COLNAME_TOKEN
private static final byte TDS_COLNAME_TOKENTDS 4.2 Column names token.- See Also:
-
TDS_COLFMT_TOKEN
private static final byte TDS_COLFMT_TOKENTDS 4.2 Column meta data token.- See Also:
-
TDS_TABNAME_TOKEN
private static final byte TDS_TABNAME_TOKENTDS Table name token.- See Also:
-
TDS_COLINFO_TOKEN
private static final byte TDS_COLINFO_TOKENTDS Cursor results column infomation token.- See Also:
-
TDS_COMP_NAMES_TOKEN
private static final byte TDS_COMP_NAMES_TOKENTDS Computed result set names token.- See Also:
-
TDS_COMP_RESULT_TOKEN
private static final byte TDS_COMP_RESULT_TOKENTDS Computed result set token.- See Also:
-
TDS_ORDER_TOKEN
private static final byte TDS_ORDER_TOKENTDS Order by columns token.- See Also:
-
TDS_ERROR_TOKEN
private static final byte TDS_ERROR_TOKENTDS error result token.- See Also:
-
TDS_INFO_TOKEN
private static final byte TDS_INFO_TOKENTDS Information message token.- See Also:
-
TDS_PARAM_TOKEN
private static final byte TDS_PARAM_TOKENTDS Output parameter value token.- See Also:
-
TDS_LOGINACK_TOKEN
private static final byte TDS_LOGINACK_TOKENTDS Login acknowledgement token.- See Also:
-
TDS_CONTROL_TOKEN
private static final byte TDS_CONTROL_TOKENTDS control token.- See Also:
-
TDS_ROW_TOKEN
private static final byte TDS_ROW_TOKENTDS Result set data row token.- See Also:
-
TDS_ALTROW
private static final byte TDS_ALTROWTDS Computed result set data row token.- See Also:
-
TDS5_PARAMS_TOKEN
private static final byte TDS5_PARAMS_TOKENTDS 5.0 parameter value token.- See Also:
-
TDS_CAP_TOKEN
private static final byte TDS_CAP_TOKENTDS 5.0 capabilities token.- See Also:
-
TDS_ENVCHANGE_TOKEN
private static final byte TDS_ENVCHANGE_TOKENTDS environment change token.- See Also:
-
TDS_MSG50_TOKEN
private static final byte TDS_MSG50_TOKENTDS 5.0 message token.- See Also:
-
TDS_DBRPC_TOKEN
private static final byte TDS_DBRPC_TOKENTDS 5.0 RPC token.- See Also:
-
TDS5_DYNAMIC_TOKEN
private static final byte TDS5_DYNAMIC_TOKENTDS 5.0 Dynamic SQL token.- See Also:
-
TDS5_PARAMFMT_TOKEN
private static final byte TDS5_PARAMFMT_TOKENTDS 5.0 parameter descriptor token.- See Also:
-
TDS_AUTH_TOKEN
private static final byte TDS_AUTH_TOKENTDS 7.0 NTLM authentication challenge token.- See Also:
-
TDS_RESULT_TOKEN
private static final byte TDS_RESULT_TOKENTDS 5.0 Result set column meta data token.- See Also:
-
TDS_DONE_TOKEN
private static final byte TDS_DONE_TOKENTDS done token.- See Also:
-
TDS_DONEPROC_TOKEN
private static final byte TDS_DONEPROC_TOKENTDS done procedure token.- See Also:
-
TDS_DONEINPROC_TOKEN
private static final byte TDS_DONEINPROC_TOKENTDS done in procedure token.- See Also:
-
TDS_ENV_DATABASE
private static final byte TDS_ENV_DATABASEEnvironment change: database changed.- See Also:
-
TDS_ENV_LANG
private static final byte TDS_ENV_LANGEnvironment change: language changed.- See Also:
-
TDS_ENV_CHARSET
private static final byte TDS_ENV_CHARSETEnvironment change: charset changed.- See Also:
-
TDS_ENV_PACKSIZE
private static final byte TDS_ENV_PACKSIZEEnvironment change: network packet size changed.- See Also:
-
TDS_ENV_LCID
private static final byte TDS_ENV_LCIDEnvironment change: locale changed.- See Also:
-
TDS_ENV_SQLCOLLATION
private static final byte TDS_ENV_SQLCOLLATIONEnvironment change: TDS 8 collation changed.- See Also:
-
EMPTY_PARAMETER_INFO
Used to optimize thegetParameters()
call -
DONE_MORE_RESULTS
private static final byte DONE_MORE_RESULTSDone: more results are expected.- See Also:
-
DONE_ERROR
private static final byte DONE_ERRORDone: command caused an error.- See Also:
-
DONE_ROW_COUNT
private static final byte DONE_ROW_COUNTDone: There is a valid row count.- See Also:
-
DONE_CANCEL
static final byte DONE_CANCELDone: Cancel acknowledgment.- See Also:
-
DONE_END_OF_RESPONSE
private static final byte DONE_END_OF_RESPONSEDone: Response terminator (if more than one request packet is sent, each response is terminated by a DONE packet with this flag set).- See Also:
-
UNPREPARED
public static final int UNPREPAREDDo not prepare SQL- See Also:
-
TEMPORARY_STORED_PROCEDURES
public static final int TEMPORARY_STORED_PROCEDURESPrepare SQL using temporary stored procedures- See Also:
-
EXECUTE_SQL
public static final int EXECUTE_SQLPrepare SQL using sp_executesql- See Also:
-
PREPARE
public static final int PREPAREPrepare SQL using sp_prepare and sp_execute- See Also:
-
SYB_LONGDATA
static final int SYB_LONGDATASybase char and binary > 255.- See Also:
-
SYB_DATETIME
static final int SYB_DATETIMESybase date and time data types.- See Also:
-
SYB_BITNULL
static final int SYB_BITNULLSybase nullable bit type.- See Also:
-
SYB_EXTCOLINFO
static final int SYB_EXTCOLINFOSybase extended column meta data.- See Also:
-
SYB_UNICODE
static final int SYB_UNICODESybase univarchar etc.- See Also:
-
SYB_UNITEXT
static final int SYB_UNITEXTSybase 15+ unitext.- See Also:
-
SYB_BIGINT
static final int SYB_BIGINTSybase 15+ bigint.- See Also:
-
ASYNC_CANCEL
private static final int ASYNC_CANCELCancel has been generated byStatement.cancel()
.- See Also:
-
TIMEOUT_CANCEL
private static final int TIMEOUT_CANCELCancel has been generated by a query timeout.- See Also:
-
tds8SpNames
Map of system stored procedures that have shortcuts in TDS8. -
hostName
Name of the client host (it can take quite a while to find it out if DNS is configured incorrectly). -
sspiJNIClient
A reference to ntlm.SSPIJNIClient. -
connection
The Connection object that created this object. -
tdsVersion
private int tdsVersionThe TDS version being supported by this connection. -
serverType
private final int serverTypeThe make of SQL Server (Sybase/Microsoft). -
socket
The Shared network socket object. -
out
The output server request stream. -
in
The input server response stream. -
endOfResponse
private boolean endOfResponseTrue if the server response is fully read. -
endOfResults
private boolean endOfResultsTrue if the current result set is at end of file. -
columns
The array of column meta data objects for this result set. -
computedColumns
The array of column meta data objects for the computed columns of this result set. -
rowData
The array of column data objects in the current row. -
computedRowData
The array of computed column data objects in the current row. -
tables
The array of table names associated with this result. -
currentToken
The descriptor object for the current TDS token. -
returnStatus
The stored procedure return status. -
returnParam
The return parameter meta data object for the current procedure call. -
parameters
The array of parameter meta data objects for the current procedure call. -
nextParam
private int nextParamThe index of the next output parameter to populate. -
messages
The head of the diagnostic messages chain. -
isClosed
private boolean isClosedIndicates that this object is closed. -
ntlmAuthSSO
private boolean ntlmAuthSSOFlag that indicates if logon() should try to use Windows Single Sign On using SSPI or Kerberos SSO via Java native GSSAPI. -
fatalError
private boolean fatalErrorIndicates that a fatal error has occurred and the connection will close. -
connectionLock
Mutual exclusion lock on connection. -
inBatch
private boolean inBatchIndicates processing a batch. -
sslMode
private int sslModeIndicates type of SSL connection. -
cancelPending
private boolean cancelPendingIndicates pending cancel that needs to be cleared. -
cancelMonitor
private final int[] cancelMonitorSynchronization monitor forcancelPending
. -
_ErrorReceived
private boolean _ErrorReceivedflag set totrue
whenever a TDS_ERROR token is received -
nonce
byte[] nonceThe nonce from an NTLM challenge packet. -
ntlmMessage
byte[] ntlmMessageNTLM authentication message. -
ntlmTarget
byte[] ntlmTargettarget info for NTLM message -
_gssContext
-
-
Constructor Details
-
TdsCore
TdsCore(JtdsConnection connection, SQLDiagnostic messages) Construct a TdsCore object.- Parameters:
connection
- The connection which owns this object.messages
- The SQLDiagnostic messages chain.
-
-
Method Details
-
checkOpen
Check that the connection is still open.- Throws:
SQLException
- if the connection is closed
-
getTdsVersion
int getTdsVersion()Retrieve the TDS protocol version.- Returns:
- The protocol version as an
int
.
-
getColumns
ColInfo[] getColumns()Retrieve the current result set column descriptors.- Returns:
- The column descriptors as a
ColInfo[]
.
-
setColumns
Sets the column meta data.- Parameters:
columns
- the column descriptor array
-
getParameters
ParamInfo[] getParameters()Retrieve the parameter meta data from a Sybase prepare.- Returns:
- The parameter descriptors as a
ParamInfo[]
.
-
getRowData
Object[] getRowData()Retrieve the current result set data items.- Returns:
- the row data as an
Object
array
-
negotiateSSL
Negotiate SSL settings with SQL 2000+ server. Server returns the following values for SSL mode:- 1 = Certificate installed client requests force encryption.
- 2 = No certificate no encryption possible.
- 3 = Server requests force encryption.
0 = Certificate installed encrypt login packet only. - Parameters:
instance
- The server instance name.ssl
- The SSL URL property value.- Throws:
IOException
SQLException
-
login
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 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- Throws:
SQLException
- if an error occurs
-
getMoreResults
Get the next result set or update count from the TDS stream.- Returns:
true
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
-
isResultSet
boolean isResultSet()Retrieve the status of the next result item.- Returns:
boolean
true if the next item is a result set.
-
isRowData
boolean isRowData()Retrieve the status of the next result item.- Returns:
boolean
true if the next item is row data.
-
isUpdateCount
boolean isUpdateCount()Retrieve the status of the next result item.- Returns:
boolean
true if the next item is an update count.
-
getUpdateCount
int getUpdateCount()Retrieve the update count from the current TDS token.- Returns:
- The update count as an
int
.
-
isEndOfResponse
boolean isEndOfResponse()Retrieve the status of the response stream.- Returns:
boolean
true if the response has been entirely consumed
-
clearResponseQueue
Empty the server response queue.- Throws:
SQLException
- if an error occurs
-
consumeOneResponse
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
-
getNextRow
Retrieve the next data row from the result set.- Returns:
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
-
isDataInResultSet
Retrieve the status of result set.
This does a quick read ahead and is needed to support method
JtdsResultSet.isLast()
.- Returns:
true
if there is more data in the result set- Throws:
SQLException
-
getReturnStatus
Integer getReturnStatus()Retrieve the return status for the current stored procedure.- Returns:
- The return status as an
Integer
.
-
closeConnection
void closeConnection()Inform the server that this connection is closing.Used by Sybase a no-op for Microsoft.
-
close
Close theTdsCore
connection object and associated streams.- Throws:
SQLException
-
cancel
void cancel(boolean timeout) Send (only) one cancel packet to the server.- Parameters:
timeout
- true if this is a query timeout cancel
-
submitSQL
Submit a simple SQL statement to the server and process all output.- Parameters:
sql
- the statement to execute- Throws:
SQLException
- if an error is returned by the server
-
startBatch
void startBatch()Notifies theTdsCore
that a batch is starting. This is so that it knows to usesp_executesql
for parameterized queries (because there's no way to prepare a statement in the middle of a batch).Sets the
inBatch
flag. -
executeSQL
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 executeprocName
- stored procedure to execute ornull
parameters
- 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- Throws:
SQLException
- if an error occurs
-
microsoftPrepare
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 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- Returns:
- name of the procedure or prepared statement handle.
- Throws:
SQLException
-
sybasePrepare
Creates a light weight stored procedure on a Sybase server.- Parameters:
sql
- SQL statement to prepareparams
- the actual parameter list- Returns:
- name of the procedure
- Throws:
SQLException
- if an error occurs
-
sybaseUnPrepare
Drops a Sybase temporary stored procedure.- Parameters:
procName
- the temporary procedure name- Throws:
SQLException
- if an error occurs
-
enlistConnection
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 connectionoleTranID
- the 40 OLE transaction ID- Returns:
- a
byte[]
array containing the TM address data - Throws:
SQLException
-
getBatchCounts
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 thatSQLException
s are chained because there could be several errors reported in a batch.- Parameters:
counts
- theArrayList
containing the update countssqlEx
- any previousSQLException
(s) encountered- Returns:
- updated
SQLException
ornull
if no error has yet occurred - Throws:
SQLException
- if the connection is closed
-
getComputedColumns
ColInfo[] getComputedColumns()Retrieve the current computed result set column descriptors, if any.
- Returns:
- column descriptors for the computed columns as
ColInfo
array; ornull
if there are no computed columns
-
getComputedRowData
Object[] getComputedRowData()Retrieve and clear the current computed result set data items, if any.
- Returns:
- the row data for the computed columns as an
Object
array; ornull
if there are no computed columns, computed data has not yet been received, or the data has already been cleared by a previous call to this method
-
putLoginString
Write a TDS login packet string. Text followed by padding followed by a byte sized length.- Throws:
IOException
-
sendPreLoginPacket
Send the SQL Server 2000 pre login packet.Packet contains; netlib version, ssl mode, instance and process ID.
- Parameters:
instance
-forceEncryption
-- Throws:
IOException
-
readPreLoginPacket
Process the pre login acknowledgment from the server.Packet contains; server version no, SSL mode, instance name and process id.
Server returns the following values for SSL mode:
- 1 = Certificate installed client requests force encryption.
- 2 = No certificate no encryption possible.
- 3 = Server requests force encryption.
0 = Certificate installed encrypt login packet only. - Returns:
- The server side SSL mode.
- Throws:
IOException
-
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 nameuser
- user namepassword
- user passwordcharset
- required server character setappName
- application nameprogName
- program namewsid
- workstation IDlanguage
- server language for messagespacketSize
- required network packet size- Throws:
IOException
- if an I/O error occurs
-
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 nameuser
- user namepassword
- user passwordcharset
- required server character setappName
- application nameprogName
- library namewsid
- workstation IDlanguage
- server language for messagespacketSize
- required network packet size- Throws:
IOException
- if an I/O error occurs
-
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 namedatabase
- required databaseuser
- user namepassword
- user passworddomain
- Windows NT domain (ornull
)appName
- application nameprogName
- program namewsid
- workstation IDlanguage
- server language for messagesmacAddress
- client network MAC addressnetPacketSize
- TDS packet size to use- Throws:
IOException
- if an I/O error occursSQLException
-
tdsGssToken
Receive a GSS token.- Throws:
IOException
-
sendGssToken
Send the next GSS authentication token.- Throws:
IOException
-
sendNtlmChallengeResponse
private void sendNtlmChallengeResponse(String user, String password, String domain) throws 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.- Throws:
IOException
-
nextToken
Read the next TDS token from the response stream.- Throws:
SQLException
- if an I/O or protocol error occurs
-
tdsInvalidToken
Report unsupported TDS token in input stream.- Throws:
IOException
ProtocolException
-
tds5ParamFmt2Token
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.
- Throws:
IOException
ProtocolException
-
tds5WideResultToken
Process Sybase 12+ wide result token which provides enhanced column meta data.- Throws:
IOException
ProtocolException
-
tdsReturnStatusToken
Process stored procedure return status token.- Throws:
IOException
SQLException
-
tdsProcIdToken
Process procedure ID token.Used by DBLIB to obtain the object id of a stored procedure.
- Throws:
IOException
-
tdsOffsetsToken
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"
.- Throws:
IOException
-
tds7ResultToken
Process a TDS 7.0 result set token.- Throws:
IOException
ProtocolException
SQLException
-
tds4ColNamesToken
Process a TDS 4.2 column names token.Note: Will be followed by a COL_FMT token.
- Throws:
IOException
-
tds4ColFormatToken
Process a TDS 4.2 column format token.- Throws:
IOException
ProtocolException
-
tdsTableNameToken
Process a table name token.Sent by select for browse or cursor functions.
- Throws:
IOException
ProtocolException
-
tdsColumnInfoToken
Process a column infomation token.Sent by select for browse or cursor functions.
- Throws:
IOException
ProtocolException
-
tdsOrderByToken
Process an order by token.Sent to describe columns in an order by clause.
- Throws:
IOException
-
tdsErrorToken
Process a TD4/TDS7 error or informational message.- Throws:
IOException
-
tdsOutputParamToken
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:- For the return value of a SQL 2000+ user defined function.
- 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.
- Throws:
IOException
ProtocolException
SQLException
-
tdsLoginAckToken
Process a login acknowledgement packet.- Throws:
IOException
-
tdsControlToken
Process a control token (function unknown).- Throws:
IOException
-
tdsRowToken
Process a row data token.- Throws:
IOException
ProtocolException
-
tds5ParamsToken
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.
- Throws:
IOException
ProtocolException
SQLException
-
tdsCapabilityToken
Processes a TDS 5.0 capability token.Sent after login to describe the server's capabilities.
- Throws:
IOException
- if an I/O error occursProtocolException
-
tdsEnvChangeToken
Process an environment change packet.- Throws:
IOException
SQLException
-
tds5ErrorToken
Process a TDS 5 error or informational message.- Throws:
IOException
-
tds5DynamicToken
Process TDS5 dynamic SQL aknowledgements.- Throws:
IOException
-
tds5ParamFmtToken
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
ProtocolException
-
tdsNtlmAuthToken
Process a NTLM Authentication challenge.- Throws:
IOException
ProtocolException
-
getIntFromBuffer
private static int getIntFromBuffer(byte[] buf, int offset) -
getShortFromBuffer
private static int getShortFromBuffer(byte[] buf, int offset) -
tds5ResultToken
Process a TDS 5.0 result set packet.- Throws:
IOException
ProtocolException
-
tdsDoneToken
Process a DONE, DONEINPROC or DONEPROC token.- Throws:
IOException
-
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.- Throws:
SQLException
IOException
-
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.- Throws:
SQLException
IOException
-
isPreparedProcedureName
Returnstrue
if the specifiedprocName
is a sp_prepare or sp_prepexec handle; returnsfalse
otherwise.- Parameters:
procName
- Stored procedure to execute ornull
.- Returns:
true
if the specifiedprocName
is a sp_prepare or sp_prepexec handle;false
otherwise.
-
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 ornull
.parameters
- Parameters for call ornull
.noMetaData
- Suppress meta data for cursor calls.- Throws:
SQLException
IOException
-
setRowCountAndTextSize
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 istextSize
- 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
-
wait
Waits for the first byte of the server response.- Parameters:
timeOut
- the timeout period in seconds or 0- Throws:
IOException
SQLException
-
cleanUp
public void cleanUp()Releases parameter and result set data and metadata to free up memory. This is useful before theTdsCore
is cached for reuse. -
getMessages
Returns the diagnostic chain for this instance. -
getMACAddress
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[]
-
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
-
tds7CryptPass
A very poor man's "encryption".- Parameters:
pw
- password to encrypt- Returns:
- encrypted password
-
tdsComputedResultToken
Process meta data for the computed result set complementing the current result set.
- Throws:
IOException
ProtocolException
-
tdsComputedRowToken
Process computed row data.
- Throws:
IOException
ProtocolException
SQLException
-
isWindowsOS
static boolean isWindowsOS()Checks whether the
os.name
system property contains "windows". -
createGssToken
Initializes the GSS context and creates the initial token.- Throws:
GSSException
UnknownHostException
-