Unable to set user_version in SQLite - c++

I am trying to use the user_version feature of an SQLite database. I am unable to actually set the user_version and I am not sure why. I have tried various ways of executing a query to update the user_version, and have searched extensively online and am now at a total loss.
Here is my query string.
const std::string kSetUserVersion = "PRAGMA user_version = 1;";
And here is where I am trying to set the user_version, however my result is still 0.
// Set the user version and check it is correct.
sqlite3_exec(dbConnection->db_handle, kSetUserVersion.c_str(), nullptr, nullptr, &db_err); // <-- this is not working!
long currentVersion = sqlite3_exec(dbConnection->db_handle, kGetUserVersion.c_str(), nullptr, nullptr, &db_err);
// If the PRAGMA statement fails, no error returns and it fails silently, so having to add check to see if it has worked.
if (currentVersion != 1) // Setting the user_version has failed.
{
throw DatabaseAccessException(sqlite3_errmsg(dbConnection->db_handle));
}
Any help is much appreciated.

sqlite3_exec() return value is a status/error code and not the value from your query.
To get the query result value, there are two primary options:
Use sqlite3_prepare_v2(), sqlite_step() for SQLITE_ROW and access the data with e.g. sqlite3_column_int(), finalizing the prepared query with sqlite3_finalize().
Supply a callback function as the third argument to your sqlite3_exec() to capture the value. See e.g. here for example: Proper use of callback function of sqlite3 in C++

Related

Understanding NiFpga_MergeStatus() function with a hard-coded value as a parameter

I am picking up on someone else's code (which works and is currently being used in hardware applications). The given code is implemented in Qt since we need to produce an application, and creates an application which allows the user to set certain parameters using a gui while the code handles transferring this command through a NI PXI to the FPGAs etc.
On my way of understanding this code, I found a function call to NiFpga_MergeStatus() shown in the code below. The parameter passed as the first argument has been hardcoded and set to NiFpga_Status_Success (which if you follow the path is a static const NiFpga_Status type set to the the value 0.
When looking at the NiFpga_MergeStatus() function implementation, I believe with this value being hardcoded, we will never get to the second if statement and our return value will be the Invalid Parameter value.
Why would somebody want to implement such code? Especially since the second parameter is sent it seems to have had some thought put into this. Am I wrong in analyzing that with harcoding the status parameter before it's passed as an argument we will always execute the first if statement? Let me know if I should provide more details. The header file is provided by Ni (NiFpga.h).
Thank you
NiFpga description of this function's purpose:
* Conditionally sets the status to a new value. The previous status is
* preserved unless the new status is more of an error, which means that
* warnings and errors overwrite successes, and errors overwrite warnings. New
* errors do not overwrite older errors, and new warnings do not overwrite
* older warnings.
*
* #param status status to conditionally set
* #param newStatus new status value that may be set
* #return the resulting status
static NiFpga_Inline NiFpga_Status NiFpga_MergeStatus(
NiFpga_Status* const status,
const NiFpga_Status newStatus)
{
if (!status) //
return NiFpga_Status_InvalidParameter;
if(NiFpga_IsNotError(*status)
&& (*status == NiFpga_Status_Success || NiFpga_IsError(newStatus)))
*status = newStatus;
return *status;
}
Status is a pointer parameter. In first if statement (if (!status)) it is only checking if the pointer is actually pointing to something in memory or not. So in your case it always evaluates to false and return NiFpga_Status_InvalidParameter; never gets called.
But second if statement is doing the job of comparing actual value (note the asterisk *) of status (*status) with NiFpga_Status_Success.

Get query from sqlite3_stmt of SQLite in c/cpp [duplicate]

I'm using SQLite (3.6.4) from a C++ application (using the standard C api). My question is: once a query has been prepared, using sqlite3_prepare_v2(), and bound with parameters using sqlite3_bind_xyz() - is there any way to get a string containing the original SQL query?
The reason is when something goes wrong, I'd like to print the query (for debugging - this is an in-house developer only test app).
Example:
sqlite3_prepare_v2(db, "SELECT * FROM xyz WHERE something = ? AND somethingelse = ?", -1, &myQuery, NULL);
sqlite3_bind_text(myQuery, 1, mySomething);
sqlite3_bind_text(myQuery, 2, mySomethingElse);
// ....
// somewhere else, in another function perhaps
if (sqlite3_step(myQuery) != SQLITE_OK)
{
// Here i'd like to print the actual query that failed - but I
// only have the myQuery variable
exit(-1);
}
Bonus points if it could also print out the actual parameters that was bound. :)
You probably want to use sqlite3_trace
This will call a callback function (that you define) and on of the parameters is a char * of the SQL of the prepared statements (including bound parameters).
As per the comments in sqlite3.c (amalgamation), sqlite3_sql(myQuery) will return the original SQL text.
I don't see any function for finding the value bound at a particular index, but we can easily add one to the standard set of SQLite functions. It may look something like this:
const char* sqlite3_bound_value(sqlite3_stmt* pStmt, int index)
{
Vdbe *p = (Vdbe *)pStmt;
// check if &p->aVar[index - 1] points to a valid location.
return (char*)sqlite3ValueText(&p->aVar[index - 1], SQLITE_UTF8);
}
Well, the above code shows only a possible way sqlite3_bound_value() could be implemented. I haven't tested it, it might be wrong, but it gives certain hints on how/where to start.
Quoting the documentation:
In the "v2" interfaces, the prepared statement that is returned (the sqlite_stmt object) contains a copy of the original SQL text.
http://www.sqlite.org/c3ref/prepare.html

ADO Command saying that I am inserting NULL, when I'm not

I'm using ADO to communicate with my Sybase server..
This is how I'm executing a simple command:
_ConnectionPtr m_ConnPtr;
//... Instantiate connection
_CommandPtr m_CommPtr;
m_CommPtr->CreateInstance(__uuidof(Command))
m_CommPtr->ActiveConnection = m_ConnPtr;
Variant m_variant;
m_variant.SetString("My Param Value");
_ParameterPtr ParamPtr;
ParamPtr = m_CommPtr->CreateParameter("#StrParam", (DataTypeEnum) m_variant.vt, adParamInput, NULL, m_variant);
m_CommPtr->Parameters->Append(PrmPtr);
m_CommPtr->CommandText = "EXECUTE my_stored_procedure #StrParam";
m_CommPtr->Execute(NULL, NULL, adOptionUnspecified);
#StrParam is supposed to be a VarChar type..
Running this gives me an error:
Attempt to insert NULL value into column 'StrParam'. table 'MYTABLE';
column does not allow nulls. Update fails.
I'm not sure why I'm getting this error, since I am specifiying its value ("My Param Value")..
Does anyone know what I'm doing wrong?
(I didn't include the Stored procedure,, because I'm sure there's nothing wrong with the procedure itself.. Other application using the same procedure works fine. So there must be something wrong with how I'm using the parametized command)
I have no clue what your Variant class even is. But the traditional variant type (vt) and the ADO data type are not synonymous. Second, you're not setting up the call nor parameters correctly for a typical stored-proc invoke.
Below is how you would do this using a standard stored proc call and variant_t from the comutil library:
_CommandPtr m_CommPtr(__uuidof(Command));
m_CommPtr->ActiveConnection = m_ConnPtr;
m_CommPtr->CommandType = adoCmdStoredProc;
m_CommPtr->CommandText = L"my_stored_procedure";
// setup parameter
variant_t vParam = L"My Param Value";
_ParameterPtr ParamPtr = m_CommPtr->CreateParameter(L"#StrParam", adBSTR, adParamInput, 0, vParam);
m_CommPtr->Parameters->Append(ParamPtr);
m_CommPtr->Execute(NULL, NULL, adOptionUnspecified);
Note that the ParamPtr is generally optional and you can straight-away append the parameter to the command's Parameters collection if you don't need it for anything else, like this:
m_CommPtr->Parameters->Append(m_CommPtr->CreateParameter(
L"#StrParam", adBSTR, adParamInput, 0, vParam));
The method you're using is common for parameters that are both input and output, as you retain the parameter object reference to extract the output side of the parameter. I see no evidence of that in your call, which is the only reason I mention it here.
Also note that unless the command returns rows for a result set you should also invoke with adExecuteNoRecords for the execution third option (which is typical for many fire-and-forget stored procedure executions)
Finally, the names of the parameters are not important unless you use the NamedParameters property of the command object. This is commonly done when you have additional parameters with default values that you would like to retain, setting only specific parameters as part of your append list.
Best of luck.

OpenLDAP API Search

I'm attempting to do an LDAP search using the OpenLDAP API. I've already successfully connected and bound to the server. I've done the search with ldap_search_ext_s() and parsed the result with ldap_parse_result(). However, I can't seem to figure out how to get the actual results of the search. Unfortunately, the OpenLDAP C API has changed recently and many of the existing examples on the Internet do not use the current API.
I've already attempted to use ldap_first_attribute(), ldap_next_attribute(), and ldap_get_values() as shown on http://www-archive.mozilla.org/directory/csdk-docs/search.htm (Example 6-13). However, it appears that ldap_get_values() is now deprecated and that ldap_get_values_len() is the closest replacement. Instead of returning a char**, the new function returns a berval**. I've attempted to tweak this example code by creating a berval* with the value of barval**[i]. This results in a successful compile, but a core dump at ber_scanf().
Does anyone know how to get the results of an LDAP search with the OpenLDAP C API?
UPDATE:
In particular, I'm asking how to get the attributes requested from the search message.
The result of a search request always contains a series of SearchResultEntry or SeachResultReference messages, this series terminated by a SearchResultDone message. Calling getNextAttribute (in any language and in any API) makes no sense whatever because the search results are a list of messages. An API should package the array of entries or references in such a way wherein the caller can simply retrieve the list of entries or references. Look for a method that does that.
After taking a look at the OpenLDAP API source code and seeing how the berval value was used, I eventually stumbled upon how to get it's value.
First, you have to get the first entry with ldap_first_entry(). Then, you need to get the first attribute in that entry with ldap_first_attribute(). Then, put the values in a berval** array with ldap_get_values_len(). The returned attribute values can then be access with berval[i]->bv_val.
You can get the next entries and attributes with ldap_next_entry() and ldap_next_attribute(), respectively.
I hope this helps anyone who has a similar issue.
hope the bellow function may help you,
int ldap_search_result(LDAP *ld, char *search_filter, char *search_base)
{
LDAPMessage *result;
BerElement *ber;
char *attr;
char **val;
if(ldap_search_ext_s(ld, search_base, LDAP_SCOPE_CHILDREN,
search_filter, NULL, 0, NULL, NULL, NULL, -1, &result) != LDAP_SUCCESS) {
return -1;
}
if(ldap_count_entries(ld,result) != 1) { // assuming search_filter is unique,
// matches only one entry, and so
// search routine returns only one entry
return -1;
}
if((attr = ldap_first_attribute(ldp, result, &ber)) == NULL) {
return -1;
}
do {
if((val = ldap_get_values(ldp,result,attr)) == NULL) {
return -1;
}
printf(" %s : %s \n", attr, val[0]); // assuming all attributes are single -
//valued.
ldap_memfree(attr);
ldap_value_free(val);
while((attr = ldap_next_attribute(ld,result,ber)) != NULL);
return 0;
}

Get original SQL query from prepared statement in SQLite

I'm using SQLite (3.6.4) from a C++ application (using the standard C api). My question is: once a query has been prepared, using sqlite3_prepare_v2(), and bound with parameters using sqlite3_bind_xyz() - is there any way to get a string containing the original SQL query?
The reason is when something goes wrong, I'd like to print the query (for debugging - this is an in-house developer only test app).
Example:
sqlite3_prepare_v2(db, "SELECT * FROM xyz WHERE something = ? AND somethingelse = ?", -1, &myQuery, NULL);
sqlite3_bind_text(myQuery, 1, mySomething);
sqlite3_bind_text(myQuery, 2, mySomethingElse);
// ....
// somewhere else, in another function perhaps
if (sqlite3_step(myQuery) != SQLITE_OK)
{
// Here i'd like to print the actual query that failed - but I
// only have the myQuery variable
exit(-1);
}
Bonus points if it could also print out the actual parameters that was bound. :)
You probably want to use sqlite3_trace
This will call a callback function (that you define) and on of the parameters is a char * of the SQL of the prepared statements (including bound parameters).
As per the comments in sqlite3.c (amalgamation), sqlite3_sql(myQuery) will return the original SQL text.
I don't see any function for finding the value bound at a particular index, but we can easily add one to the standard set of SQLite functions. It may look something like this:
const char* sqlite3_bound_value(sqlite3_stmt* pStmt, int index)
{
Vdbe *p = (Vdbe *)pStmt;
// check if &p->aVar[index - 1] points to a valid location.
return (char*)sqlite3ValueText(&p->aVar[index - 1], SQLITE_UTF8);
}
Well, the above code shows only a possible way sqlite3_bound_value() could be implemented. I haven't tested it, it might be wrong, but it gives certain hints on how/where to start.
Quoting the documentation:
In the "v2" interfaces, the prepared statement that is returned (the sqlite_stmt object) contains a copy of the original SQL text.
http://www.sqlite.org/c3ref/prepare.html