Open bubnenkoff opened 3 years ago
@bubnenkoff: you don't need to call COMMIT
in the transaction((ctx) {})
callback. Unspecified callbacks will call commit when the queries return without issues, or, if you need manual abort on the transaction, you can call ctx.cancelTransaction()
.
@isoos Do you mean I need to add some callback (that currently not in code)?
You already do have a callback: (ctx) {}
is a function that gets called when the transaction is ready.
@isoos Thanks, but how to detect it was error in transaction?
PostgreSQLSeverity.error : Query failed prior to execution. This query's transaction encountered an error earlier in the transaction that prevented this query from executing.
it's not exception, so I can't handle it.
How to from next method check if all ok, or there was an error?
await connection.transaction( (ctx) {
for (var s in body['sql'].split(';')) {
ctx.query(s + ";");
}
// was it complete?
}
use async
and await
:
(ctx) async {
await ctx.query(s);
And try-catch inside it? Like:
await connection.transaction( (ctx) async {
for (var s in body['sql'].split(';')) {
// print(s + ";");
try {
await ctx.query(s + ";");
} // catch
}
}
Depends on what you want. You should be able to get the exception propagated to the connection.transaction
block too, if you execute them in sequence (== with await
).
Big thanks! Could you look at next code and say if I understand all that you said right:
Future<dynamic> sqlInsert(Map body) async {
try {
print("Trying to inserting data");
print("sql: ${body['sql']}");
// comma separated inserts as list
await connection.transaction( (ctx) async {
for (var s in body['sql']) {
try {
await ctx.query(s);
} catch (e) {
print("cancelTransaction was called");
connection.cancelTransaction();
}
}
});
}
on PostgreSQLException catch(e)
{
print("There is some duplicates. Removing them in new transaction");
await connection.transaction( (ctx) async {
for (var s in body['sql-remove']) { // sql-remove have DELETE queries
try {
await ctx.query(s);
} catch (e) {
// something wrong with removing
}
}
});
writeLog("sqlInsert ", e.message);
}
catch (e) {
writeLog("11sqlInsert ", e.message);
}
return 0;
}
Or it should be:
try {
await connection.transaction( (ctx) async {
for (var s in body['sql']) {
await ctx.query(s);
}
});
} catch (e) {
print("cancelTransaction was called");
await connection.cancelTransaction();
}
?
I need to insert in DB list of single INSERT statement as single transaction. Like:
But I am getting error:
Same result on:
What I am missing?