ERROR: duplicate key value violates unique constraint "xak1fact_dim_relationship" - postgresql

I am getting the below error while deleting some rows and updating the table based on a condition from java. My database is PostgreSQL 8.4. Below is the error:
ERROR: duplicate key value violates unique
constraint "xak1fact_dim_relationship"
The code cuasing this issue is below:
/**
* Commits job. This does the following:
* <OL>
* <LI> cancel previous datamart states </LI>
* <LI> drop diabled derived objects </LI>
* <LI> flip mirror relationships for objects with next states </LI>
* <LI> advance rolloff_state from start1 to complete1, from start2 to complete </LI>
* <LI> set 1/0 internal states to 0/-1 </LI>
* <LI> remove header objects with no letter rows </LI>
* <LI> mark mirror rel as OS if children are missing (e.g., semantic w/o agg build) </LI>
* <LI> mark mirror rel as OS if int-map not in sync with dim base (e.g., int-map SQL w/o semantic) </LI>
* </OL>
*/
protected void CommitJobUnprotected()
throws SQLException
{
if (_repl.epiCenterCon== null)
throw makeReplacementError(0);
boolean oldAutoCommitStatus = _repl.epiCenterCon.getAutoCommit();
try
{
_repl.epiCenterCon.setAutoCommit(false);
Statement stmt = null;
boolean committed = false;
synchronized (SqlRepl.metaChangeLock)
{
try
{
stmt = _repl.epiCenterCon.createStatement();
// update internal states for fact_dim_relationship
metaExec(stmt, "DELETE from fact_dim_relationship WHERE internal_state = -1 AND " +
" EXISTS (SELECT 1 FROM fact_dim_relationship WHERE internal_state = 1)",
" SELECT 1 from fact_dim_relationship WHERE internal_state = -1 AND " +
" EXISTS (SELECT 1 FROM fact_dim_relationship WHERE internal_state = 1)"); /*1*/
metaExec( stmt, "UPDATE fact_dim_relationship SET internal_state = internal_state - 1 " +
" WHERE EXISTS (SELECT 1 FROM fact_dim_relationship inner1 " +
" WHERE inner1.internal_state = 1 " +
" AND inner1.fact_tbl_key = fact_dim_relationship.fact_tbl_key " +
" AND inner1.dim_base_key = fact_dim_relationship.dim_base_key ) ",
" SELECT 1 FROM fact_dim_relationship " +
" WHERE EXISTS (SELECT 1 FROM fact_dim_relationship inner1 " +
" WHERE inner1.internal_state = 1 " +
" AND inner1.fact_tbl_key = fact_dim_relationship.fact_tbl_key " +
" AND inner1.dim_base_key = fact_dim_relationship.dim_base_key ) "); /*5*/
System.out.println("Update done on fact_dim_relationship");
_repl.doDrop(SqlReplLogger.DB_META, stmt, "fact_agg", "SELECT fact_agg_key FROM fact_agg f WHERE " +
" NOT EXISTS (SELECT 1 FROM fact_agg_letter l WHERE " +
" f.fact_agg_key = l.fact_agg_key) "); /*6*/
_repl.doDrop(SqlReplLogger.DB_META, stmt, "dim_base_agg", "SELECT dim_base_agg_key FROM dim_base_agg d WHERE " +
" NOT EXISTS (SELECT 1 FROM dim_base_agg_letter l WHERE " +
" d.dim_base_agg_key = l.dim_base_agg_key) "); /*6*/
CheckOutOfSync(stmt, "fact_agg", null); /*7*/
CheckOutOfSync(stmt, "dim_base_agg", null); /*7*/
metaExec( stmt, " update mirror_relationship set relation_to_current = 'Out Of Sync' " +
" where dim_col_intmap_key is not null " +
" and relation_to_current = 'One Back' " +
" and not exists ( " +
" select 1 " +
" from mirror_relationship m2, dim_col_view c, dim_col_intmap i " +
" where m2.dim_base_key = c.dim_base_key " +
" and c.dim_col_key = i.dim_col_key " +
" and i.dim_col_intmap_key = mirror_relationship.dim_col_intmap_key " +
" and m2.relation_to_current = 'One Back') ",
" SELECT 1 FROM mirror_relationship " +
" where dim_col_intmap_key is not null " +
" and relation_to_current = 'One Back' " +
" and not exists ( " +
" select 1 " +
" from mirror_relationship m2, dim_col_view c, dim_col_intmap i " +
" where m2.dim_base_key = c.dim_base_key " +
" and c.dim_col_key = i.dim_col_key " +
" and i.dim_col_intmap_key = mirror_relationship.dim_col_intmap_key " +
" and m2.relation_to_current = 'One Back') "); /*8*/
// clean out the tables used by mombuilder, aggbuilder, and semantics
metaExec( stmt, "delete from relation_intermediary", "select 1 from relation_intermediary" );
_repl.epiCenterCon.commit();
committed = true;
}
finally
{
safeMetaRollbackIfNeeded( committed );
_repl.safeClose( null, stmt );
}
} // end synchronized block
}
finally
{
_repl.epiCenterCon.setAutoCommit(oldAutoCommitStatus);
}
}
The first delete statement ran well, but while running the update it is throwing the above exception....! We support the SQLServer, Oracle and DB2, and the same code runs fine with other DBs. By the way we run these statements in a READ_COMMITTED transaction level and we are setting the autocommit off if anything fails in between we safely rolls back. If i run the above code with autocommit true the code works fine! But we should not do so. I am suspecting the Multi version concurrency control feature of PostgreSQL, am i wrongly setting the Isolation level? Please help me as early as possible. I can provide what ever the info you want.

If it is only this particular set of queries, use SET CONSTRAINT:
BEGIN;
SET CONSTRAINT = xak1fact_dim_relationship DEFERRED;
-- Do your SQL
COMMIT;
If this is a very common case, you can change your database schema to you can, change your database schema to support INITIALLY DEFERRED.

Related

JPA Subquery missing from-clause, but when I try to execute the query it works

This is my code looks like
#Query(value = "SELECT pu.id_user AS idUser, " +
"pu.full_name AS \"name\", " +
"pu.username, " +
"pu.email, " +
"CASE pu.status " +
"WHEN 0 THEN 'Blocked' " +
"WHEN 1 THEN 'Unblocked' " +
"END status, " +
"(SELECT branch_name AS \"branch\" " +
"FROM schema_a.branch aa " +
"WHERE mpb.branch_id IS NOT NULL AND mpb.parent_branch_id IS NOT NULL AND " +
"branch_id = mpb.parent_branch_id " +
") AS branch, " +
"mpb.branch_id AS childId, " +
"mpb.branch_name AS childName, " +
"mpb.parent_branch_id AS parentBranchId, " +
"r.role_name AS roleName " +
"FROM schema_a.user pu " +
"JOIN schema_a.branch mpb ON pu.id_branch = mpb.id_branch " +
"JOIN schema_a.\"role\" r ON pu.id_role = r.id_role " +
"WHERE pu.is_deleted = false", nativeQuery = true)
Page<UserAndBranch> findAllByIsDeletedIsFalse(Pageable pageable);
the result i got
Caused by: org.postgresql.util.PSQLException: ERROR: missing FROM-clause entry for table "aa"
That native query is executed succesfully in DBeaver, nothings different just remove the quotation mark, what am I missing?

JpaSystemException: No Dialect mapping for JDBC type: 1111

I have viewed some of the related question but the solutions on them are bit older. Most of them are using EntityManager. I have written the following native query in JpaRepository and when I get geojson as a String I'm getting the error mentioned in the title.
Here is my query
#Query(value = "SELECT\n"
+ " json_build_object(\n"
+ " 'type', 'FeatureCollection',\n"
+ " 'features', json_agg(\n"
+ " json_build_object(\n"
+ " 'type', 'Feature',\n"
+ " 'geometry', ST_AsGeoJSON(a.check_in_geom)\\:\\:json,\n"
+ " 'properties', json_build_object(\n"
+ " 'username', a.username,\n"
+ " 'users', (\n"
+ " -- Generate json array of \"users\"\n"
+ " SELECT array_to_json(array_agg(u.*)) \n"
+ " FROM users u \n"
+ " WHERE u.username = a.username\n"
+ " GROUP BY u.username\n"
+ " )\n"
+ " )\n"
+ " )\n"
+ " )\n"
+ " ) Json\n"
+ "FROM\n"
+ " attendances a, users u\n"
+ " WHERE a.username = u.username AND u.designation = 'Manager' AND date_trunc('day', a.created_at)\\:\\:DATE = '2022-04-04'"
+ " ;", nativeQuery = true)
String getAttendanceGeoJsonByDesignationAndDate(String designation, String dateStr);
For now I'm passing designation and date as static values.
When I run this query on Postgresql it runs successfully and return the expected geojson. But spring boot does not allow the result to be as String or it throws exception while running the query.
Please let me know how can I fix it. Also if I need to provide more detail, do let me know.

EF Core to make SQL Database MERGE call and get output of new inserted record along with identify column

We are using EF Core to make database call and we have a MERGE call to conditionally insert a record and what we want is once the record is inserted we want to get that new RECORD in the OUTPUT (along with the identify column). I am doing this avoid additional Select query post the insert. Following is our code, any guidance on how we can get the OUTPUT of the new record along with the identify column (auto generated value):
string query = $"MERGE INTO [ReceiptMaster] AS old " +
$"USING (VALUES ({receipt.ProfileID},'{receipt.TranscribeID}','{receipt.ReceiptStatusID}'," +
$"'{receipt.ReceiptTypeID}','{receipt.TransactionDate}','{receipt.ProcessTypeID}'," +
$"'{receipt.TripTranscriptionVendorID}','{receipt.AcquireTypeID}',{receipt.CategoryTypeID}," +
$"'{receipt.IsResubmitted}','{receipt.IsResubmittedByPanel}', {receipt.ScrapeJobID}, " +
$"'{receipt.TripTranscriptionPayloadID}')) " +
$"AS new (ProfileID, TranscribeID, ReceiptStatusID, ReceiptTypeID, TransactionDate, ProcessTypeID, " +
$"TripTranscriptionVendorID, AcquireTypeID, CategoryTypeID, IsResubmitted, IsResubmittedByPanel, " +
$"ScrapeJobID, TripTranscriptionPayloadID) " +
$"ON new.TranscribeID = old.TranscribeID " +
$"WHEN NOT MATCHED BY TARGET THEN INSERT (ProfileID, TranscribeID, ReceiptStatusID, ReceiptTypeID, " +
$"TransactionDate, ProcessTypeID, TripTranscriptionVendorID, AcquireTypeID, CategoryTypeID, IsResubmitted, " +
$"IsResubmittedByPanel, ScrapeJobID, TripTranscriptionPayloadID) VALUES (ProfileID, TranscribeID, ReceiptStatusID, " +
$"ReceiptTypeID, TransactionDate, ProcessTypeID, TripTranscriptionVendorID, AcquireTypeID, CategoryTypeID, " +
$"IsResubmitted, IsResubmittedByPanel, ScrapeJobID, TripTranscriptionPayloadID);";
var context = _dbContext.Database.ExecuteSqlRaw(query);
if (context == 0) return false;
else return true;
}

An identification variable must be provided for a range variable declaration

I'm trying to use this query in my jpa but it doesn't work:
List<Object[]> query = em.createQuery("SELECT Tstat.idStatistiques, TL.codeLieu, TL.materiel, TL.zone, sum(Tstat.colis) as colis, Tstat.defaut, sum(Tstat.nbreDefaut) as nbreDefaut,"
+ " sum(Tstat.nonLu) as nonLu, sum(Tstat.multiple) as multiple, sum(Tstat.nonRecu) as nonRecu, sum(Tstat.incoherent) as incoherent, sum(Tstat.requete) as requete , "
+ "sum(Tstat.tempsFonctionnement) as tempsFonctionnement, SUM(Tstat.tempsUtilisation) as tempsUtilisation, Tstat.modeFonctionnement FROM "
+ "( SELECT CURRENT_DATE as horodatage, St.idStatistiques, St.colis, St.defaut, St.nbreDefaut, St.nonLu, St.requete, St.multiple, St.nonRecu, St.incoherent, St.tempsFonctionnement, St.tempsUtilisation, St.modeFonctionnement FROM Statistique St )"
+ " UNION "
+ "(SELECT h.horodatage, h.idStatistiques, h.colis, h.defaut, h.nbreDefaut, h.nonLu, h.nonRecu, h.requete, h.multiple, h.incoherent, h.tempsFonctionnement, h.tempsUtilisation, h.modeFonctionnement FROM Statistiqueshisto h )"
+ " Tstat "
+ "LEFT JOIN (SELECT * FROM Lieux) as TL on Tstat.idStatistiques = TL.code_VI WHERE idStatistiques like :A ").setParameter("A", 0040+"%").getResultList();
This gives me error
The expression is invalid, which means it does not follow the JPQL
grammar.

Access list of object array with alias in jpa

i have written a native query in jpa which fetch list of object array
list = entityManager.createNativeQuery("select emp.card Card,emp.code Code,emp.emp_name EmpName,ln.BAL Balance, ln.cum_intr CumIntr, ln.install Install,ln.install_no InstallNo, "
+ " led.BAL ledgBAL,led.cum_intr ledgCum,led.install ledgInstall,led.install_no ledgInstallNo "
+ " from LOANS ln "
+ " inner join "
+ " LOAN_LEDGER led "
+ " on (led.EMPLOYEES_ID = ln.EMPLOYEES_ID and ln.LOAN_UID= led.LOAN_UID and (ln.bal!= led.BAL or ln.cum_intr!= led.cum_intr or ln.INSTALL != led.INSTALL )) "
+ " inner join EMPLOYEES emp "
+ " on ln.employees_id = emp.id "
+ " where led.ledger_month in "
+ " ( 201312 )").getResultList();
I assigned alias for each field.this is my code to access this object array.
Iterator it = list.iterator();
while (it.hasNext()) {
Object[] result = (Object[]) it.next();
System.err.println("Result Arrayyyyy "+result[0]);
}
Now i want to access this result array using alias . How can I do it?