SybSQL class

index

# SybSQL

SybSQL provides high level interfaces between Ruby and Sybase server. This class includes methods that connect to a server, and methods that send commands to a server, and methods that process the results.

### Contents

- Class Method
- Methods for connection
- Methods for sending commands
- Methods for processing results
- Methods for SQL server options
- Methods for Text and Image datatype
- Methods for Client-Library cursor

### Included Modules

- SybConstant

### Class Method

new ( hash, context_class=SybSQLContext )
  This method initialize Client-Library , and connect to a server by properties which specified hash

  Parameters:

  - hash
    Specify connection properties as a Hash object.

    Details for key-value pair

    Key | Value
    --- | ---
    'S' | The name of the server to connect to. (required)
    'U' | The name used to log into the server.(required)
    'P' | The password used to log into the server. (the default is "" )
    'lang' | A locale name which is registered in $SYBASE/locales/locales.dat
    'timeout' | The timeout value(seconds) for a server response. (the default is 0 , which represents an infinite timeout period.)
    'login-timeout' | The login timeout value(seconds)
    'appname' | The application name used when logging into the server
    'hostname' | The host machine name used when logging into the server
    'async' | In case of multiple threads application, you must set this to true. (the default is false) See also SybContext.create.

  - context_class
    If you want to redefine message-callbacks, please specify subclass of SybSQLContext to context_class l

  Examples:

  - Server-name: SYBSRV01, Username: sa, Locale-name: ja_JP.ujis

        query = SybSQL.new({'S'=>'SYBSRV01','U'=>'sa','P'=>'XXXXXX',
                                    'lang'=>'ja_JP.ujis'} )

  - Redefinition of Server-Message callback

        class MyContext < SybSQLContext
          def srvmsgCB( con,msghash)
            print "My server-callback\n"
          end
        end
        query = SybSQL.new({'S'=>'SYBSRV01','U'=>'sa','P'=>'XXXXXX'}, MyContext)

### Methods for connection

context
  Returns the SybContext object.

connection
  Returns the SybConnection object.

close ( force=false )
  Close the server connection, and exit Client-Library.

  If the force parameter is true, the connection is closed whether or not results are pending, and without notifying the server.

connection_status
  return connection status
  return value is SybConstant::CS_CONSTAT_DEAD, SybConstant::CS_CONSTAT_CONNECTED bit OR

connection_dead?
  This call returns TRUE if the connection has been marked DEAD.
  You need to reconnect to the server.

### Methods for sending commands

sql ( command, nbind=nil )
  Runs the SQL commands.
  You can get query results by the result method later.

  Parameters:

  - command
    Language commands
  - nbind
    The maximum column number to be fetched.
    If you want to fetch all columns, set this to nil.

  Examples:

         query.sql('select * from sysservers')
         raise "ERROR: select ..." unless (query.cmd_done? )

sql ( command, nbind=nil ) {|cmd,st,col,row| }
  Runs the SQL commands.
  Whenever one row is retrieved, the block is called.

  The block parameters

    cmd | SybCommand object
    st | SybConstant::CS_SUCCEED or SybConstant::CS_ROW_FAIL
    col | The array of column names
    row | The array of row datas

  The block's return value

    true | The row's value is added to the result that the results method returns.
    nil | The row's value is not added to the result that the results method returns. (When large number of rows are retrieved, this is effective in order to save memory)
    false | Stop to iterates

  Examples:

           query.sql("select title_id, notes from titles"){
             |cm,s,c,r|
             note = r[1]
             # get first sentence
             if( note =~ /^([^\.]*)\./io ) then
      	 print r[0],"\t",$1,"\n"
             end
             nil		# Not use a SybResult object
           }

set_strip ( on )
  If on is true, then sql method will strip the trailing white spaces from all of the String values in the results.

sql_norow ( command )
  This method is used to send SQL commands to the server that do not return rows, such as insert, use db, and update statement.

  Returns:
    true if it was completed successfully.

  Examples:

        raise "ERROR: use DB" unless query.sql_norow('use master')

timeout?
  Returns TRUE , if the driver has exceeded the timeout period while waiting for a response from the Server
  (This method depends upon implementation of Client-Message-Callback.)

### Methods for processing results

results
  Returns the result as array of SybResult objects, which is retrieved by sql or sql_norow or sql_iodesc method.

  The following table lists correspondence with SyBase datatype and Ruby datatype that this module handle.

  SyBase datatype | Ruby datatype
  --- | ---
  TINYINT | Integer
  SMALLINT | Integer
  INT | Integer
  REAL | Float
  FLOAT | Float
  Others | String

each_results( type=SybConstant::CS_ROW_RESULT ) { | r | .. }
  Iterates over each SybResult object in Result Sets which type of result is equal to type.

nth_results ( nth=0, type = SybConstant::CS_ROW_RESULT )
  Returns the nth SybResult object in Result Sets which type of result is equal to type.

  The parameter type indicates the type of result. the following table lists the possible value of type.

  CS_CMD_SUCCEED | The success of a command that returns no data
  CS_CMD_DONE | The results of a command have been completely processed.
  CS_CMD_FAIL | The server encountered an error while executing a command
  CS_ROW_RESULT | Regular row results
  CS_PARAM_RESULT | Parameter results
  CS_STATUS_RESULT | Stored procedure return status results.
  CS_COMPUTE_RESULT | Compute row results

  These CS_XXX_XXXXX constants is defined in SybConstant module.

  Examples

        ### Prints out two RowResults. #####
        query.sql("select * from table1\n select * from table2")
        raise "Failed" unless (query.cmd_done? )
        raise "No results in table1" unless (res = query.nth_results(0, CS_ROW_RESULT) )
        res.rows.each {
          |r| print "  #{r.join('|')}\n"
        }
        raise "No results in table2" unless (res = query.nth_results(1, CS_ROW_RESULT) )
        res.rows.each {
           |r| print "  #{r.join('|')}\n"
        }

top_row_result
  Returns the first regular row result in Result Sets.

      This method is equivalent to
            nth_results(0, SybConstant::CS_ROW_RESULT)

top_param_result
  Returns the first parameter result in Result Sets.

      This method is equivalent to
         nth_results(0, SybConstant::CS_PARAM_RESULT)

top_status_result
  Returns the first return-status as a Integer object.

cmd_done?
  Returns TRUE, if the results of a command have been completely processed.

cmd_succeed?
  Returns TRUE, if the command returning no rows completely successfully.

cmd_fail?
  Returns TRUE, if the server encountered an error while executing a command.

### Methods for SQL server options

set_rowcount ( maxrows )
  Sets the limit for the maximum number of rows.

  Parameters:
  maxrows - The max rows limit, maxrows=0 means unlimited.
  (This method corresponds to "set rowcount maxrows" of Transact-SQL.)

set_forceplan( val )
  This method corresponds to "set forceplan val" of Transact-SQL

### Methods for Text and Image datatype

image_transize (size=nil )
  If size was specified in param, This method sets data transfer size for the sql_getimage method and the send_imagefile method.
  If size was omitted, This method returns the current data transfer size.

  In initial condition, Data transfer size is set to 1024 bytes.

image_log( lg )
  This method tells the server whether or not to log the update operation of the send_imagefile method and the send_image method.

  if the lg parameter is FALSE, then the server does not update log
  ("select into/bulkcopy option" is necessary for the database beforehand.)

sql_getimage( sqlstr, id ) { | rowid, row, clmid, clm, data | }
  Retrieve Image or Text data.
  Buffer size for transfer is specified by the image_transize method.

  Parameters:

  - sqlstr
    SQL statement for fetching Image/Text column.
    As for the order of columns, Image/Text column should come last.

  - id
    The column number of the first Image/Text item (starting at 1)

  - Block
    Iterates over each chunk of data .

    The block parameters

      rowid | index of row data(start at 0)
      row | The array of row datas
      clmid | The column number (start at 0)
      clm | The array of column names
      data | String : A chunk of Image/Text data nil : It retrieved the last chunk of data false : Failed

  If error has occurred, then it raise a RuntimeError exception.

  Examples
  Retrieves image data from the au_pix table

        query=SybSQL.new( {'S'=>'SYBASE', 'U'=>'sa', 'P'=>'XXXXXX'} )
        raise "ERROR: use pubs2" unless( query.sql_norow("use pubs2") )

        # Enlarges CS_OPT_TEXTSIZE
        #          (The maximum data size which the server should return)
        unless( query.connection.setopt(CS_OPT_TEXTSIZE, 1024 * 1024)) then
          $stderr.print("ERROR: setopt(CS_OPT_TEXTSIZE)\n");
        end

        file = File.open("486-29-1786.ras","w")   # open the file
        query.image_transize(8192)   # set buffer size for transfer
        imgsize = 0
        sql = "select au_id ,pic from au_pix where au_id = '486-29-1786'"
        query.sql_getimage(sql, 2){
          |rid,r,cid,clm, data|
          if( data.kind_of?(String) )then
            file.write(data)
            imgsize += data.length
          elsif (data.nil?) then
            print "End of data\n"
            file.close
          end
        }
        print "Size=#{imgsize}\n"

sql_iodesc( sqlstr, id )

  Gets the current SybIODesc object (I/O descriptor).

  Parameters:

  - sqlstr
    SQL statement for fetching the I/O descriptor item.
    As for the order of columns, I/O descriptor column (usually Image/Text column) should come last.

  - id
    The column number of the first I/O descriptor item , usually Image/Text column. (starting at 1)

  Returns:
  Returns a SybIODesc object.
  In case of error; raise RuntimeError exception.

send_image ( iodesc, imagesize ) { | cmd | }

  Sends Image or Text data

  Parameters:

  - iodesc
    Specify SybIODesc object
    This object will be destructively updated.

  - imagesize
    The whole size , in bytes, of Image/Text data to send.
    If zero is specified, the column is updated to NULL.

  Block
  When setup to transmit data was completed, this method calls a block repeatedly. In this block, you must provide the server with a chunk of Image/Text data.

  The block parameters
    cmd --- SybCommand object

  Return value of the block
    String object:
      A chunk of Image/Text data.
      It's length <= image_transize .
    nil :
      Indicates end of transfer.

  If error has occurred, then it raise a RuntimeError exception.

send_imagefile ( iodesc, filename )

  Sends contents of the file to a server as Image or Text data
  Buffer size for transfer is specified by the image_transize method.

  Parameters:

  - iodesc
    Specify SybIODesc object
    This object will be destructively updated.

  - filename
    File name

  If error has occurred, it raise a RuntimeError exception.

  Examples
  Inserts new Image data row to the au_pix table in the pubs2 database.

        query=SybSQL.new( {'S'=>'SYBASE', 'U'=>'sa', 'P'=>'XXXXXX'} )

        # Enable bulkcopy into the database
        raise "ERROR: use master" unless( query.sql_norow("use master") )
        query.sql("exec sp_dboption pubs2,'select into/bulkcopy',true")
        raise "ERROR: sp_dboption" unless (query.cmd_done? )
        # Check the return status.
        raise "ERROR: sp_dboption" if( query.top_status_result != 0 )
        # checkpoint
        raise "ERROR: use pubs2" unless( query.sql_norow("use pubs2") )
        raise "ERROR: checkpoint" unless( query.sql_norow("checkpoint") )

        # Insert new row
        sql = "insert au_pix (au_id,format_type ) values ('my-image-1', 'JPG')"
        raise "ERROR: insert" unless( query.sql_norow(sql) )

        # Update Image column to NULL.  --  (required)
        sql = 'update au_pix set pic=NULL where au_id = "my-image-1"'
        raise "ERROR update" unless( query.sql_norow(sql) )

        query.image_transize( 2048 )	# set buffer size for transfer
        query.image_log( false )	# with no log

        # Retrieves SybIODesc
        sql = 'select au_id,pic from au_pix where au_id = "my-image-1"'
        query.sql_iodesc(sql,2)
        iodesc = query.top_row_result.nthrow(0,1)
        raise "Cannot fetch IODESC" unless( iodesc.kind_of?(SybIODesc) )

        # Send contents of my-image-1.jpg file to the server.
        query.send_imagefile(iodesc, "my-image-1.jpg")
        print "Success\n"

### Methods for Client-Library cursor

do_cursor ( csrname, langcmd, rowcount=nil, curopt=nil, nbind=nil) {| cmd, st, col, row | }
  Declares Client-Library cursor and executes it.
  Note:
  - If the do_cursor method is finished, then the cursor is deallocated automatically
  - About the Language cursor, please process it with a sql method.

  Parameters:

  - csrname
    The cursor name to declare.

  - langcmd
    The SQL text that represents the body of the cursor.
    (See also: SybCommand#cursor_new)

  - rowcount
    The number of rows to be returned with a single fetch request.
    (See also: SybCommand#cursor_rows)

  - curopt
    The option to declare the cursor.
    (See also: SybCommand#cursor_new)

  - nbind
    The maximum column number to be fetched.
    If you want to fetch all columns, set this to nil.

  Whenever one row is retrieved, the block is called.
  In the block, nested UPDATE and DELETE commands can be used.

  The block parameters

    cmd | SybCommand object
    st | SybConstant::CS_SUCCEED or SybConstant::CS_ROW_FAIL
    col | The array of column names
    row | The array of row datas

  The block's return value

    true | The row's value is added to the result that the results method returns.
    nil | The row's value is not added to the result that the results method returns. (When large number of rows are retrieved, this is effective in order to save memory)
    false | Stop to iterates

  Examples:
  See, sample/cursor_disp.rb and sample/cursor_update.rb