/* libzzdb
 *
 * This program is distributed under the GNU General Public License, version 2.
 * A copy of this license is included with this source.
 *
 * Copyright 2000-2006, Toni Thomsson <toni@tonjac.org> 
*/

#ifndef zz_db_h
#define zz_db_h

#include <zz_string.h>
#include <zz_log.h>
#include <zz_export.h>
#include <otl.h>

#define BEGIN_TRY try {
#define END_TRY }

#define BEGIN_CATCH catch( otl_exception& e ){ CzzDbException::m_LastExtException = e;
#define END_CATCH }

/**
    SQL stream
    @author Toni Thomsson, toni@tonjac.org
*/
class ZZ_API CzzSQLStream: public otl_stream
{
public:
    /**
        Create stream
        @param  db  connection, see OTL
        @param  Stm SQL-statement with bind variables
        @param  BufSize Buffert size
        @param  autocommit  Autocommit on/off 1=on, 0=off
    */
    CzzSQLStream( otl_connect& db, const CzzString Stm, const short BufSize, int autocommit = 0 );
    
    /** Row count */
    int RowCount(void);

    /** SQL statement */
    char* GetSqlStm(void);

    /** Cursor */
    otl_cursor* GetCurrentCursor(void);

private:
    CzzLog  m_Log;
};

/**
    Database access via OTL
    @author Toni Thomsson, toni@tonjac.org
*/
class ZZ_API CzzDb
{
    static int m_cnt;

protected:
    /** OTL-connection handle */
    otl_connect m_db;
    /** SQL */
    CzzString m_SQL;
    /** Logger */
    CzzLog m_Log;
       
public:

    /** 
        Create database wrapper
        @param db_user  User/connect
        @param autocommit   Enable/disable autocommit, 1=auto, 0=manual
    */
    CzzDb(const CzzString& db_user, int autocommit = 1);
    ~CzzDb();
    
    /** Commit transaction */
    void Commit(void);

    /** Rollback transaction */
    void Rollback(void);
    
    /** System date */
    void GetSysDate(char* sysdate);
    
    /** User/connect */
    void GetDbUser(char *dbUser);
  
    /** 
        Create a SQL stream 
        @param sql      SQL-string with bind valiables, see OTL
        @param bufsize  Buffert size
    */
    CzzSQLStream* getStream( const CzzString& sql, const short bufsize );

    /** Autocommit */
    int m_AutoCommit;
};


#endif