Format SQL query in c++ - c++

I was wondering if there is something I can use in C++ similar to "sqlparse" module in Python to format my query. Do you know what can I use?
I'm sorry for didn't provide an example before.
I want that something like this:
SELECT MEMB.NAME, MEMB.AGE, AGE.GROUP FROM MEMB, AGE WHERE MEMB.AGE = AGE.AGE
Become this:
SELECT MEMB.NAME,
MEMB.AGE,
AGE.GROUP
FROM MEMB,
AGE
WHERE MEMB.AGE = AGE.AGE
Thanks a lot.

You can write your own pretty printer. In that case, it won't be any hard. Just replace things like the following:
"FROM" -> "\nFROM"
"WHERE" -> "\nWHERE"
"," -> ",\n\t"
"AND" -> "AND\n\t"
"OR" -> "OR\n\t"
etc.
Edit: as you don't code, here's a little version of this functionality.
#include <string>
using std::string; /* put these lines in the top of your file */
string replace(string a, string b, string c) {
unsigned x;
for(x = a.find(b); x != string::npos;) {
a.erase(x, b.length());
a.insert(x, c);
}
return a;
}
string formatSQL(string sql) {
replace(sql, "FROM", "\nFROM");
replace(sql, "WHERE", "\nWHERE");
replace(sql, "," , ",\n\t");
replace(sql, "AND", "AND\n\t");
replace(sql, "OR", "OR\n\t");
}
So calling formatSql("SELECT MEMB.NAME, MEMB.AGE, AGE.GROUP FROM MEMB, AGE WHERE MEMB.AGE = AGE.AGE") gives you the desired result.

Related

Equivalent of mysql_real_escape_string()

In MySQL there is the mysql_real_escape_string function.
Is there an such for MS SQL to correctly handle strings like this one?
SELECT * FROM MyTable WHERE Phrase='Mr Charlie's dog's dog and Mrs Molly's cat's cat plus Chris' bicycle' AND Item='wood';
I use Microsoft SQL
#include <sqlext.h>
#include <sqltypes.h>
#include <sql.h>
Rather than composing a query as a string, write a parameterised query and supply whatever string as the parameter.
You don't say what sql library you use, but it'd look something like this
void prepare_find(pqxx::connection_base &c)
{
c.prepare(
"find",
"SELECT * FROM MyTable WHERE Phrase = $1 AND Item = $2");
}
pqxx::result execute_find(
pqxx::transaction_base &t, std::string phrase, std::string item)
{
return t.exec_prepared("find", phrase, item);
}

cfscript and queryExecute() using like instead of equals

I'm curious if this is the correct method to use the like operator when using queryExecute() in a cfscript function.
if( len(arguments?.lastName) ){
local.sqlWhere & = " AND t_lastname LIKE :lName";
local.sqlParams.lName = { value : arguments.lastName & '%', cfsqltype:'cf_sql_varchar'};
};
Is it just appended like a string with & '%'?
I've just go through your issue. In coldfusion & symbol always concatenation the two string. So we could not able to use like that. Here I've wrote some sample code for you please check that. I hope it will more help full to wrote a script based query.
local.MyQry = "SELECT * FROM Users WHERE 1=1 ";
I've used same condition from you. Not sure about your conditions
if( len(arguments?.lastName) ){
local.MyQry &= " AND Email like :email"
}
Here concatenate the query with previous one if the condition is true. And mentioned :(colon as we are going to use as queryparam)
local.qry = new Query( datasource = 'your DB name' , sql = Local.MyQry);
if( len(arguments?.lastName) ){
local.qry.addParam( name="email", value="%#Arguments.email#%", cfsqltype="cf_sql_varchar");
}
return local.qry.execute();
You can give the % symbol here based on your scenario . Ex %#Arguments.email#. or %#Arguments.email#%
I hope this will help you more. Thanks

Creating json string using json lib

I am using jsonc-libjson to create a json string like below.
{ "author-details": {
"name" : "Joys of Programming",
"Number of Posts" : 10
}
}
My code looks like below
json_object *jobj = json_object_new_object();
json_object *jStr1 = json_object_new_string("Joys of Programming");
json_object *jstr2 = json_object_new_int("10");
json_object_object_add(jobj,"name", jStr1 );
json_object_object_add(jobj,"Number of Posts", jstr2 );
this gives me json string
{
"name" : "Joys of Programming",
"Number of Posts" : 10
}
How do I add the top part associated with author details?
To paraphrase an old advertisement, "libjson users would rather fight than switch."
At least I assume you must like fighting with the library. Using nlohmann's JSON library, you could use code like this:
nlohmann::json j {
{ "author-details", {
{ "name", "Joys of Programming" },
{ "Number of Posts", 10 }
}
}
};
At least to me, this seems somewhat simpler and more readable.
Parsing is about equally straightforward. For example, let's assume we had a file named somefile.json that contained the JSON data shown above. To read and parse it, we could do something like this:
nlohmann::json j;
std::ifstream in("somefile.json");
in >> j; // Read the file and parse it into a json object
// Let's start by retrieving and printing the name.
std::cout << j["author-details"]["name"];
Or, let's assume we found a post, so we want to increment the count of posts. This is one place that things get...less tasteful--we can't increment the value as directly as we'd like; we have to obtain the value, add one, then assign the result (like we would in lesser languages that lack ++):
j["author-details"]["Number of Posts"] = j["author-details"]["Number of Posts"] + 1;
Then we want to write out the result. If we want it "dense" (e.g., we're going to transmit it over a network for some other machine to read it) we can just use <<:
somestream << j;
On the other hand, we might want to pretty-print it so a person can read it more easily. The library respects the width we set with setw, so to have it print out indented with 4-column tab stops, we can do:
somestream << std::setw(4) << j;
Create a new JSON object and add the one you already created as a child.
Just insert code like this after what you've already written:
json_object* root = json_object_new_object();
json_object_object_add(root, "author-details", jobj); // This is the same "jobj" as original code snippet.
Based on the comment from Dominic, I was able to figure out the correct answer.
json_object *jobj = json_object_new_object();
json_object* root = json_object_new_object();
json_object_object_add(jobj, "author-details", root);
json_object *jStr1 = json_object_new_string("Joys of Programming");
json_object *jstr2 = json_object_new_int(10);
json_object_object_add(root,"name", jStr1 );
json_object_object_add(root,"Number of Posts", jstr2 );

Create stored procedure from x++

Got myself into trouble today trying to create a stored procedure from ax.
Here is a simple example:
static void testProcedureCreation(Args _args)
{
MyParamsTable myParams;
SqlStatementExecutePermission perm;
str sqlStatement;
LogInProperty Lp = new LogInProperty();
OdbcConnection myConnection;
Statement myStatement;
ResultSet myResult;
str temp;
;
select myParams;
LP.setServer(myParams.Server);
LP.setDatabase(myParams.Database);
//Lp.setUsername("sa");
//Lp.setPassword("sa");
sqlStatement = #"create procedure testproc
as begin
print 'a'
end";
//sqlStatement = strFmt(sqlStatement, myStr);
info(sqlStatement);
perm = new SqlStatementExecutePermission(sqlStatement);
perm.assert();
try
{
myConnection = new OdbcConnection(LP);
}
catch
{
info("Check username/password.");
return;
}
myStatement = myConnection.createStatement();
myResult = myStatement.executeQuery(sqlStatement);
while (myResult.next())
{
temp = myResult.getString(1);
info(temp);
if (strScan(temp, 'Error', 1, strLen(temp)) > 0)
throw error(temp);
}
myStatement.close();
CodeAccessPermission::revertAssert();
}
To be honest, in my real example I am using BCP and some string concat with a lot of | ' and "".
Anyway, here is what I got:
For a couple of hours I kept changing and retrying a lot of things and, a good thought came into my mind.
"Let's try with a much easier example and check the results!"
OK, no luck, the results were the same, as you can see in the pic above.
But for no reason, I tried to :
exec testproc
in my ssms instance and to my surprise, it worked. My small procedure was there.
It would be so nice if someone could explain this behavior and maybe what should be the correct approach.
This Q/A should provide an answer.
How to get the results of a direct SQL call to a stored procedure?
executeQuery vs executeUpdate

Replace expression with subsection using regex?

My IDE PHPstorm allows you to do search and replace using regex, one of the things I find myself often doing is switching the order or action, aka, in function a I will set a value on items from list a using list b as the values.
but then in function b I want to invert it.
so I want to set a value on items from list b using list a as the values.
A proper example is this:
var $clipDetailsGame = $('#clipDetailsGame');
var $clipDetailsTitle = $('#clipDetailsTitle');
var $clipDetailsByline = $('#clipDetailsByline');
var $clipDetailsTeamOne = $('#clipDetailsTeamOne');
var $clipDetailsTeamTwo = $('#clipDetailsTeamTwo');
var $clipDetailsReferee = $('#clipDetailsReferee');
var $clipDetailsDescription = $('#clipDetailsDescription');
var $clipDetailsCompetition = $('#clipDetailsCompetition');
function a(clip){
clip.data('gameId' , $clipDetailsGame.val());
clip.data('title' , $clipDetailsTitle.val());
clip.data('byline' , $clipDetailsByline.val());
clip.data('team1' , $clipDetailsTeamOne.val());
clip.data('team2' , $clipDetailsTeamTwo.val());
clip.data('refereeId' , $clipDetailsReferee.val());
clip.data('description' , $clipDetailsDescription.val());
clip.data('competitionId', $clipDetailsCompetition.val());
}
function b (clip){
$clipDetailsGame .val(clip.data('gameId'));
$clipDetailsTitle .val(clip.data('title'));
$clipDetailsByline .val(clip.data('byline'));
$clipDetailsTeamOne .val(clip.data('team1'));
$clipDetailsTeamTwo .val(clip.data('team2'));
$clipDetailsReferee .val(clip.data('refereeId'));
$clipDetailsDescription.val(clip.data('description'));
$clipDetailsCompetition.val(clip.data('competitionId'));
}
Excluding the formatting (It's just there to make my point clearer), what kind of regex could I use to do the replacement for me?
Basic regex -- nothing fancy or complex at all
Search for: (clip\.data\('[a-zA-Z0-9]+')\s*, (\$[a-zA-Z0-9]+\.val\()(\)\);)
Replace with: \$2\$1\$3
The only PhpStorm-related thing here is replacement string format -- you have to "escape" $ to have it work (i.e. it has to be \$2 to use 2nd back-trace instead of just $2 or \2 (as used in other engines)).
This will transform this:
clip.data('gameId' , $clipDetailsGame.val());
clip.data('title' , $clipDetailsTitle.val());
clip.data('byline' , $clipDetailsByline.val());
clip.data('team1' , $clipDetailsTeamOne.val());
clip.data('team2' , $clipDetailsTeamTwo.val());
clip.data('refereeId' , $clipDetailsReferee.val());
clip.data('description' , $clipDetailsDescription.val());
clip.data('competitionId', $clipDetailsCompetition.val());
into this:
$clipDetailsGame.val(clip.data('gameId'));
$clipDetailsTitle.val(clip.data('title'));
$clipDetailsByline.val(clip.data('byline'));
$clipDetailsTeamOne.val(clip.data('team1'));
$clipDetailsTeamTwo.val(clip.data('team2'));
$clipDetailsReferee.val(clip.data('refereeId'));
$clipDetailsDescription.val(clip.data('description'));
$clipDetailsCompetition.val(clip.data('competitionId'));
Useful link: http://www.jetbrains.com/phpstorm/webhelp/regular-expression-syntax-reference.html
Mopping up (not quite the answer to this question, but another way of organizing the code to make search and replace unnecessary):
var $details = {};
var fields = [
'Game', 'Title', 'Byline', 'TeamOne', 'TeamTwo', 'Referee', 'Description',
'Competition'
];
for(field in fields) {
$details[field] = $('#clipDetails' + field);
}
function a(clip) {
for(field in fields) {
clip.data(field, $details[fields].val());
}
}
function b(clip) {
for(field in fields) {
$details[field].val(clip.data(field));
}
}
Yes, I know that there are tiny naming inconsistencies that means that this isn't working out of the box, such as Game versus gameId. This is an excellent occasion to clean that up too :). If you still want to keep the title case for the ids (such as #clipDetailsGame in stead of #clipDetailsgame), keep it in title case in the fields array and use toLowerCase where you need lower case.
By the way, there is an interesting read on what makes DRY a good thing here: https://softwareengineering.stackexchange.com/questions/103233/why-is-dry-important