WORM 0.2
A C++ DAL/ORM code generation framework
Public Member Functions

WSql::WSqlDatabase Class Reference

The WSqlDatabase class represents a single database. More...

#include <wsqldatabase.h>

List of all members.

Public Member Functions

 WSqlDatabase ()
 Creates an empty, invalid WSqlDatabase object.
 WSqlDatabase (const WSql::DriverType &type)
 Creates a WSqlDatabase object with a driver.
 WSqlDatabase (const WSqlDatabase &other)
 Creates a copy of other.
 ~WSqlDatabase ()
 Destroys the object and frees any allocated resources.
WSqlDatabaseoperator= (const WSqlDatabase &other)
 Copies the values of other to this object.
bool open ()
 Open a connection.
bool open (const std::string &username, const std::string &password)
 Open a connection using username and password.
void close ()
bool isOpen () const
bool hasError () const
WSqlError error () const
std::vector< std::string > errors ()
bool isValid () const
std::string databaseName () const
std::string userName () const
std::string password () const
std::string hostName () const
int port () const
 Returns the connection's port number.
std::string connectionOptions () const
WSql::DriverType driverType ()
void setDatabaseName (const std::string &name)
 Set the the database name.
void setUserName (const std::string &name)
 Set the the user name.
void setPassword (const std::string &password)
 Set the the password.
void setHostName (const std::string &host)
 Sets the connection's host name.
void setPort (int p)
 Sets the port number for the connection.
void setConnectOptions (const std::string &options=std::string())
 Sets the connection options for this database server.
void setDriverType (WSql::DriverType t)
void addError (const WSqlError &e)
void setDriver (WSqlDriver *d)
WSqlDriverdriver () const
 Return a pointer to the database driver - expert only.
WSqlDriverhandle () const
const std::vector< std::string > & tableNames (WSql::TableType type=WSql::Tables)
 Returns a vector of the database's table names.
WSqlTable tableMetaData (const std::string &tableName) const
 Fetch metadata for table tableName.
void initMetaData ()
 Initializes the metadata for all tables in the database.
bool query (const std::string &sql)
 Executes the query in sql returning true on sucess.
WSqlResultresult (bool iscached=true)
 Returns a pointer to the result set from the most recent query.
bool initDriver ()

Detailed Description

The WSqlDatabase class represents a single database.

The WSqlDatabase class provides an interface for accessing a specific database through a connection. An instance of WSqlDatabase represents the information relevant to connecting to the database, including the name of the database, the host, the username, etc.

WSqlDatabase should be instantiated with a driver type (or another valid database object) - when constructed it will try to obtain the requested driver from WSqlDriverFactory(todo - currently just creates one ..). If this fails isValid() will return false.

Drivers are derived from WSqlDriver, see WSql::DriverType for supported database drivers.

Example:

WSql::WSqlDatabase db( WSql::WMYSQL );
db.setDatabaseName( std::string( "sakila" ) );
db.setUserName( "root" );

if ( !db.open() ) {
    std::cerr << "Failed to open: " << db.error().text() << std::endl;
    return 1;
}
std::string sql = "select * from " + sometable + " limit 2;";
if(!db.query(sql))
    std::cout << "Query Failed: " << db.error().text() << std::endl;
}else{
    WSql::WSqlResult *result = db.getResult();
    std::cout << "Number of rows: " << result->size() << std::endl;
    WSql::WSqlRecord record = result->fetchFirst();
    while(!record.empty())
    {
        int numcols = record.count(); // or record.size();
        std::cout << "Number of columns: " << record.size() << std::endl;
        WSql::WSqlField fld;
        for(int i = 0;i < record.size();i++)
        {
            //no danger - if there is nothing there we still get an empty field object 
            fld = record.field(i);
            std::cout << "Field " << fld.name()
            << ", Origin Column "<< fld.columnName() 
            << "Value: " << fld.data<std::string>() << std::endl;
        }
        record = result->fetchNext();
    }
}
See also:
WSqlResult WSqlRecord WSqlField WSql::DriverType WSqlDriver

Definition at line 34 of file wsqldatabase.h.


Constructor & Destructor Documentation

WSql::WSqlDatabase::WSqlDatabase ( )

Creates an empty, invalid WSqlDatabase object.

Definition at line 104 of file wsqldatabase.cpp.

WSql::WSqlDatabase::WSqlDatabase ( const WSql::DriverType type)

Creates a WSqlDatabase object with a driver.

This constructs a database object with a driver of type - the object will attempt to create a driver - if successful isValid() will return true.

Parameters:
WSql::DriverTypetype - the type of driver to use

Definition at line 93 of file wsqldatabase.cpp.

WSql::WSqlDatabase::WSqlDatabase ( const WSqlDatabase other)

Creates a copy of other.

This constructs a new database object initialized with the values of other WARNING: This also creates a new driver! If other is destroyed getResult() is invalid until the next query() is called!

Parameters:
WSqlDatabaseother - database to copy

Definition at line 118 of file wsqldatabase.cpp.

WSql::WSqlDatabase::~WSqlDatabase ( )

Destroys the object and frees any allocated resources.

Note that the driver is also destroyed at this time - any WSqlResults obtained from getResult() will be invalid after this.

See also:
close()

Definition at line 137 of file wsqldatabase.cpp.


Member Function Documentation

void WSql::WSqlDatabase::addError ( const WSqlError e) [inline]

Definition at line 74 of file wsqldatabase.h.

void WSql::WSqlDatabase::close ( )

Closes the database connection.

Definition at line 256 of file wsqldatabase.cpp.

std::string WSql::WSqlDatabase::connectionOptions ( ) const

Returns the connection options string used for this connection. The string may be empty.

See also:
setConnectOptions()

Definition at line 582 of file wsqldatabase.cpp.

std::string WSql::WSqlDatabase::databaseName ( ) const

Returns the connection's database name, which may be empty.

See also:
setDatabaseName()

Definition at line 368 of file wsqldatabase.cpp.

WSqlDriver * WSql::WSqlDatabase::driver ( ) const

Return a pointer to the database driver - expert only.

This returns a pointer to the database driver used to access the database connection. Caution! This is not meant to be used directly - use open(). close(), query() and getResult() for interaction with the driver instead.

!This may be removed in future.

See also:
open() close() query() getResult()

Definition at line 420 of file wsqldatabase.cpp.

WSql::DriverType WSql::WSqlDatabase::driverType ( ) [inline]

Definition at line 64 of file wsqldatabase.h.

WSqlError WSql::WSqlDatabase::error ( ) const

Returns the last error that occurred on the database or in the driver.

See also:
WSqlError

Definition at line 430 of file wsqldatabase.cpp.

std::vector<std::string> WSql::WSqlDatabase::errors ( )
WSqlDriver* WSql::WSqlDatabase::handle ( ) const [inline]

Definition at line 80 of file wsqldatabase.h.

bool WSql::WSqlDatabase::hasError ( ) const

Returns true if there is an error available.

See also:
error()

Todo:
resolve this - there is also the local errorStack ..

Definition at line 275 of file wsqldatabase.cpp.

std::string WSql::WSqlDatabase::hostName ( ) const

Returns the connection's host name; it may be empty.

See also:
setHostName()

Definition at line 397 of file wsqldatabase.cpp.

bool WSql::WSqlDatabase::initDriver ( )

Definition at line 185 of file wsqldatabase.cpp.

void WSql::WSqlDatabase::initMetaData ( )

Initializes the metadata for all tables in the database.

This method can be used to initialize all the metadata for the the database at once - this is convenient if one wishes to then use table metadata while also conducting queries. If this is called before tableMetaData() the metadata for all tables is cached in the driver and will be returned for a given table from the cache.

Note:
This also initializes the referenced tables WSqlReferencedKeys - used by the ORM generation. If you need access to this kind of metadata you must use this method to initialize the referenced key lists - if you initialize table metadata individually the reference keys will be omitted.
See also:
tableMetaData() tableNames()

Definition at line 532 of file wsqldatabase.cpp.

bool WSql::WSqlDatabase::isOpen ( ) const

Returns true if the database connection is currently open

Definition at line 265 of file wsqldatabase.cpp.

bool WSql::WSqlDatabase::isValid ( ) const

Returns true if the WSqlDatabase has a valid driver.

Definition at line 590 of file wsqldatabase.cpp.

bool WSql::WSqlDatabase::open ( )

Open a connection.

Opens the database connection using the current connection values. Returns true on success; otherwise returns false. Error information can be retrieved using error().

See also:
error() setDatabaseName() setUserName() setPassword()
setHostName() setPort() setConnectOptions()

Definition at line 230 of file wsqldatabase.cpp.

bool WSql::WSqlDatabase::open ( const std::string &  username,
const std::string &  password 
)

Open a connection using username and password.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Opens the database connection using the given user name and password. Returns true on success; otherwise returns false. Error information can be retrieved using the error() function.

See also:
error()

Definition at line 245 of file wsqldatabase.cpp.

WSqlDatabase & WSql::WSqlDatabase::operator= ( const WSqlDatabase other)

Copies the values of other to this object.

WARNING: This also creates a new driver! If other is destroyed getResult() is invalid until the next query()!

Parameters:
WSqlDatabaseother - database to copy

Definition at line 152 of file wsqldatabase.cpp.

std::string WSql::WSqlDatabase::password ( ) const

Returns the connection's password. If the password was not set an empty string is returned.

Definition at line 387 of file wsqldatabase.cpp.

int WSql::WSqlDatabase::port ( ) const [inline]

Returns the connection's port number.

The value is -1 if the port number has not been set.

See also:
setPort()

Definition at line 62 of file wsqldatabase.h.

bool WSql::WSqlDatabase::query ( const std::string &  sql)

Executes the query in sql returning true on sucess.

This method sends the query SQL in string sql to the database server, the results of which will be available by calling getResult(). Use this method when you expect a result set, for non-result execution use execute()

See also:
getResult() execute()
Return values:
booltrue on success.

Definition at line 602 of file wsqldatabase.cpp.

WSqlResult * WSql::WSqlDatabase::result ( bool  iscached = true)

Returns a pointer to the result set from the most recent query.

This method returns a pointer to a WSqlResult object containing the most recent result set from a query - it may be empty if no results were returned. You must not delete this pointer yourself - it is owned by the driver.

The parameter iscached may be set to true to indicate a non-cached result set that will be fetched row by row - the default is true and results are cached. Note that uncached queries may or may not be implemented in a particular driver - see the documentation for the specific driver to find out.

Note:
Only use this after an execute() query! Do not use twice in a row as it will delete the previous result and return a newly created object. Example:
 WSqlDatabase db;
 if (!db.open()) 
    dosomeerror();
 if (!db.query(std::string("select foo from bar")))
    dosomeerror();
 WSqlResult *result = db.getResult();
 //WSqlResult *result2 = db.getResult(); <- wrong 
 //...iterate over results ..._then repeat:
 if (!db.query(std::string("select baz from bar")))
    dosomeerror();
 WSqlResult *result = db.getResult();
 ..etc.
See also:
WSqlResult WSqlRecord WMysqlDriver WSqliteDriver
Parameters:
booliscached - if true (the default) fetches entire result set at once.
Return values:
WSqlResult*- the result set

Definition at line 640 of file wsqldatabase.cpp.

void WSql::WSqlDatabase::setConnectOptions ( const std::string &  options = std::string())

Sets the connection options for this database server.

Sets database-specific options. This must be done before the connection is opened or it has no effect (or you can close() the connection, call this function and open() the connection again).

Note that the options are specific to a database server - drivers should handle this string appropriately.

Parameters:
std::string&options - connection options to pass to the driver.
See also:
getConnectionOptions()

Definition at line 571 of file wsqldatabase.cpp.

void WSql::WSqlDatabase::setDatabaseName ( const std::string &  name)

Set the the database name.

Sets the connection's database name to name. To have effect, the database name must be set before opening the connection with open() Alternately, you can close() the connection, set the database name, and call open() again There is no default value.

Parameters:
std::stringname - the name of the database
See also:
databaseName()

Definition at line 292 of file wsqldatabase.cpp.

void WSql::WSqlDatabase::setDriver ( WSqlDriver d) [inline]

Definition at line 76 of file wsqldatabase.h.

void WSql::WSqlDatabase::setDriverType ( WSql::DriverType  t)
void WSql::WSqlDatabase::setHostName ( const std::string &  hostname)

Sets the connection's host name.

This method sets the connection's host name to hostname. To have effect, the host name must be set before opening the connection with open() Alternately, you can close() the connection, set the host name, and call open() again.

There is no default value.

Parameters:
std::stringhostname - the hostname to use
See also:
hostName() open() close()

Definition at line 342 of file wsqldatabase.cpp.

void WSql::WSqlDatabase::setPassword ( const std::string &  password)

Set the the password.

Sets the connection's password to password. To have effect, the password must be set {before} the connection is {open()} {opened}. Alternatively, you can close() the connection, set the password, and call open() again.

There is no default value.

Parameters:
std::stringpassword - the password to use
See also:
password() open() close()

Definition at line 326 of file wsqldatabase.cpp.

void WSql::WSqlDatabase::setPort ( int  port)

Sets the port number for the connection.

This method sets the connection's port number to port. To have effect, the port number must be set before opening the connection with open() Alternately, you can close() the connection, set the port number, and call open() again

The default value is -1.

See also:
port() open() close()
Parameters:
intport number to use

Definition at line 359 of file wsqldatabase.cpp.

void WSql::WSqlDatabase::setUserName ( const std::string &  name)

Set the the user name.

Sets the connection's user name to name. To have effect, the user name must be set before opening the connection with open() Alternately, you can close() the connection, set the user name, and call open() again.

There is no default value.

Parameters:
std::stringname - the name of the user
See also:
userName() open() close()

Definition at line 309 of file wsqldatabase.cpp.

WSqlTable WSql::WSqlDatabase::tableMetaData ( const std::string &  tablename) const

Fetch metadata for table tableName.

This method returns a WSqlTable object populated with WSqlColumns that contain metadata for the columns in the given table tableName. Example:

    meta_table = db.tableMetaData(*it);
    numflds = meta_table.count();
    for (int i=0; i < numflds; ++i) 
    {
        WSql::WSqlColumn column = meta_table.column(i);
        
        std::cout << "Column " << i << " = " << column.columnName() << std::endl;
        std::cout << "  * Data type: " << WSql::WSqlDataType::toString(column.dataType()) << std::endl;
        std::cout << "  * Max Length:  " << column.maxLength() << std::endl;
        std::cout << "  * Unsigned:  " << (column.isUnsigned() ? "true" : "false") << std::endl;
        std::cout << "  * Can be null:  " << (column.canBeNull() ? "true" : "false") << std::endl;
        std::cout << "  * Primary key:  " << (column.isPrimaryKey() ? "true" : "false") << std::endl;
        std::cout << "  * Autoincrement:  "  << (column.isAutoIncremented()?"true" : "false") << std::endl;
        std::cout << "  * default value:  "  << column.defaultValue<std::string>() << std::endl;
 }
Warning:
If the table metadata has not been initialized yet this method will invalidate any previous WSqlResult pointer returned - in this case nesting calls to this method inside of a loop iterating over WSqlResults WILL NOT WORK. Obtain the WSqlTable first and then query() a query and fetch the result set using getResult() or use initMetaData() to initialize the metadata for all tables at once.
Parameters:
stringthe name of the table to use
Return values:
WSqlTablean object containing metadata
See also:
WSqlTable WSqlColumn

Definition at line 509 of file wsqldatabase.cpp.

const std::vector< std::string > & WSql::WSqlDatabase::tableNames ( WSql::TableType  type = WSql::Tables)

Returns a vector of the database's table names.

Returns all the errors that have occurred on the database or in the driver as a vector of strings.

Todo:
.. decide if we use this ..
See also:
WSqlError

This function returns a vector of strings containing the names tables and views as specified by the parameter type. The vector is cached for quick reference - if empty it is initialized by a request to the driver for the names. If the names are not available an empty vector is returned.

Warning:
If the table metadata has not been initialized yet this method will invalidate any previous WSqlResult pointer returned - in this case nesting calls to this method inside of a loop iterating over WSqlResults WILL NOT WORK. Obtain the WSqlTable first and then query() a query and fetch the result set using getResult() or use initMetaData() to initialize the metadata for all tables at once.
Todo:
Use the table type - currently does nothing.
See also:
WSql::TableType
Parameters:
WSql::TableType
Return values:
std::vector<std::string>&- the table names in this database

Definition at line 467 of file wsqldatabase.cpp.

std::string WSql::WSqlDatabase::userName ( ) const

Returns the connection's user name; it may be empty.

See also:
setUserName()

Definition at line 378 of file wsqldatabase.cpp.


The documentation for this class was generated from the following files:
 All Classes Namespaces Files Functions Variables Enumerations Enumerator Friends Defines