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.2.4 2009/08/10 17:38:02 ickzon Exp $
    Author:
    Mike Hutchinson, Matt Brinkley, Alin Sinpalean, FreeTDS project
    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
      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.
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      (package private) void cancel​(boolean timeout)
      Send (only) one cancel packet to the server.
      private void checkOpen()
      Check that the connection is still open.
      void cleanUp()
      Releases parameter and result set data and metadata to free up memory.
      (package private) void clearResponseQueue()
      Empty the server response queue.
      (package private) void close()
      Close the TdsCore connection object and associated streams.
      (package private) void closeConnection()
      Inform the server that this connection is closing.
      (package private) void consumeOneResponse()
      Consume packets from the server response queue up to (and including) the first response terminator.
      (package private) byte[] enlistConnection​(int type, byte[] oleTranID)
      Enlist the current connection in a distributed transaction or request the location of the MSDTC instance controlling the server we are connected to.
      (package private) void executeSQL​(java.lang.String sql, java.lang.String procName, ParamInfo[] parameters, boolean noMetaData, int timeOut, int maxRows, int maxFieldSize, boolean sendNow)
      Send an SQL statement with optional parameters to the server.
      private void executeSQL42​(java.lang.String sql, java.lang.String procName, ParamInfo[] parameters, boolean noMetaData, boolean sendNow)
      Execute SQL using TDS 4.2 protocol.
      private void executeSQL50​(java.lang.String sql, java.lang.String procName, ParamInfo[] parameters)
      Execute SQL using TDS 5.0 protocol.
      private void executeSQL70​(java.lang.String sql, java.lang.String procName, ParamInfo[] parameters, boolean noMetaData, boolean sendNow)
      Execute SQL using TDS 7.0 protocol.
      (package private) java.sql.SQLException getBatchCounts​(java.util.ArrayList counts, java.sql.SQLException sqlEx)
      Obtain the counts from a batch of SQL updates.
      (package private) ColInfo[] getColumns()
      Retrieve the current result set column descriptors.
      private static java.lang.String getHostName()
      Tries to figure out what client name we should identify ourselves as.
      private static int getIntFromBuffer​(byte[] buf, int offset)  
      private static byte[] getMACAddress​(java.lang.String macString)
      Converts a user supplied MAC address into a byte array.
      SQLDiagnostic getMessages()
      Returns the diagnostic chain for this instance.
      (package private) boolean getMoreResults()
      Get the next result set or update count from the TDS stream.
      (package private) boolean getNextRow()
      Retrieve the next data row from the result set.
      (package private) ParamInfo[] getParameters()
      Retrieve the parameter meta data from a Sybase prepare.
      (package private) java.lang.Integer getReturnStatus()
      Retrieve the return status for the current stored procedure.
      (package private) java.lang.Object[] getRowData()
      Retrieve the current result set data items.
      private static int getShortFromBuffer​(byte[] buf, int offset)  
      (package private) int getTdsVersion()
      Retrieve the TDS protocol version.
      (package private) int getUpdateCount()
      Retrieve the update count from the current TDS token.
      (package private) boolean isDataInResultSet()
      Retrieve the status of result set.
      (package private) boolean isEndOfResponse()
      Retrieve the status of the response stream.
      static boolean isPreparedProcedureName​(java.lang.String procName)
      Returns true if the specified procName is a sp_prepare or sp_prepexec handle; returns false otherwise.
      (package private) boolean isResultSet()
      Retrieve the status of the next result item.
      (package private) boolean isRowData()
      Retrieve the status of the next result item.
      (package private) boolean isUpdateCount()
      Retrieve the status of the next result item.
      (package private) void login​(java.lang.String serverName, java.lang.String database, java.lang.String user, java.lang.String password, java.lang.String domain, java.lang.String charset, java.lang.String appName, java.lang.String progName, java.lang.String wsid, java.lang.String language, java.lang.String macAddress, int packetSize)
      Login to the SQL Server.
      (package private) java.lang.String microsoftPrepare​(java.lang.String sql, ParamInfo[] params, boolean needCursor, int resultSetType, int resultSetConcurrency)
      Prepares the SQL for use with Microsoft server.
      (package private) void negotiateSSL​(java.lang.String instance, java.lang.String ssl)
      Negotiate SSL settings with SQL 2000+ server.
      private void nextToken()
      Read the next TDS token from the response stream.
      private void putLoginString​(java.lang.String txt, int len)
      Write a TDS login packet string.
      private int readPreLoginPacket()
      Process the pre login acknowledgement from the server.
      private void send42LoginPkt​(java.lang.String serverName, java.lang.String user, java.lang.String password, java.lang.String charset, java.lang.String appName, java.lang.String progName, java.lang.String wsid, java.lang.String language, int packetSize)
      TDS 4.2 Login Packet.
      private void send50LoginPkt​(java.lang.String serverName, java.lang.String user, java.lang.String password, java.lang.String charset, java.lang.String appName, java.lang.String progName, java.lang.String wsid, java.lang.String language, int packetSize)
      TDS 5.0 Login Packet.
      private void sendMSLoginPkt​(java.lang.String serverName, java.lang.String database, java.lang.String user, java.lang.String password, java.lang.String domain, java.lang.String appName, java.lang.String progName, java.lang.String wsid, java.lang.String language, java.lang.String macAddress, int netPacketSize)
      Send a TDS 7 login packet.
      private void sendNtlmChallengeResponse​(byte[] nonce, java.lang.String user, java.lang.String password, java.lang.String domain)
      Send the response to the NTLM authentication challenge.
      private void sendPreLoginPacket​(java.lang.String instance, boolean forceEncryption)
      Send the SQL Server 2000 pre login packet.
      (package private) void setColumns​(ColInfo[] columns)
      Sets the column meta data.
      private void setRowCountAndTextSize​(int rowCount, int textSize)
      Sets the server row count (to limit the number of rows in a result set) and text size (to limit the size of returned TEXT/NTEXT fields).
      (package private) void startBatch()
      Notifies the TdsCore that a batch is starting.
      (package private) void submitSQL​(java.lang.String sql)
      Submit a simple SQL statement to the server and process all output.
      (package private) java.lang.String sybasePrepare​(java.lang.String sql, ParamInfo[] params)
      Creates a light weight stored procedure on a Sybase server.
      (package private) void sybaseUnPrepare​(java.lang.String procName)
      Drops a Sybase temporary stored procedure.
      private void tds4ColFormatToken()
      Process a TDS 4.2 column format token.
      private void tds4ColNamesToken()
      Process a TDS 4.2 column names token.
      private void tds5DynamicToken()
      Process TDS5 dynamic SQL aknowledgements.
      private void tds5ErrorToken()
      Process a TDS 5 error or informational message.
      private void tds5ParamFmt2Token()
      Process TDS 5 Sybase 12+ Dynamic results parameter descriptor.
      private void tds5ParamFmtToken()
      Process TDS 5 Dynamic results parameter descriptors.
      private void tds5ParamsToken()
      Process TDS 5.0 Params Token.
      private void tds5ResultToken()
      Process a TDS 5.0 result set packet.
      private void tds5WideResultToken()
      Process Sybase 12+ wide result token which provides enhanced column meta data.
      private static java.lang.String tds7CryptPass​(java.lang.String pw)
      A very poor man's "encryption".
      private void tds7ResultToken()
      Process a TDS 7.0 result set token.
      private void tdsCapabilityToken()
      Processes a TDS 5.0 capability token.
      private void tdsColumnInfoToken()
      Process a column infomation token.
      private void tdsControlToken()
      Process a control token (function unknown).
      private void tdsDoneToken()
      Process a DONE, DONEINPROC or DONEPROC token.
      private void tdsEnvChangeToken()
      Process an environment change packet.
      private void tdsErrorToken()
      Process a TD4/TDS7 error or informational message.
      private void tdsInvalidToken()
      Report unsupported TDS token in input stream.
      private void tdsLoginAckToken()
      Process a login acknowledgement packet.
      private void tdsNtlmAuthToken()
      Process a NTLM Authentication challenge.
      private void tdsOffsetsToken()
      Process offsets token.
      private void tdsOrderByToken()
      Process an order by token.
      private void tdsOutputParamToken()
      Process output parameters.
      private void tdsProcIdToken()
      Process procedure ID token.
      private void tdsReturnStatusToken()
      Process stored procedure return status token.
      private void tdsRowToken()
      Process a row data token.
      private void tdsTableNameToken()
      Process a table name token.
      private void wait​(int timeOut)
      Waits for the first byte of the server response.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • MIN_PKT_SIZE

        public static final int MIN_PKT_SIZE
        Minimum network packet size.
        See Also:
        Constant Field Values
      • 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.
        See Also:
        Constant Field Values
      • MAX_PKT_SIZE

        public static final int MAX_PKT_SIZE
        Maximum network packet size.
        See Also:
        Constant Field Values
      • PKT_HDR_LEN

        public static final int PKT_HDR_LEN
        The size of the packet header.
        See Also:
        Constant Field Values
      • QUERY_PKT

        public static final byte QUERY_PKT
        TDS 4.2 or 7.0 Query packet.
        See Also:
        Constant Field Values
      • LOGIN_PKT

        public static final byte LOGIN_PKT
        TDS 4.2 or 5.0 Login packet.
        See Also:
        Constant Field Values
      • SYBQUERY_PKT

        public static final byte SYBQUERY_PKT
        TDS 5.0 Query packet.
        See Also:
        Constant Field Values
      • MSLOGIN_PKT

        public static final byte MSLOGIN_PKT
        TDS 7.0 Login packet.
        See Also:
        Constant Field Values
      • NTLMAUTH_PKT

        public static final byte NTLMAUTH_PKT
        TDS 7.0 NTLM Authentication packet.
        See Also:
        Constant Field Values
      • PRELOGIN_PKT

        public static final byte PRELOGIN_PKT
        SQL 2000 prelogin negotiation packet.
        See Also:
        Constant Field Values
      • SSL_ENCRYPT_LOGIN

        public static final int SSL_ENCRYPT_LOGIN
        SSL Mode - Login packet must be encrypted.
        See Also:
        Constant Field Values
      • SSL_CLIENT_FORCE_ENCRYPT

        public static final int SSL_CLIENT_FORCE_ENCRYPT
        SSL Mode - Client requested force encryption.
        See Also:
        Constant Field Values
      • SSL_NO_ENCRYPT

        public static final int SSL_NO_ENCRYPT
        SSL Mode - No server certificate installed.
        See Also:
        Constant Field Values
      • SSL_SERVER_FORCE_ENCRYPT

        public static final int SSL_SERVER_FORCE_ENCRYPT
        SSL Mode - Server requested force encryption.
        See Also:
        Constant Field Values
      • TDS5_PARAMFMT2_TOKEN

        private static final byte TDS5_PARAMFMT2_TOKEN
        TDS 5.0 Parameter format token.
        See Also:
        Constant Field Values
      • TDS_LANG_TOKEN

        private static final byte TDS_LANG_TOKEN
        TDS 5.0 Language token.
        See Also:
        Constant Field Values
      • TDS5_WIDE_RESULT

        private static final byte TDS5_WIDE_RESULT
        TSD 5.0 Wide result set token.
        See Also:
        Constant Field Values
      • TDS_CLOSE_TOKEN

        private static final byte TDS_CLOSE_TOKEN
        TDS 5.0 Close token.
        See Also:
        Constant Field Values
      • TDS_OFFSETS_TOKEN

        private static final byte TDS_OFFSETS_TOKEN
        TDS DBLIB Offsets token.
        See Also:
        Constant Field Values
      • TDS_RETURNSTATUS_TOKEN

        private static final byte TDS_RETURNSTATUS_TOKEN
        TDS Procedure call return status token.
        See Also:
        Constant Field Values
      • TDS_PROCID

        private static final byte TDS_PROCID
        TDS Procedure ID token.
        See Also:
        Constant Field Values
      • TDS7_RESULT_TOKEN

        private static final byte TDS7_RESULT_TOKEN
        TDS 7.0 Result set column meta data token.
        See Also:
        Constant Field Values
      • TDS7_COMP_RESULT_TOKEN

        private static final byte TDS7_COMP_RESULT_TOKEN
        TDS 7.0 Computed Result set column meta data token.
        See Also:
        Constant Field Values
      • TDS_COLNAME_TOKEN

        private static final byte TDS_COLNAME_TOKEN
        TDS 4.2 Column names token.
        See Also:
        Constant Field Values
      • TDS_COLFMT_TOKEN

        private static final byte TDS_COLFMT_TOKEN
        TDS 4.2 Column meta data token.
        See Also:
        Constant Field Values
      • TDS_TABNAME_TOKEN

        private static final byte TDS_TABNAME_TOKEN
        TDS Table name token.
        See Also:
        Constant Field Values
      • TDS_COLINFO_TOKEN

        private static final byte TDS_COLINFO_TOKEN
        TDS Cursor results column infomation token.
        See Also:
        Constant Field Values
      • TDS_OPTIONCMD_TOKEN

        private static final byte TDS_OPTIONCMD_TOKEN
        TDS Optional command token.
        See Also:
        Constant Field Values
      • TDS_COMP_NAMES_TOKEN

        private static final byte TDS_COMP_NAMES_TOKEN
        TDS Computed result set names token.
        See Also:
        Constant Field Values
      • TDS_COMP_RESULT_TOKEN

        private static final byte TDS_COMP_RESULT_TOKEN
        TDS Computed result set token.
        See Also:
        Constant Field Values
      • TDS_ORDER_TOKEN

        private static final byte TDS_ORDER_TOKEN
        TDS Order by columns token.
        See Also:
        Constant Field Values
      • TDS_ERROR_TOKEN

        private static final byte TDS_ERROR_TOKEN
        TDS error result token.
        See Also:
        Constant Field Values
      • TDS_INFO_TOKEN

        private static final byte TDS_INFO_TOKEN
        TDS Information message token.
        See Also:
        Constant Field Values
      • TDS_PARAM_TOKEN

        private static final byte TDS_PARAM_TOKEN
        TDS Output parameter value token.
        See Also:
        Constant Field Values
      • TDS_LOGINACK_TOKEN

        private static final byte TDS_LOGINACK_TOKEN
        TDS Login acknowledgement token.
        See Also:
        Constant Field Values
      • TDS_CONTROL_TOKEN

        private static final byte TDS_CONTROL_TOKEN
        TDS control token.
        See Also:
        Constant Field Values
      • TDS_ROW_TOKEN

        private static final byte TDS_ROW_TOKEN
        TDS Result set data row token.
        See Also:
        Constant Field Values
      • TDS_ALTROW

        private static final byte TDS_ALTROW
        TDS Computed result set data row token.
        See Also:
        Constant Field Values
      • TDS5_PARAMS_TOKEN

        private static final byte TDS5_PARAMS_TOKEN
        TDS 5.0 parameter value token.
        See Also:
        Constant Field Values
      • TDS_CAP_TOKEN

        private static final byte TDS_CAP_TOKEN
        TDS 5.0 capabilities token.
        See Also:
        Constant Field Values
      • TDS_ENVCHANGE_TOKEN

        private static final byte TDS_ENVCHANGE_TOKEN
        TDS environment change token.
        See Also:
        Constant Field Values
      • TDS_MSG50_TOKEN

        private static final byte TDS_MSG50_TOKEN
        TDS 5.0 message token.
        See Also:
        Constant Field Values
      • TDS_DBRPC_TOKEN

        private static final byte TDS_DBRPC_TOKEN
        TDS 5.0 RPC token.
        See Also:
        Constant Field Values
      • TDS5_DYNAMIC_TOKEN

        private static final byte TDS5_DYNAMIC_TOKEN
        TDS 5.0 Dynamic SQL token.
        See Also:
        Constant Field Values
      • TDS5_PARAMFMT_TOKEN

        private static final byte TDS5_PARAMFMT_TOKEN
        TDS 5.0 parameter descriptor token.
        See Also:
        Constant Field Values
      • TDS_AUTH_TOKEN

        private static final byte TDS_AUTH_TOKEN
        TDS 7.0 NTLM authentication challenge token.
        See Also:
        Constant Field Values
      • TDS_RESULT_TOKEN

        private static final byte TDS_RESULT_TOKEN
        TDS 5.0 Result set column meta data token.
        See Also:
        Constant Field Values
      • TDS_DONE_TOKEN

        private static final byte TDS_DONE_TOKEN
        TDS done token.
        See Also:
        Constant Field Values
      • TDS_DONEPROC_TOKEN

        private static final byte TDS_DONEPROC_TOKEN
        TDS done procedure token.
        See Also:
        Constant Field Values
      • TDS_DONEINPROC_TOKEN

        private static final byte TDS_DONEINPROC_TOKEN
        TDS done in procedure token.
        See Also:
        Constant Field Values
      • TDS_ENV_DATABASE

        private static final byte TDS_ENV_DATABASE
        Environment change: database changed.
        See Also:
        Constant Field Values
      • TDS_ENV_LANG

        private static final byte TDS_ENV_LANG
        Environment change: language changed.
        See Also:
        Constant Field Values
      • TDS_ENV_CHARSET

        private static final byte TDS_ENV_CHARSET
        Environment change: charset changed.
        See Also:
        Constant Field Values
      • TDS_ENV_PACKSIZE

        private static final byte TDS_ENV_PACKSIZE
        Environment change: network packet size changed.
        See Also:
        Constant Field Values
      • TDS_ENV_LCID

        private static final byte TDS_ENV_LCID
        Environment change: locale changed.
        See Also:
        Constant Field Values
      • TDS_ENV_SQLCOLLATION

        private static final byte TDS_ENV_SQLCOLLATION
        Environment change: TDS 8 collation changed.
        See Also:
        Constant Field Values
      • DONE_MORE_RESULTS

        private static final byte DONE_MORE_RESULTS
        Done: more results are expected.
        See Also:
        Constant Field Values
      • DONE_ERROR

        private static final byte DONE_ERROR
        Done: command caused an error.
        See Also:
        Constant Field Values
      • DONE_ROW_COUNT

        private static final byte DONE_ROW_COUNT
        Done: There is a valid row count.
        See Also:
        Constant Field Values
      • DONE_CANCEL

        static final byte DONE_CANCEL
        Done: Cancel acknowledgement.
        See Also:
        Constant Field Values
      • 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).
        See Also:
        Constant Field Values
      • TEMPORARY_STORED_PROCEDURES

        public static final int TEMPORARY_STORED_PROCEDURES
        Prepare SQL using temporary stored procedures
        See Also:
        Constant Field Values
      • EXECUTE_SQL

        public static final int EXECUTE_SQL
        Prepare SQL using sp_executesql
        See Also:
        Constant Field Values
      • PREPARE

        public static final int PREPARE
        Prepare SQL using sp_prepare and sp_execute
        See Also:
        Constant Field Values
      • SYB_LONGDATA

        static final int SYB_LONGDATA
        Sybase char and binary > 255.
        See Also:
        Constant Field Values
      • SYB_DATETIME

        static final int SYB_DATETIME
        Sybase date and time data types.
        See Also:
        Constant Field Values
      • SYB_EXTCOLINFO

        static final int SYB_EXTCOLINFO
        Sybase extended column meta data.
        See Also:
        Constant Field Values
      • ASYNC_CANCEL

        private static final int ASYNC_CANCEL
        Cancel has been generated by Statement.cancel().
        See Also:
        Constant Field Values
      • TIMEOUT_CANCEL

        private static final int TIMEOUT_CANCEL
        Cancel has been generated by a query timeout.
        See Also:
        Constant Field Values
      • tds8SpNames

        private static java.util.HashMap tds8SpNames
        Map of system stored procedures that have shortcuts in TDS8.
      • hostName

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

        private static SSPIJNIClient sspiJNIClient
        A reference to ntlm.SSPIJNIClient.
      • connection

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

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

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

        private final SharedSocket socket
        The Shared network socket object.
      • out

        private final RequestStream out
        The output server request stream.
      • in

        private final ResponseStream in
        The input server response stream.
      • 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.
      • columns

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

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

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

        private java.lang.Integer returnStatus
        The stored procedure return status.
      • returnParam

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

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

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

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

        private boolean isClosed
        Indicates that this object is closed.
      • ntlmAuthSSO

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

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

        private Semaphore connectionLock
        Mutual exclusion lock on connection.
      • inBatch

        private boolean inBatch
        Indicates processing a batch.
      • sslMode

        private int sslMode
        Indicates type of SSL connection.
      • cancelPending

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

        private final int[] cancelMonitor
        Synchronization monitor for cancelPending.
    • Constructor Detail

      • TdsCore

        TdsCore​(ConnectionJDBC2 connection,
                SQLDiagnostic messages)
        Construct a TdsCore object.
        Parameters:
        connection - The connection which owns this object.
        messages - The SQLDiagnostic messages chain.
    • Method Detail

      • checkOpen

        private void checkOpen()
                        throws java.sql.SQLException
        Check that the connection is still open.
        Throws:
        java.sql.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

        void setColumns​(ColInfo[] columns)
        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

        java.lang.Object[] getRowData()
        Retrieve the current result set data items.
        Returns:
        the row data as an Object array
      • negotiateSSL

        void negotiateSSL​(java.lang.String instance,
                          java.lang.String ssl)
                   throws java.io.IOException,
                          java.sql.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.
        Throws:
        java.io.IOException
        java.sql.SQLException
      • login

        void login​(java.lang.String serverName,
                   java.lang.String database,
                   java.lang.String user,
                   java.lang.String password,
                   java.lang.String domain,
                   java.lang.String charset,
                   java.lang.String appName,
                   java.lang.String progName,
                   java.lang.String wsid,
                   java.lang.String language,
                   java.lang.String macAddress,
                   int packetSize)
            throws java.sql.SQLException
        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
        Throws:
        java.sql.SQLException - if an error occurs
      • getMoreResults

        boolean getMoreResults()
                        throws java.sql.SQLException
        Get the next result set or update count from the TDS stream.
        Returns:
        boolean if the next item is a result set.
        Throws:
        java.sql.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

        void clearResponseQueue()
                         throws java.sql.SQLException
        Empty the server response queue.
        Throws:
        java.sql.SQLException - if an error occurs
      • consumeOneResponse

        void consumeOneResponse()
                         throws java.sql.SQLException
        Consume packets from the server response queue up to (and including) the first response terminator.
        Throws:
        java.sql.SQLException - if an I/O or protocol error occurs; server errors are queued up and not thrown
      • getNextRow

        boolean getNextRow()
                    throws java.sql.SQLException
        Retrieve the next data row from the result set.
        Returns:
        false if at the end of results, true otherwise
        Throws:
        java.sql.SQLException - if an I/O or protocol error occurs; server errors are queued up and not thrown
      • isDataInResultSet

        boolean isDataInResultSet()
                           throws java.sql.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.
        Throws:
        java.sql.SQLException
      • getReturnStatus

        java.lang.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

        void close()
            throws java.sql.SQLException
        Close the TdsCore connection object and associated streams.
        Throws:
        java.sql.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

        void submitSQL​(java.lang.String sql)
                throws java.sql.SQLException
        Submit a simple SQL statement to the server and process all output.
        Parameters:
        sql - the statement to execute
        Throws:
        java.sql.SQLException - if an error is returned by the server
      • startBatch

        void startBatch()
        Notifies the TdsCore that a batch is starting. This is so that it knows to use sp_executesql for parameterized queries (because there's no way to prepare a statement in the middle of a batch).

        Sets the inBatch flag.

      • executeSQL

        void executeSQL​(java.lang.String sql,
                        java.lang.String procName,
                        ParamInfo[] parameters,
                        boolean noMetaData,
                        int timeOut,
                        int maxRows,
                        int maxFieldSize,
                        boolean sendNow)
                 throws java.sql.SQLException
        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
        Throws:
        java.sql.SQLException - if an error occurs
      • microsoftPrepare

        java.lang.String microsoftPrepare​(java.lang.String sql,
                                          ParamInfo[] params,
                                          boolean needCursor,
                                          int resultSetType,
                                          int resultSetConcurrency)
                                   throws java.sql.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.
        Throws:
        java.sql.SQLException
      • sybasePrepare

        java.lang.String sybasePrepare​(java.lang.String sql,
                                       ParamInfo[] params)
                                throws java.sql.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
        Throws:
        java.sql.SQLException - if an error occurs
      • sybaseUnPrepare

        void sybaseUnPrepare​(java.lang.String procName)
                      throws java.sql.SQLException
        Drops a Sybase temporary stored procedure.
        Parameters:
        procName - the temporary procedure name
        Throws:
        java.sql.SQLException - if an error occurs
      • enlistConnection

        byte[] enlistConnection​(int type,
                                byte[] oleTranID)
                         throws java.sql.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
        Throws:
        java.sql.SQLException
      • getBatchCounts

        java.sql.SQLException getBatchCounts​(java.util.ArrayList counts,
                                             java.sql.SQLException sqlEx)
                                      throws java.sql.SQLException
        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 occurred
        Throws:
        java.sql.SQLException - if the connection is closed
      • putLoginString

        private void putLoginString​(java.lang.String txt,
                                    int len)
                             throws java.io.IOException
        Write a TDS login packet string. Text followed by padding followed by a byte sized length.
        Throws:
        java.io.IOException
      • sendPreLoginPacket

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

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

        Parameters:
        instance -
        forceEncryption -
        Throws:
        java.io.IOException
      • readPreLoginPacket

        private int readPreLoginPacket()
                                throws java.io.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.
        Throws:
        java.io.IOException
      • send42LoginPkt

        private void send42LoginPkt​(java.lang.String serverName,
                                    java.lang.String user,
                                    java.lang.String password,
                                    java.lang.String charset,
                                    java.lang.String appName,
                                    java.lang.String progName,
                                    java.lang.String wsid,
                                    java.lang.String language,
                                    int packetSize)
                             throws java.io.IOException
        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
        Throws:
        java.io.IOException - if an I/O error occurs
      • send50LoginPkt

        private void send50LoginPkt​(java.lang.String serverName,
                                    java.lang.String user,
                                    java.lang.String password,
                                    java.lang.String charset,
                                    java.lang.String appName,
                                    java.lang.String progName,
                                    java.lang.String wsid,
                                    java.lang.String language,
                                    int packetSize)
                             throws java.io.IOException
        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
        Throws:
        java.io.IOException - if an I/O error occurs
      • sendMSLoginPkt

        private void sendMSLoginPkt​(java.lang.String serverName,
                                    java.lang.String database,
                                    java.lang.String user,
                                    java.lang.String password,
                                    java.lang.String domain,
                                    java.lang.String appName,
                                    java.lang.String progName,
                                    java.lang.String wsid,
                                    java.lang.String language,
                                    java.lang.String macAddress,
                                    int netPacketSize)
                             throws java.io.IOException,
                                    java.sql.SQLException
        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
        Throws:
        java.io.IOException - if an I/O error occurs
        java.sql.SQLException
      • sendNtlmChallengeResponse

        private void sendNtlmChallengeResponse​(byte[] nonce,
                                               java.lang.String user,
                                               java.lang.String password,
                                               java.lang.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.
        Throws:
        java.io.IOException
      • nextToken

        private void nextToken()
                        throws java.sql.SQLException
        Read the next TDS token from the response stream.
        Throws:
        java.sql.SQLException - if an I/O or protocol error occurs
      • tdsInvalidToken

        private void tdsInvalidToken()
                              throws java.io.IOException,
                                     ProtocolException
        Report unsupported TDS token in input stream.
        Throws:
        java.io.IOException
        ProtocolException
      • tds5ParamFmt2Token

        private void tds5ParamFmt2Token()
                                 throws java.io.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.

        Throws:
        java.io.IOException
        ProtocolException
      • tds5WideResultToken

        private void tds5WideResultToken()
                                  throws java.io.IOException,
                                         ProtocolException
        Process Sybase 12+ wide result token which provides enhanced column meta data.
        Throws:
        java.io.IOException
        ProtocolException
      • tdsReturnStatusToken

        private void tdsReturnStatusToken()
                                   throws java.io.IOException,
                                          java.sql.SQLException
        Process stored procedure return status token.
        Throws:
        java.io.IOException
        java.sql.SQLException
      • tdsProcIdToken

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

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

        Throws:
        java.io.IOException
      • tdsOffsetsToken

        private void tdsOffsetsToken()
                              throws java.io.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".

        Throws:
        java.io.IOException
      • tds7ResultToken

        private void tds7ResultToken()
                              throws java.io.IOException,
                                     ProtocolException,
                                     java.sql.SQLException
        Process a TDS 7.0 result set token.
        Throws:
        java.io.IOException
        ProtocolException
        java.sql.SQLException
      • tds4ColNamesToken

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

        Note: Will be followed by a COL_FMT token.

        Throws:
        java.io.IOException
      • tds4ColFormatToken

        private void tds4ColFormatToken()
                                 throws java.io.IOException,
                                        ProtocolException
        Process a TDS 4.2 column format token.
        Throws:
        java.io.IOException
        ProtocolException
      • tdsTableNameToken

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

        Sent by select for browse or cursor functions.

        Throws:
        java.io.IOException
        ProtocolException
      • tdsColumnInfoToken

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

        Sent by select for browse or cursor functions.

        Throws:
        java.io.IOException
        ProtocolException
      • tdsOrderByToken

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

        Sent to describe columns in an order by clause.

        Throws:
        java.io.IOException
      • tdsErrorToken

        private void tdsErrorToken()
                            throws java.io.IOException
        Process a TD4/TDS7 error or informational message.
        Throws:
        java.io.IOException
      • tdsOutputParamToken

        private void tdsOutputParamToken()
                                  throws java.io.IOException,
                                         ProtocolException,
                                         java.sql.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.
        Throws:
        java.io.IOException
        ProtocolException
        java.sql.SQLException
      • tdsLoginAckToken

        private void tdsLoginAckToken()
                               throws java.io.IOException
        Process a login acknowledgement packet.
        Throws:
        java.io.IOException
      • tdsControlToken

        private void tdsControlToken()
                              throws java.io.IOException
        Process a control token (function unknown).
        Throws:
        java.io.IOException
      • tds5ParamsToken

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

        Throws:
        java.io.IOException
        ProtocolException
        java.sql.SQLException
      • tdsCapabilityToken

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

        Sent after login to describe the server's capabilities.

        Throws:
        java.io.IOException - if an I/O error occurs
        ProtocolException
      • tdsEnvChangeToken

        private void tdsEnvChangeToken()
                                throws java.io.IOException,
                                       java.sql.SQLException
        Process an environment change packet.
        Throws:
        java.io.IOException
        java.sql.SQLException
      • tds5ErrorToken

        private void tds5ErrorToken()
                             throws java.io.IOException
        Process a TDS 5 error or informational message.
        Throws:
        java.io.IOException
      • tds5DynamicToken

        private void tds5DynamicToken()
                               throws java.io.IOException
        Process TDS5 dynamic SQL aknowledgements.
        Throws:
        java.io.IOException
      • tds5ParamFmtToken

        private void tds5ParamFmtToken()
                                throws java.io.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.

        Throws:
        java.io.IOException
        ProtocolException
      • tdsNtlmAuthToken

        private void tdsNtlmAuthToken()
                               throws java.io.IOException,
                                      ProtocolException
        Process a NTLM Authentication challenge.
        Throws:
        java.io.IOException
        ProtocolException
      • getIntFromBuffer

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

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

        private void tds5ResultToken()
                              throws java.io.IOException,
                                     ProtocolException
        Process a TDS 5.0 result set packet.
        Throws:
        java.io.IOException
        ProtocolException
      • tdsDoneToken

        private void tdsDoneToken()
                           throws java.io.IOException
        Process a DONE, DONEINPROC or DONEPROC token.
        Throws:
        java.io.IOException
      • executeSQL42

        private void executeSQL42​(java.lang.String sql,
                                  java.lang.String procName,
                                  ParamInfo[] parameters,
                                  boolean noMetaData,
                                  boolean sendNow)
                           throws java.io.IOException,
                                  java.sql.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:
        java.sql.SQLException
        java.io.IOException
      • executeSQL50

        private void executeSQL50​(java.lang.String sql,
                                  java.lang.String procName,
                                  ParamInfo[] parameters)
                           throws java.io.IOException,
                                  java.sql.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:
        java.sql.SQLException
        java.io.IOException
      • isPreparedProcedureName

        public static boolean isPreparedProcedureName​(java.lang.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.
      • executeSQL70

        private void executeSQL70​(java.lang.String sql,
                                  java.lang.String procName,
                                  ParamInfo[] parameters,
                                  boolean noMetaData,
                                  boolean sendNow)
                           throws java.io.IOException,
                                  java.sql.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.
        Throws:
        java.sql.SQLException
        java.io.IOException
      • setRowCountAndTextSize

        private void setRowCountAndTextSize​(int rowCount,
                                            int textSize)
                                     throws java.sql.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
        Throws:
        java.sql.SQLException - if an error is returned by the server
      • wait

        private void wait​(int timeOut)
                   throws java.io.IOException,
                          java.sql.SQLException
        Waits for the first byte of the server response.
        Parameters:
        timeOut - the timeout period in seconds or 0
        Throws:
        java.io.IOException
        java.sql.SQLException
      • 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.

      • getMessages

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

        private static byte[] getMACAddress​(java.lang.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[]
      • getHostName

        private static java.lang.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
      • tds7CryptPass

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