diff --git a/doc.html b/doc.html index 8aa81f82..fecef84e 100644 --- a/doc.html +++ b/doc.html @@ -21,38 +21,36 @@ The following documentation and tutorial apply to the original SOCI library, which supports only Oracle databases. Once the library will be ported to support other databases, this page will be redesigned.

-Files
-Errors
-Connecting -to the database
-One-time -statements
-Binding -local data
-Indicators
-Statement -preparation and repeated execution
-Transactions
-Advanced -stuff
+Files
+Errors
+Connecting to the database
+One-time statements
+Binding local data
+   Binding output data
+   Binding input data
+   Binding by position
+   Binding by name
+   Types
+      Static type binding
+      Dynamic resultset binding
+      Extending with user-provided datatypes
+Indicators
+Statement preparation and repeated execution
+Transactions
+Advanced stuff
+Rationale for some design decisions

-

Files

+

Files

The whole SOCI library consists of only two files: soci.h and soci.cpp. The first needs to be #included in your own code and the second should be just added to the whole project for compilation and linking. There was no reason to make a precompiled library out of this single file.

Everything in SOCI is declared in the namespace SOCI. -All the following examples assume that your code begins with something +All code examples presented in this documentation assume that your code begins with something like:

#include "soci.h"
// other includes

using namespace SOCI;

// ...
-

Errors

+

Errors

All DB-related errors manifest themselves as exceptions of type SOCIError, which is derived from std::runtime_error. This allows to handle Oracle errors within the standard exception framework:

@@ -62,7 +60,7 @@ member, which contains the Oracle error code. Of course, in order to access this code you have to catch the exception as SOCIError:

int main()
{
try
{
// regular code
}
catch (SOCIError const &e)
{
cerr << "Oracle error: " << e.errNum_
<< " " << e.what() << endl;
}
catch (exception const &e)
{
cerr << "Some other error: " << e.what() << endl;
}
}
-

Connecting to the database

+

Connecting to the database

The class Session encapsulates the database connection and other OCI-related details, which are common to all the statements that will be later executed. Its constructor expects three string @@ -72,7 +70,7 @@ parameters, which are service name, user name and password:

exception. It is possible to have many active Sessions at the same time.

-

One-time statements

+

One-time statements

In many cases, the SQL query is intended to be executed only once, which means that statement parsing and execution can go together. The Session class provides a special once @@ -87,18 +85,18 @@ statement text can be composed of many parts, involving anything that is streamable (including custom classes, if they have appropriate operator<<):

string tableName = "person";
sql << "drop table " << tableName;
-

Binding local data

+

Binding local data

Note:
The Oracle documentation uses two terms: defining (for instructing the library where the output data should go) and binding (for the input data and input/output PL/SQL parameters). For the sake of simplicity, SOCI uses the term binding for both of these.

-

Binding output data:

+

Binding output data:

The into expression is used to add binding info to the statement:

int count;
sql << "select count(*) from person", into(count);

string name;
sql << "select name from person where id = 7", into(name);
-

Binding input data:

+

Binding input data:

The use expression is used (no pun intended) to associate the SQL placeholder (written with colon) with the local data:

@@ -110,7 +108,7 @@ placeholder and its name is ignored here, and the third "val" is a name of local variable.
To better understand the meaning of each "val" above, consider also:

int number = 7;
sql << "insert into numbers(val) values(:blabla)", use(number);
-

Binding by position

+

Binding by position

If there is more output or input "holes" in the single statement, it is possible to use many into and use expressions, separated by commas, where each expression will be @@ -119,14 +117,16 @@ responsible for the consecutive "hole" in the statement:

In the code above, the order of "holes" in the SQL statement and the order of into and use expression should match.

-

Binding by name

+

Binding by name

The SQL placeholders that have their names (with colon) can be bound by name.
This allows to use different order:

string firstName = "John", lastName = "Smith";
int personId = 7;
sql << "insert into person(id, firstname, lastname) values(:id, :fn, :ln)",
use(firstName, "fn"), use(lastName, "ln"), use(personId, "id");

or bind the same local data to many "holes" at the same time:

string addr = "...";
sql << "update person"
" set mainaddress = :addr, contactaddress = :addr"
" where id = 7",
use(addr, "addr);
-

Types:

+

Types:

+

Static type binding

+

The static binding for types is most useful when the types used in the database are known at compile time - this was already presented with the help of into and use functions.

The following types are currently supported for use with into and use expressions:

+

See the test code that accompanies the library to see how each of these types is used.

-

The library can be extended to support other types (including -user-defined classes). The extension points are the IntoType<T> + +

Dynamic resultset binding

+

For certain applications it is desirable to be able to select data from arbitrarily +structured tables (e.g. via "select * ") and format the resulting data based upon its type. +SOCI supports this through the SOCI::Row and SOCI::ColumnProperties classes.

+

+Data is selected into a Row object, which holds ColumnProperties objects describing +the type of data contained in each column. Once the data type for each column is known, +the data can be formatted appropriately. +

+

+For example, the code below creates an xml document from a selected row of data from an arbitrary table: +

+
+Session sql("db1", "scott", "tiger");
+  
+sql << "create table ex2(num NUMBER, str VARCHAR2(20), dt DATE)";
+
+int num_in = 123;
+std::string str_in("my name");
+std::time_t dt_in = time(0);
+
+sql << "insert into ex2 values(:num1, :str1, :dt1)",
+    use(num_in), use(str_in), use(dt_in);
+    
+Row r;
+sql << "select * from ex2", into(r);
+  
+std::ostringstream doc;
+doc << "<row>" << std::endl;
+for(int i=0; i<r.size(); ++i)
+{
+    const ColumnProperties& props = r.getProperties(i);
+    doc << '<' << props.getName() << '>';
+    switch(props.getDataType())
+    {
+    case eString:
+        doc << r.get<std::string>(i);
+        break;
+    case eDouble:
+        doc << r.get<double>(i);
+        break;
+    case eInteger:
+        doc << r.get<int>(i);
+        break;
+    case eUnsignedLong:
+        doc << r.get<unsigned long>(i);
+        break;
+    case eDate:
+        std::tm when = r.get<std::tm>(i);
+        doc << asctime(&when);
+        break;
+    }
+    doc << "</" << props.getName() << '>' << std::endl;  
+}
+doc << "</row>";
+
+ +

+The following table shows the type T parameter that should be passed to +Row::get<T>() for each possible SOCI Data Type that can be returned from +ColumnProperties::getDataType(). Row::get<T>() throws an exception of type +std::bad_cast if an incorrect type T is used. +

+ + + + + + + + +
Oracle Data TypeSOCI Data TypeRow::get<T> specializations
NUMBEReDoubledouble
NUMBEReIntegerint
NUMBEReUnsignedLongunsigned long
CHAR, VARCHAR, VARCHAR2eStringstd::string
DATEeDatestd::tm, std::time_t
+ +

Extending SOCI to support custom (user-defined) C++ types

+ +

SOCI can be easily extended through user code so that custom types can +be used transparently to insert into, update, and select from the database.

+ +

To do so, provide an appropriate implementation of the TypeConversion class +that converts to and from one of the SOCI Base Types listed below:

+ + + + + + + + + +
Oracle Data TypeSOCI Base Type
NUMBERdouble
NUMBERint
NUMBERunsigned long
VARCHAR, VARCHAR2std::string
CHARchar
DATEstd::tm
+ +

+For example, SOCI's built in support for std::time_t is implemented entirely +as follows, utilizing std::tm as the Base Type:

+ +
+namespace SOCI
+{
+  template<>
+  class TypeConversion<std::time_t> 
+  {
+  public:
+      typedef std::tm base_type;
+      static std::time_t from(std::tm& t){return mktime(&t);}
+      static std::tm to(std::time_t& t){return *localtime(&t);}
+  };
+}
+
+ +

+There are three required class members for a valid TypeConversion specialization:

+ +

(Note that no database-specific code is required.)

+

+The following example shows how application code could extend SOCI to transparently support boost::gregorian::date:

+ +
+#include "boost/date_time/gregorian/gregorian.hpp"
+namespace SOCI
+{
+template<>
+class TypeConversion<boost::gregorian::date>
+{
+public:
+    typedef std::tm base_type;
+    static boost::gregorian::date from(std::tm& t)
+    {
+        boost::gregorian::months_of_year month = 
+            static_cast<boost::gregorian::months_of_year>(t.tm_mon + 1);
+        
+        boost::gregorian::date d(t.tm_year + 1900, month, t.tm_mday);
+        return d;
+    }
+    static std::tm to(boost::gregorian::date& d)
+    {
+        std::tm t;
+        t.tm_year = d.year() - 1900;
+        t.tm_mon = d.month() - 1;
+        t.tm_mday = d.day();
+        t.tm_hour = 0;
+        t.tm_min = 0;
+        t.tm_sec = 0;
+        std::mktime(&t); //normalize and compute remaining fields
+          
+        return t;
+    }
+};
+} // namespace SOCI
+
+ +With the above TypeConversion specialization in place, it is possible to +use boost::gregorian::date directly with SOCI, binding input or output, either +statically or via a dynamic resultset: + +
+using boost::gregorian::date;
+    
+Session sql("db1", "scott", "tiger");
+
+sql << "create table test_boost(when DATE)";
+date d_in(1999, boost::gregorian::Feb, 10);
+
+sql << "insert into test_boost values(:when)", use(d_in);
+    
+date d_out(boost::gregorian::not_a_date_time);
+  
+sql << "select when from test_boost", into(d_out);
+assert(d_in == d_out);
+
+Row r;
+sql << "select * from test_boost", into(r);
+assert(r.get<date>(0) == d_in);
+
+ +

The other possibility to extend SOCI with custom data types is to use the IntoType<T> and UseType<T> class templates, which specializations can be user-provided. These specializations need to implement the interface defined by, @@ -158,7 +337,8 @@ of appropriate class. The only convention is that when the indicator variable is used (see below), it should appear in the second position. Please refer to the library source code to see how this is done for the standard types.

-

Indicators

+ +

Indicators

In order to support null values and other conditions which are not real errors, the concept of indicator is provided.
For example, when the following SQL query is executed:

@@ -187,8 +367,9 @@ overrided to be null:

int id = 7;
string name;
eIndicator ind = eNull;
sql << "insert into person(id, name) values(:id, :name)",
use(id), use(name, ind);

In the above example, the row is inserted with name attribute set to null.

-

Statement preparation and repeated -execution

+ +

Statement preparation and repeated +execution

Consider the following examples:

// Example 1.
for (int i = 0; i != 100; ++i)
{
sql << "insert into numbers(value) values(" << i << ")";
}

// Example 2.
for (int i = 0; i != 100; ++i)
{
sql << "insert into numbers(value) values(:val)", use(i);
}

Both examples will populate the table numbers with the @@ -213,12 +394,14 @@ with the default parameter 0. The following fetch calls perform the actual data retrieval and cursor traversal. The end-of-cursor condition is indicated by the fetch function returning false.

-

Transactions

+ +

Transactions

The Session class provides two methods for transaction processing: commit and rollback. The transaction is implicitly started with the first statement that modifies data in the database.

-

Advanced stuff

+ +

Advanced stuff

If there is any need to use more advanced features of the underlying OCI library (special connection steps, attribute manipulation, call-back functions, etc.), it can be done by accessing the low-level @@ -226,9 +409,9 @@ OCI handles available as public (see rationale below) members of the Sessi and Statement classes. Please refer to the soci.h file to see exactly what handles are available.

-

Rationale for some design decisions

-

Since public data members are considered harmful amongst C++ -programmers, some explanation is in order to defend SOCI against + +

Rationale for some design decisions

+

Since public data members are considered harmful in the C++ community, some explanation is in order to defend SOCI against anticipated criticism. The intent is to allow reading, writing and object modifications through the low-level OCI handles, to enable experienced programmers to @@ -244,7 +427,7 @@ real benefits. The only argument for providing getter/setter abstractions would be to allow future replacements of low-level OCI handles with "something else", but the reality is that OCI handles exist in a specific family and that "something else" (like handles for -database other than Oracle) would not map into those abstrations. +database other than Oracle) would not map into those abstractions. Porting the SOCI library to support other databases would require to change not only low-level handles, but also the getter/setter pairs, which would then prove to be not really abstract. Uff...