Passing String to Prepared Statement in Golang - string

The idea is I want to update the status and returning the id only if the status is different.
So, I have a prepared statement like this:
var theQuery = `UPDATE process SET status=$1 WHERE status!=$1 AND id=$2 RETURNING id`
Then, I called it with this:
err = statement.QueryRow("set", 12).Scan(&id)
Then there is an error appear like this.
runtime error: invalid memory address or nil pointer dereference
When I tried:
var theQuery = `UPDATE process SET status='$1' WHERE status!='$1' AND id=$2 RETURNING id`
It runs. Then, when I run it again, I am expecting to get no rows, but it still returning the id. It looked like it still updating the rows and ignored the status!='$1' part.
Thank you

So, I just find the solution. Instead of using $1 twice, the prepared statement will received 3 arguments:
var theQuery = `UPDATE process SET status=$1 WHERE status!=$2 AND id=$3 RETURNING id`
Then, I call the prepared statement like this.
status := "set"
err = statement.QueryRow(status, status, 12).Scan(&id)
I know maybe this is not the best approach to solve the problem. But it worked for me.

Related

Cloud Function ArrayRemove not deleting array value, but function runs without error

My cloud function is not deleting value from the array it is suppose to. It gets all the values correctly as I see in my debug console, but the value in the array is still there.
My code statement is as follows:
for (const id of membersUnderStructure){
const ele = context.params.structure;
console.log(`Deleting ${ele} From ${id}`);
await db.collection(`TeamMember`)
.doc(id)
.update({teamStructIds: admin.firestore.FieldValue.arrayRemove(ele)})
I know the problem is with the admin.firestore.... line as if I put a constant value there, it does update fine. My console shows the correct value of 'ele' and 'id' as well, so the values are correct. The function executes 'ok' without any error but does NOT delete the value of 'ele' from the 'teamStructIds' array.
I am not sure what am I doing wrong here?
Solution:
The Array is of 'Number' and it is trying to delete a String of 'ele'.
I just changed to parseInt(context.parama.structure) and it works now.

Node.js - Pass Session Variables to a SQL Server function call

In a MS Teams BOT I have working dialog code to ask a series of questions and return the formatted response back to the user in a session like so:
session.send(`Details: <br/>Question1: ${session.dialogData.Question1} <br/>Question2: ${session.dialogData.Question2} <br/>Question3: ${session.dialogData.Question3}`);
So I know the values I need are in the session variables. Now I want to pass the session variables to an SQL insert function (executeStatement):
var session_username = session.dialogData.username
var session_yesterday = session.dialogData.yesterday
var session_today = session.dialogData.today
var session_obstacles = session.dialogData.obstacles
executeStatement(session_username, session_yesterday, session_today, session_obstacles)
I can pass strings and the function works fine. But when I try to pass the session variables like above or just passing session.dialogData.yesterday for instance, straight into the function all of the code runs fine - no errors are thrown - but the session variables are not inserted and 0 rows are returned.
What is the proper way to pass a session variable? Google has not been kind in this regard. :)
Thank you in advance...
Edit:
So I couldn't sleep and had a (weird) idea. Use the session.send when assigning the values to the variable like so:
session_username = session.send(`${session.dialogData.username}`)
or
session_username = session.send(session.dialogData.username)
It writes to the database but it is an [object Object] value. So how do I get to the actual value? Hmmm...Still looking
Edit 2:
To get at the object value I tried:
session_yesterday = session.dialogData.yesterday.text()
and
session_yesterday = session.dialogData.yesterday.value()
For the 1st attempt, .text() I received the following error:
TypeError: Cannot read property 'text' of undefined
at Array.<anonymous> (C:\Developer\dailyStatus\index.js:96:56)
at C:\Developer\dailyStatus\node_modules\botbuilder\lib\dialogs\WaterfallDialog.js:67:39
at next (C:\Developer\dailyStatus\node_modules\botbuilder\lib\dialogs\WaterfallDialog.js:92:21)
at WaterfallDialog.beforeStep (C:\Developer\dailyStatus\node_modules\botbuilder\lib\dialogs\WaterfallDialog.js:99:9)
at WaterfallDialog.doStep (C:\Developer\dailyStatus\node_modules\botbuilder\lib\dialogs\WaterfallDialog.js:61:14)
at WaterfallDialog.dialogResumed (C:\Developer\dailyStatus\node_modules\botbuilder\lib\dialogs\WaterfallDialog.js:46:14)
at Session.endDialogWithResult (C:\Developer\dailyStatus\node_modules\botbuilder\lib\Session.js:358:28)
at PromptText.Prompt.invokeIntent (C:\Developer\dailyStatus\node_modules\botbuilder\lib\dialogs\Prompt.js:331:21)
at PromptText.Prompt.replyReceived (C:\Developer\dailyStatus\node_modules\botbuilder\lib\dialogs\Prompt.js:147:18)
at Session.routeToActiveDialog (C:\Developer\dailyStatus\node_modules\botbuilder\lib\Session.js:525:24)
/ - ERROR: Cannot read property 'text' of undefined
/ - Session.endConversation()
I was stubbornly trying to access the variables because I KNEW that the information was there.
I tested going back up into the dialog results.response like below and it worked:
session.dialogData.yesterday = session_yesterday = results.response;
It honestly is still a little odd to me that I couldn't just access the variable directly but oh well - lesson learned I guess.
Thank you

firebase equalTo database query command

var ref = db.ref("main")
var usersRef = ref.child("users");
var accountIdVal = 56473;
What datatype is the equalTo query commmand using when I try to search with a variable, like below it does not return the desired result.
usersRef.orderByChild("accountID").equalTo(accountIdVal).once("value",function(snapshot){
//returns all the values in users
});
when the same thing is tried with non referenced value like below it works fine
usersRef.orderByChild("accountID").equalTo(56473).once("value",function(snapshot){
//returns the exact user
});
even when I use accountIdVal.toString() it does not seem to work, am I missing something here?
Hi thanks for the help I figured out the answer it was because I was getting the value of the variable as a Long, it was checking for a Integer and not a string so the datatypes were not matching up.

How to set timeout for NHibernate LINQ statement

I am using Fluent NHibernate for my ORM. In doing so I am trying to use the NHibernate LINQ syntax to fetch a set of data with the power of LINQ. The code I have works and executes correctly with the exception being that a timeout is thrown if it takes longer than roughly 30 seconds to run. The question I have is how do I extend the default 30 second timeout for LINQ statements via NHibernate?
I have already seen the posts here, here, and here but the first two refer to setting the DataContext's Timeout property, which does not apply here, and the third refers to setting the timeout in XML, which also does not apply because I am using Fluent NHibernate to generate the XML on the fly. Not only that but the post is 2 years old and Fluent NHibernate has changed since.
With the ICriteria objects and even HQL I can specify the timeout, however that is not the goal here. I would like to know how to set that same timeout and use LINQ.
Example code:
using (var session = SessionFactory.OpenSession())
using (var transaction = session.BeginTransaction())
{
var query = (from mem in session.Query<Member>()
select mem);
query = query.Where({where statement});
int start = (currentPage - 1) * max);
if (start > 0)
query = query.Skip(start).Take(max);
else
query = query.Take(max);
var list = query.ToList();
transaction.Commit();
return list;
}
This code (where statement does not matter) works for all purposes except where a timeout occurs.
Any help is appreciated. Thanks in advance!
I ended up setting the command timeout for the Configuration for Fluent NHibernate. The downside to this is that it sets the timeout for ALL of my data access calls and not just the one.
Example code:
.ExposeConfiguration(c => c.SetProperty("command_timeout", (TimeSpan.FromMinutes(10).TotalSeconds).ToString()))
I found this suggestion from this website.
Nhibernate has extended the IQueryable and added a few methods https://github.com/nhibernate/nhibernate-core/blob/master/src/NHibernate/Linq/LinqExtensionMethods.cs
var query = (from c in Session.Query<Puppy>()).Timeout(12);
or
var query = (from c in Session.Query<Puppy>());
query.Timeout(456);
I've just spent fair amount of time fighting with this and hopefully this will save someone else some time.
You should use the .Timeout(120) method call at the very last moment to make sure it is used. TBH I'm not 100% sure on why this is but here are some examples:
WILL WORK
query = query.Where(x => x.Id = 123);
var result = query.Timeout(120).ToList();
DOESN'T WORK
query.Timeout(120);
query = query.Where(x => x.Id = 123);
var result = query.ToList();
If done like the second (DOESN'T WORK) example, it seems to fall back to the default System.Transaction.TransactionManager.DefaultTimeout.
Just in case anyone is still looking for this and finds this old thread too...
Query.Timeout is deprecated.
You should use WithOptions instead:
.WithOptions(o => o.SetTimeout(databaseTimeoutInSeconds))

Nodejs node-sqlite3 run callback not working

I am trying to perform a delete of a row in sqlite db using nodejs and node-sqlite3 package.
When I run the delete command, and manually check the entries, I can see that the query successfully deleted that row but I cant seem to write the code that confirms this.
This is the query
db.run("DELETE FROM Table1 WHERE id=? AND username=?", [id, user], function(error) {
console.log(error);
});
Regardless of a wrong or right input, it outputs null to the console. If the right details are given, it deletes it and prints null, if wrong id and user are given, it still prints null.
Any ideas on what might be wrong?
Thanks
To my prevoius question, the problem was that I've used fat arrow for callback declaration. From javascript documentation I've discovered that in arrow function (fat arrow ), this has lexical scope and so this result undefined and not valued as in library documentation said. Using otherwise anonimous function, this is bounded in dynamic scope and so this.changes is valued.
Now, with code as below, is ok:
var sql = 'update recipes set stars = stars + 1 where id = ?';
db.run(sql,
[
1 // id = 1 execute update - if id = 11111 do nothing
], function(err) {
if(err)
throw err;
console.log("VALUE CHANGES: " + this.changes + " - " + util.inspect(this, { showHidden: false, depth: null }));
if(this.changes == 1)
console.log("WORK DONE");
else
console.log("NOTHING DONE");
});
Here more explanations: https://github.com/mapbox/node-sqlite3/issues/606
There is nothing wrong in the node and node-sqlite3 behaviour here.
Here are two parts to explain first regarding node and other regarding Sqlite.
Node
Your callback is getting called after execution of the statement. So nothing wrong here, since your callback is getting called (as proved by 'null' as output).
Sqlite
Delete query in Sqlite deletes if condition given in where clause evaluates to true, otherwise nothing is deleted.
Referring from node-sqlite3 documentation's Database#run api:
callback (optional): If given, it will be called when an error occurs
during any step of the statement preparation or execution, and after
the query was run. If an error occurred, the first (and only)
parameter will be an error object containing the error message. If
execution was successful, the first parameter is null.
So, in your case query execution succeeds without any error, resulting in error argument to callback function null as you see in output.
Further, if you want to check if any row was actually removed, you can use changes property as mentioned in the documentation:
If execution was successful, it contains two properties named "lastID"
and "changes" which contain the value of the last inserted row ID and
the number of rows affected by this query respectively. Note that
"lastID" only contains valid information when the query was a
successfully completed INSERT statement and "changes" only contains
valid information when the query was a successfully completed UPDATE
or DELETE statement. In all other cases, the content of these
properties is inaccurate and should not be used. The .run() function
is the only query method that sets these two values; all other query
methods such as .all() or .get() don't retrieve these values.
Hope it helps...
I had similar problem, callbacks just would not fire. Period. The problem was that elsewhere I was calling process.exit(1), so my code was exiting before the the callbacks had a chance to return.
Search for process.exit, that may (or may not) save you hours of debugging and blaming sqlite :)
Off the topic: What bugs my mind is why they all-cap ID in lastID. It's not like it's an abbreviation like SQL or USA. It stands for Identification, which is one word.

Resources