Failed to assert PGX error using PGconn and PGX - postgresql

rows, err:= b.DB.ExecContext(
ctx,
fmt.Sprintf(`
UPDATE service_slots
SET slots_left = slots_left - %d
WHERE date = $1 AND
start_hour = $2 AND
service_id =$3
`, serviceSlots.Qty),
booking.Date,
booking.Appointment,
serviceSlots.ID,
)
if err!= nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
fmt.Println(pgErr.Message) // => syntax error at end of input
fmt.Println(pgErr.Code) // => 42601
}
return err
}
tried to use error assert from pgconn, but somehow cannot make the error get inside errors.As(err,&pgErr)
if I hit the constraint error or any error from postgres, it just pass the errors.As (did not trigger the printline ) and return the normal error.
what is wrong with my code ?
used
github.com/jackc/pgx v3.6.2+incompatible
github.com/jackc/pgconn v1.13.0 // indirect
the error is
"ERROR: new row for relation \"service_slots\" violates check constraint \"slot_nonnegative\" (SQLSTATE 23514)"
-----------SOLVED----------
should not use *pgconn.PgError but should use pgx.PgError instead
thanks to #Adrian for pointing out that I assume the type wrong

Related

Flutter functions Null safety errors

Got the following errors and don't know how to update the code to solve it.
Error: Can't use an expression of type 'Function?' as a function because it's potentially null.
'Function' is from 'dart:core'.
Try calling using ?.call instead.
PageName nextPage = pageName_pageFunction_mapPageName.welcomePage;
PageName nextPage2 = pageName_pageFunction_mapnextPage;
The code:
enum PageName {
welcomePage,
register,
login,
editProfile,
showProfile,
resetPassword,
errorUserExists,
}
Map<PageName, Function> pageName_pageFunction_map = {
PageName.welcomePage: showWelcomePage,
PageName.register: showRegisterPage,
PageName.login: showLoginPage,
PageName.editProfile: showEditProfile,
PageName.showProfile: showUserProfile,
PageName.resetPassword: showResetPassword,
PageName.errorUserExists: showErrorUserExists,
};
void main() {
PageName nextPage = pageName_pageFunction_map[PageName.welcomePage]();
if (nextPage != null) {
while (true) {
PageName nextPage2 = pageName_pageFunction_map[nextPage]();
if (nextPage2 != null) {
nextPage = nextPage2;
}
}
}
}
Can you help me? Thank you
The error message tell that you can't execute a function because this one might be null, and if you execute a function on a null value it will break the program. You have two solution :
First you can make sure that your function isn't null with a test :
if (myFunction != null) {
myFunction()
}
Or you can tell the compiler that your function is not null with the ! operator
myFunction!()
Error: Can't use an expression of type 'Function?' as a function
because it's potentially null.
When you look up one of your functions from the map like pageName_pageFunction_map[PageName.welcomePage] you get a value of type Function?. This is because if you enter a key which does not have a corresponding value, you will get back null from the expression.
The following error message gives you a suggestion on how to solve this problem.
'Function' is from 'dart:core'. Try calling using ?.call instead.
PageName nextPage = pageName_pageFunction_mapPageName.welcomePage;
PageName nextPage2 = pageName_pageFunction_mapnextPage;
You can place ?.call directly before the argument list () to safely call the function;
pageName_pageFunction_map[PageName.welcomePage]?.call();

Entity Framework is failing to delete a record from an associated table throwing an error

I have a simple association table whose PK isn't referenced anywhere but when I am trying to delete a record from it in the following way, I get an error. I am using EF code-first. Any help would be very very helpful. Thanks in advance.
List<ViolationTypeNOV> novRels = UnitOfWork.Context.ViolationTypeNOVs.Where(x => x.NOVId == nov.NOVId).Include("ViolationType").Include("NOV").ToList();
foreach (ViolationTypeNOV o in novRels)
{
UnitOfWork.Context.ViolationTypeNOVs.Remove(o);
}
UnitOfWork.Context.SaveChanges();
Here is the error message I am getting. If the table's PK isn't referenced in any way, why is it failing with this error? Just not able to understand:
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
The same thing if I am running through SSMS same thing is working though:
DELETE ViolationTypeNOVs
WHERE ViolationTypeNOVId = 2
Why?
But again if I am running the same query through context as below, I get the same error at the calling SaveChanges:
foreach (ViolationTypeNOV o in novRels)
{
string str = string.Format("Delete ViolationTypeNOVs where ViolationTypeNOVId = {0}", new object[] { o.ViolationTypeNOVId });
UnitOfWork.Context.Database.ExecuteSqlCommand(str);
}
UnitOfWork.Context.SaveChanges();
It seems like some of the objects within the context aren't nulling or getting deleted, is there anyway to clear them all in one go? Because these ids/objects are used in multiple places in the code - please let me know how to clear them all - thanks a lot.
Any help please?
Fixed it - the problem is we need to clear up all the objects and its links that the parent object is using then only we can save the changes thanks here is my solution
public bool Delete(NOV nov, bool performCommit = true)
{
System.Data.Entity.DbContextTransaction dbOperation = null;
if (performCommit)
dbOperation = UnitOfWork.BeginTransaction();
try
{
//-- Remove the Items - "foreach" approach was a problem
// http://weblogs.asp.net/ricardoperes/entity-framework-pitfalls-deleting-orphans
//------------------------------------------------------
// Remove the Violations that are in this NOV
//------------------------------------------------------
List<Violation> violationIdlist = new List<Violation>();
foreach (var v in nov.ViolationNOVs)
{
var a = UnitOfWork.ViolationRepository.GetAll().Where(z => z.ViolationId == v.ViolationId).FirstOrDefault();
violationIdlist.Add(a);
}
foreach (var v in violationIdlist)
{
var a = nov.ViolationNOVs.Where(x => x.NOVId == nov.NOVId && x.ViolationId == v.ViolationId)?.FirstOrDefault();
nov.ViolationNOVs.Remove(a);
}
nov.IssuedBy.Clear();
//deleting all OneToMany references to NOV
List<ViolationTypeNOV> novRels = UnitOfWork.Context.ViolationTypeNOVs.Where(x => x.NOVId == nov.NOVId).Include("ViolationType").Include("NOV").ToList();
nov?.ViolationTypeNOVs?.Clear();
//foreach (ViolationTypeNOV o in novRels)
//{
// UnitOfWork.Context.ViolationTypeNOVs.Remove(o);
// o?.ViolationType?.ViolationTypeNOVs?.Remove(o);
// nov?.ViolationTypeNOVs?.Remove(o);
//}
UnitOfWork.Context.ViolationTypeNOVs.RemoveRange(novRels);
List<ViolationNOV> violationNOVs = UnitOfWork.Context.ViolationNOVs.Where(x => x.NOVId == nov.NOVId).Include("Violation").Include("NOV").ToList();
nov?.ViolationNOVs?.Clear();
UnitOfWork.Context.ViolationNOVs.RemoveRange(violationNOVs);
List<CaseNOV> caseNOVs = UnitOfWork.Context.CaseNOVs.Where(x => x.NOVId == nov.NOVId).Include("Case").Include("NOV").ToList();
nov?.CaseNOVs?.Clear();
UnitOfWork.Context.CaseNOVs.RemoveRange(caseNOVs);
UnitOfWork.Context.SaveChanges();
if (dbOperation != null)
dbOperation.Commit();
LogHandler.LogInfo(2521, "Deleted NOV " + nov.NOVNumber);
return true;
}
catch (Exception ex)
{
LogHandler.LogError(2523, "Commit Fail in NOV Delete", ex);
if (dbOperation != null)
dbOperation.Rollback();
throw ex;
}
}
This statement has fixed the problem: UnitOfWork.Context.ViolationTypeNOVs.RemoveRange(novRels); thanks a lot for everybody who tried to help me

unable delete all selected checkbox rows in yii2

can anybody explain me how to delete only selected row or all selected row by checkbox it have below code but giving me error sql exception Exception (Database Exception) 'yii\db\Exception' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause'
The SQL being executed was: DELETE FROM usermaster WHERE id='28''
public function actionMultipledelete() {
if (\Yii::$app->request->post()) {
$keys=array();
$keys = \Yii::$app->request->post('id'); // id is array
}
UsermasterModel::deleteAll(['IN','id',$keys]);
return $this->redirect(['index']);
}
Simply use this
$keys = implode(',', $array);
$connection = Yii::$app->db; $command =
$connection->createCommand("DELETE FROM usermaster where id IN
(".$keys.")");

Using DB2, "statement.executeQuery()" throws SqlEception only in my system

//Class UserProfileDBUtil.java
Connection conn = null;
PreparedStatement statment = null;
ResultSet rs = null;
try{
String sqlString = "select count(*) from "+AGENCY_SCHEMA_NAME+".AGENCY WHERE AGENCYCODE= ? and ENABLEDFLAG = ?";
conn = JDBCUtils.getConnection(JDBCUtils.WP_ODS);
statment = conn.prepareStatement(sqlString);
statment.setString(1, agencyCode.toUpperCase());
statment.setString(2, "Y");
rs =statment.executeQuery(); // SQL Error Line 42
while(rs.next())
{
if(rs.getInt(1) > 0 )
{
return true;
}
}
log.error("Agency for agency code "+agencyCode+" is not available or not active");
}
LOG :
com.ibm.db2.jcc.b.SqlException: DB2 SQL error: SQLCODE: -401, SQLSTATE: 42818, SQLERRMC: =
at com.ibm.db2.jcc.b.sf.e(sf.java:1680)
at com.ibm.db2.jcc.b.sf.a(sf.java:1239)
at com.ibm.db2.jcc.c.jb.h(jb.java:139)
at com.ibm.db2.jcc.c.jb.a(jb.java:43)
at com.ibm.db2.jcc.c.w.a(w.java:30)
at com.ibm.db2.jcc.c.cc.g(cc.java:161)
at com.ibm.db2.jcc.b.sf.n(sf.java:1219)
at com.ibm.db2.jcc.b.tf.gb(tf.java:1818)
at com.ibm.db2.jcc.b.tf.d(tf.java:2294)
at com.ibm.db2.jcc.b.tf.X(tf.java:508)
at com.ibm.db2.jcc.b.tf.executeQuery(tf.java:491)
at com.ibm.ws.rsadapter.jdbc.WSJdbcPreparedStatement.executeQuery(WSJdbcPreparedStatement.java:559)
at UserProfileDBUtil.isAgencyActive(UserProfileDBUtil.java:42)
The error you're getting is a -401, which means:
The data types of the operands for the operation operator are not
compatible or comparable.
I would check and make sure that the parameters you're passing in are using the right data types. If you catch the exception, you should be able to use the exceptions Message property to see what the operator is. See here for an example.

Setting PostgreSQL enums using a JDBC ResultSet

I'm trying to copy data from a MySQL database to an equivalent PostgreSQL database, doing a load/insert through Java using JDBC. I get this error whenever I try to copy an enum column:
org.postgresql.util.PSQLException: ERROR: column "mycol" is of type mytable_mycol_enum but expression is of type character varying
Hint: You will need to rewrite or cast the expression.
Position: 194
The Java code (simplified and anonymized):
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection mysqlConn = DriverManager.getConnection(
"jdbc:mysql://localhost/mysqldb", "user", "pass");
Class.forName("org.postgresql.Driver").newInstance();
Connection pgConn = DriverManager.getConnection(
"jdbc:postgresql://othercomp/pgdb", "user", "pass");
Statement selStatement = mysqlConn.createStatement();
ResultSet selSet = selStatement.executeQuery("SELECT * FROM mytable");
Statement insStatement = pgConn.createStatement(
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
Resultset insSet = insStatement.executeQuery("SELECT * FROM mytable WHERE 0=1");
insSet.moveToInsertRow();
while(selSet.next())
{
ResultSetMetaData metaData = selSet.getMetaData();
for (int i = 1; i <= metaData.getColumnCount(); i++)
{
String colName = metaData.getColumnName(i);
Object obj = selSet.getObject(colName);
insertSet.updateObject(colName, obj);
}
insertSet.insertRow();
}
This works fine for tables without an enum column, but
In MySQL I have a column mycol of type enum('A','B','C')
In PostgreSQL I have mycol of type mytable_mycol_enum with CREATE TYPE mytable_mycol_enum AS ENUM ('A','B','C')
How do I set the enum value?
You have to cast the value, so that postgresql understands it:
insert into mytable (mycol) values ('A'::mytable_mycol_enum)
You might have to use a named insert statement, not the generic one in your example. Also, try it in psql first to see if it works.
HTH