Prepared statements Issue with pgBouncer with 'transaction' pool_mode - postgresql

I have Prepared statements Issue with pgBouncer in 'transaction' pooling mode.
This Rust code:
use postgres::{Client, Error, NoTls};
fn main() -> Result<(), Error> {
let mut client = Client::connect(
"postgresql://haproxy#localhost:9435/haproxy",
NoTls,
)?;
for row in client.query("SELECT pg_is_in_recovery() as x;", &[])? {
let x: bool = row.get(0);
println!(
"found app x: {}",
x
);
}
Ok(())
}
fails with: prepared statement "s0" does not exist
Error: Error { kind: Db, cause: Some(DbError { severity: "ERROR", parsed_severity: Some(Error), code: SqlState(E26000), message: "prepared statement \"s0\" does not exist", detail: None, hint: None, position: None, where_: None, schema: None, table: None, column: None, datatype: None, constraint: None, file: Some("prepare.c"), line: Some(506), routine: Some("FetchPreparedStatement") }) }
Any solution to this?

FTR!
the answer is using simple_query !
use postgres::{Client, Error, NoTls, SimpleQueryMessage};
fn main() -> Result<(), Error> {
let mut client = Client::connect("postgresql://haproxy#localhost:9435/haproxy", NoTls)?;
let mut res = false;
let it = client.simple_query("SELECT pg_is_in_recovery()")?;
for mm in it {
match mm {
SimpleQueryMessage::CommandComplete(_x) => {
// println!("{:?}", x);
}
SimpleQueryMessage::Row(x) => {
if x.get(0).as_ref().unwrap().contains('t') {
res = true;
} else {
res = false;
}
}
_ => panic!("n"),
}
}
println!("Result is: {}", res);
Ok(())
}

Related

"[Function: Error Ctor]" error in console

the first console log is getting logged but the second one isn't
and the catch is catching an error which I do not understand ...
this is my route:
router.post("/buy", JwtAuthenticateToken, async (req, res, next) => {
try {
const entry = new PositionModel(req.body)
console.log("new", entry)
const result = await entry.save()
console.log("saved", result)
} catch (error) {
console.log(error)
next(error)
}
})
this is what gets printed in the console:
new {
_id: 6125514a26fb7d06603b1a5a,
stock: 'Apple Inc',
ticker: 'AAPL',
purchasePrice: 149.62,
shares: 1,
owner: 6124e2a70d195a05f4e480cd
}
[Function: ErrorCtor]
I was passing an error to an error creator in my .post("validate")
probably the dumbest 5 lines of code I have ever written.
post("validate", (error, doc, next) => {
if (error) {
const err = createError(400, error)
next(err)
} else {
next(error)
}
})

How to use a user-defined type in a rust-postgres client.execute call

I have the following code that is used to insert email addresses in a table.
fn add(&mut self, email: &str) {
match self.client.execute("call email_add($1)", &[&email]) {
Ok(_) => {
println!("inserted")
}
Err(e) => {
println!("{:?}", e);
}
}
}
I get this error when I test the code:
Error { kind: ToSql(0), cause: Some(WrongType { postgres: Other(Other { name: "email_address", oid: 37434, kind: Domain(Text), schema: "public" }), rust: "&str" }) }
The email address user-defined type is defined as:
-- http://www.regular-expressions.info/email.html
create domain email_address
text not null
constraint chk_email
check(
length(value) < 254
and
value ~ '^[a-zA-Z0-9._%+-]{1,64}#(?:[a-zA-Z0-9-]{1,63}\.){1,125}[a-zA-Z]{2,63}$'
);
I am using rust-postgres crate.
I had to implement the postgres_types::ToSql trait for the email_address domain that I created.
struct EmailAddress {
email: String
}
impl ToSql for EmailAddress {
fn to_sql(&self, ty: &Type, out: &mu BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
return self.email.to_sql(ty, out);
}
to_sql_checked!();
fn accepts(ty: &Type) -> bool {
return ty.name() == "email_address";
}
}
Then I changed the add function to:
fn add(&mut self, email: &str) {
let email_address: EmailAddress = EmailAddress {
email: String::from(email)
}
match self.client.execute("call email_add($1)", &[&email_address]) {
Ok(_) => {
println!("inserted")
}
Err(e) => {
println!("{:?}", e);
}
}
}

What's wrong with this mongo query?

db.items.mapReduce({function(){emit(this.name,this.price);},function(key,value){Array.sum(value)},{out:"map_reduce_example"}});
items are:
{
"_id":"5bfe309ff0e3775c684e85c9",
"name":"sdgjkld",
"price":"123"
}
Error Description:
2018-11-28T12:16:19.407+0530 E QUERY [thread1] SyntaxError: invalid property id #(shell):1:98
Try this
db.items.mapReduce(
function () {
emit(this.name, this.price);
},
function (key, value) {
Array.sum(value)
},
{ out: "map_reduce_example" }
)
OR
var first = function () {
emit(this.name, this.price);
}
var second = function (key, value) {
Array.sum(value)
}
db.items.mapReduce(
first,
second,
{ out: "map_reduce_example" }
)

Unable to return an array of json from Cloud Firestore via Cloud Functions (onCall) to Swift

I have a problem getting the result from a Cloud Function.
This is my Cloud Function:
exports.retrieveTrips = functions.https.onCall((data, context) => {
const uidNumber = context.auth.uid;
var arrayOfResults = new Array();
var idOfFoundDoc;
var query = admin.firestore().collection('Users').where('UID','==', uidNumber);
query.get().then(snapshot =>
{
snapshot.forEach(documentSnapshot =>
{
idOfFoundDoc = documentSnapshot.id;
});
var queryDoc = admin.firestore().collection('Users').doc(idOfFoundDoc).collection('Trips');
queryDoc.get().then(snapshot =>
{
snapshot.forEach(documentSnapshot =>
{
arrayOfResults.push(documentSnapshot.data());
});
console.log('ARRAY: ' , arrayOfResults);
return arrayOfResults;
})
.catch (err =>
{
console.log ('Error adding document: ', err);
});
})
.catch (err => {
//response.send('Error getting documents', err);
console.log ('Error getting documents', err);
});
And this is the code that I have in my application.
#IBAction func RetrieveTripsButton(_ sender: Any)
{
self.functions.httpsCallable("retrieveTrips").call() {(result, error) in
if let error = error as NSError? {
if error.domain == FunctionsErrorDomain
{
let message = error.localizedDescription
print ("Message: " + message)
}
return
}
print ("Result: -> \(type(of: result))")
print("Result.data type: \(type(of: result?.data))");
print ("Result.data -> \(result?.data)")
}
}
And this is the printed result.
Result: -> Optional<FIRHTTPSCallableResult>
Result.data type: Optional<Any>
Result.data -> Optional(<null>)
The console log is able to print arrayOfResults correctly. Furthermore, when I change this functions to onRequest and feed it the relevant information, the res.status(200).send(arrayOfResults) is able to display the array of JSON in the page.
If I placed the return arrayOfResults; outside of the .then function, I would get a result along with an empty array. My issue is similar to this problem here but I'm unable to receive even that when I return { text: "some_data" }; .
Any help would be great, thank you!
You have to chain the different promises and return the result of the promises chain, as follows.
Note that it is actually what the OP explains in his answer to the SO post you mention "The issue was that I forgot to return the actual promise from the cloud function".
exports.retrieveTrips = functions.https.onCall((data, context) => {
const uidNumber = context.auth.uid;
const arrayOfResults = new Array();
let idOfFoundDoc;
const query = admin.firestore().collection('Users').where('UID','==', uidNumber);
return query.get().then(snapshot => { // here add return
snapshot.forEach(documentSnapshot =>
{
idOfFoundDoc = documentSnapshot.id;
});
const queryDoc = admin.firestore().collection('Users').doc(idOfFoundDoc).collection('Trips');
return queryDoc.get(); // here add return and chain with then()
})
.then(snapshot => {
snapshot.forEach(documentSnapshot => {
arrayOfResults.push(documentSnapshot.data());
});
console.log('ARRAY: ' , arrayOfResults);
return { arrayOfResults : arrayOfResults }; //return an object
})
.catch (err => {
console.log ('Error getting documents', err);
//Here you may return an error as per the documentation https://firebase.google.com/docs/functions/callable#handle_errors, i.e. by throwing an instance of functions.https.HttpsError
});
});
I would also suggest that you look at these two videos from the Firebase team, about Cloud Functions and promises: https://www.youtube.com/watch?v=7IkUgCLr5oA and https://www.youtube.com/watch?v=652XeeKNHSk.

Parse, cloud code beforeDelete

Before I'm deleting my user I would like to remove some objects in another class. This works fine in Swift.
class func deleteAnonymousUserListSettings(completetion:(result:Bool, error:NSError!) -> Void){
var queryListSettings = PFQuery(className: "ListSettings")
queryListSettings.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
if let objs = objects as? [PFObject] where error == nil {
PFObject.deleteAllInBackground(objs, block: { (success, error) -> Void in
if success{
completetion(result: success, error: error)
}
})
}
}
}
Now I would like to transfer this to cloudCode. It works approximately 1 out of 10 times but I don't know why or when it works and sometimes not.
Parse.Cloud.beforeDelete(Parse.User, function(request, response) {
var query = new Parse.Query('ListSettings');
query.find({
success: function(results) {
for (var i = 0; i < results.length; i+=1) {
results[i].destroy();
}
response.success(results);
},
error: function() {results
response.error("error");
}
});
});
Help, please.
Instead of deleting one by one, you can delete all of the object at once and return success if it is successful. You can do this via the below code blocks;
query.find().then(function (results)
{
Parse.Object.destroyAll(results);
response.success("Success");
},
function (error)
{
response.success("Error");
})
Hope this helps.Regards.
Here we go, this works for me.
Parse.Cloud.beforeDelete(Parse.User, function(request, response) {
var query = new Parse.Query('ListSettings');
query.find().then(function(results) {
return Parse.Object.destroyAll(results);
}).then(function() {
response.success();
}, function(error) {
response.error("Error removing ListSettings.");
});
});