Multithreading using C++ and Pro*C - c++

We want to write a multi-threading application using C++ and Pro*c. I have written classes for spawning the threads and doing business logic. I am facing an issue while connecting to the database using Pro*C.
I don't see any way to write Pro*C code to get the SQL context back to the C++ layer and assign it to a thread. I searched google for examples and I see the entire threading logic being embedded in the Pro*C layer.
I am trying to code like below.
void getSqlContext(const char* userName, const char* password)
{
/*
declaring the variables.
sql_context ctx1;
*/
/*Enabling threads in proc.
opening a connection
*/
/*
returning sql_context
*/
}

Related

Mysql Connector connect() issues

I have a small C++ project and need to access a mySQL DB from it, so i have setup mySQL Connector for C++.
This is done on OS X 10.10, and i got no problems with the compilation/linking.
I have written a class for all the mysql stuff, and in the constructor i want to setup the connection to the db. However, this seems to be kinda hard.
Here is the relevant part from the class:
class mysql{
public:
mysql(std::string server, std::string user, std::string password);
private:
sql::mysql::MySQL_Driver *driver;
sql::Connection *con;
std::string last_error = "";
};
And here the implementation:
mysql::mysql(std::string server, std::string user, std::string password){
driver = sql::mysql::get_mysql_driver_instance();
try{
con = driver->connect(server, user, password);
last_error = "";
}
catch(sql::SQLException &e){
last_error = e.what();
}
}
However, when i create an object of that class like this:
mysql db("tcp://127.0.0.1:3306", "root", "secretsecret");
I then have this in my last_error string:
Unknown MySQL server host '???' (0)
The "host" sometimes differs even tho i dont change it in code. This seems like internally a different memory location is read out as it should be.
But even if i pass the connect() variables directly when i call it, i get this error. Same when saving those three variables internally in the mysql class and use those to call connect().
Anyone has an idea what could cause this? I have a similar implementation in a different project where this does work fine so im kinda confused :/
Here is a post that matches to your circumstances (The C++ connector works on linux and fails on OSX).
With using mysql logging/tracing or running it in debugger, you may be able to gather more information to report to mysql developers. You may have better luck.
After a long time of googeling i found this the most useful link: https://apple.stackexchange.com/questions/251290/weird-behaviour-of-mysql-connector-c-in-osx
Following the hints there, i recompiled the myscl c connector and then the mysql c++ connector (version 1.1.6 cause 1.1.7 caused a json error while compiling).
I also saw in the cmake logs of the c++ connector that Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ was used to compile the library.
So i used that one too for my compilation. It could be that this would work, tho im also including wxwisgeds in my project resulting in this error:
/usr/local/include/wx-3.0/wx/strvararg.h:30:18: fatal error: 'tr1/type_traits' file not found
#include <tr1/type_traits>
I found some hints for that one but they all just produced a massiv amount of new errors, so i stopped digging deeper here.
My best options would be to create two seperate programs, on to communicate with mysql and one to provide the gui and let them both communicate with each other either via sockets or files providing a very inefficient access to a mysql db.
Good luck to anyone who runs into the same thing..

Issuing prepared/parameterized queries through libcouchbase-cxx

I'm brand new to couchbase, and I'm developing a client which needs to issue prepared/parameterized n1ql queries via the c++ client library (https://github.com/couchbaselabs/libcouchbase-cxx). Issuing static queries is straightforward, but I haven't been able to find the correct process for issuing prepared queries. Has anybody been able to do this?
Following doc/example shows how to use the prepared stmt.
http://developer.couchbase.com/documentation/server/4.5/sdk/c/n1ql-queries-with-sdk.html
https://github.com/couchbaselabs/devguide-examples/blob/server-4.5/c/query-placeholders.cc
// To enable using prepared (optimized) statements, you can use
// the LCB_CMDN1QL_F_PREPCACHE flag. This is equivalent to setting
// 'adhoc=False' in other SDKs
cmd.cmdflags |= LCB_CMDN1QL_F_PREPCACHE;
rc = lcb_n1p_mkcmd(params, &cmd);
rc = lcb_n1ql_query(instance, &rows, &cmd);
lcb_wait(instance);
-Prasad

C++ wrapper class SQLite advice

I'm learning C++ and have a question about classes and wrappers. I'm writing an application for a raspberry pi. I have a class called SensorClass whose methods read data from various sensors attached to the board.
class SensorClass {
public:
SensorClass();
virtual ~SensorClass();
int getTemperature();
int getPressue();
;
I want to write the data to a local sqlite database when it is read. On the SQLite website there are a number of wrapper classes.
SQLite wrappers
I'm wondering if I should use one of these to for example insert data into the database when it has been read.
I'm thinking then I would be separating the code and just calling for example the SQLite insert method in the getTemperature() function. Would this be a good idea? Which wrapper should I use?
Example SQlite wrapper class
Alternatively I could hard code the database operations in the getTemperature() method like this.
int SensorClass::getTemperature(){
// read temperature
//insert into database
/* Create SQL statement */
sql = "INSERT INTO DATAPOINTS (Temperature) " \
"VALUES (15); " \
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
}
Thanks for your advice
It would generally be better to separate the two things. i.e. make the sensor class do the job on sensing stuff well and only that.
Then have a separate class that does the job of logging sensor data to the database well. You may find it is better to insert entire rows into the database in one go. And you may also decide that you want to only log data periodically at a fixed sampling rate.
Then in your main application loop / via an event driven timer, you can do measurements and record data as separate steps.
e.g.
void APP_tick(void)
{
SensorValues values = sensors.readValues();
logger.writeValues(values);
}
By separating responsibility, you can then change the logger class out easily - you may end up deciding that you don't want to use a database and would rather just log the data into flat files in order to use less disk space and improve performance.
If using SQLite then you might find it worthwhile using prepared statements to avoid having to compile the SQL query every time you execute it (which is expensive in CPU terms and you are running this on a fairly limited system).

Managing a global DB connection in C++

Is is possible to do the following safely:
I have a C++ library which connects to SQL DB at various points. I would like to have a global connection available at all of these points. Can this be done? IS there a standard pattern for this. I was thinking of storing a connection in a singleton.
Edit:
Suppose I have the following interface for the connection.
class Connection {
public:
Connection();
~Connection();
bool isOpen();
void open();
}
I would like to implement the following interface:
class GlobalConnection {
public:
static Connection & getConnection() {
static Connection conn_;
if (!conn_.isOpen())
conn_.open();
return conn_;
}
private:
GlobalConnection() {};
Connection conn_;
};
I have two concerns with the above. One is that the getConnection is not thread safe and the other is that I'm not sure about the destruction of the static resource. In other words, am I guaranteed that the connection will close (ie its destructor will be called).
For the record, the connection class itself is provided by the SQLAPI++ library (though that's not very relevant).
EDIT 2: After doing some research it seems that while SQLAPI doent directly support pooling it can be used to enable connection pooling through the ODBC facilities via the call
setOption("SQL_ATTR_CONNECTION_POOLING") = SQL_CP_ONE_PER_DRIVER
The documentation says that that this call must be made before the first connection is established. What is the best way to assure this in code with multiple potential call sites for opening a connection. What if this doesn't happen? Will an error be thrown or pooling just wont be enabled.
Also what tools are available for monitoring how many open connections there are to the DB?
A Singleton can solve this in any OO language. In C/C++, you can also use a static variable (in case you don't use a pure-OO coding style).
most client libaries support connection pooling.
so open a new connection will just pick a existing connection from the pool.

simulate socket errors

How to simulate socket errors? (sometimes server or client disconnects because of some socket error and it is impossible to reproduce.)
I was looking for a tool to do this, but I can't find one.
Does anyone know either of a tool or has a code example on how to do this? (C# or C/C++)
Add a wrapper layer to the APIs you're using to access the sockets and have them fail rand() % 100 > x percent of the time.
I had exactly the same problem this summer.
I had a custom Socket class and wanted to test what would happen if read or write threw an exception. I really wanted to mimic the Java mocking frameworks, and I did it like this:
I inherited the Socket class into a FakeSocket class, and created something called a SocketExpectation. Then, in the unit tests, I created fake sockets, set up the expectations and then passed that fake socket to the code I wanted to test.
The FakeSocket had these methods (stripped of unneeded details):
uint32_t write(buffer, length); // calls check
uint32_t read(buffer, length); // calls check
bool matches();
void expect(expectation);
uint32_t check(CallType, buffer, length) const;
They're all pretty straight forward. check checks the arguments against the current expectation and if everything is according to plan, proceeds to perform the SocketExpectation requirement.
The SocketExpectation has this outline (also stripped):
typedef enum { write, read } CallType;
SocketExpectation(CallType type);
SocketExpectation &with_arguments(void *a1, uint32_t a2); // expects these args
SocketExpectation &will_return(uint32_t value);
SocketExpectation &will_throw(const char * e); // test error handling
bool matches();
I added more methods as I needed them. I would create it like this, then pass the fake socket to the relevant method:
fake_socket = FakeSocket();
fake_socket.expect(SocketExpectation(write).with_arguments(....).will_return(...));
fake_socket.expect(SocketExpectation(read).with_arguments(...).will_throw("something"));
My socket code unit tests are probably better described as integration tests as I drive the code under test to connect to a 'mock' remote peer. Since the remote peer is under the control of the test (it's simply a simple client or server) I can have the test cause the remote peer to disrupt the connection in various ways and then ensure that the code under test reacts as expected. It takes a little work to set up, but once you have all the pieces in place it makes it pretty trivial to test most situations.
So, I guess, my suggestion is that rather than attempting to simulate the situations that you're encountering you should understand them and then reliably generate them.