SymmetricDS update error duplicate key - symmetricds

I use SymetricDS and sometimes symmetric raise an error :
INFO [slave] [DefaultDatabaseWriter] [slave-data-loader-1] Failed to process update event in batch 298578.
ERROR [slave] [DataLoaderService] [slave-data-loader-1] Failed to load batch 000-298578 StackTraceKey [UniqueKeyException:4114584735]
ERROR [master][AcknowledgeService] [master-push-default-5] The outgoing batch 001-298578 failed: ERREUR: la valeur d'une clé dupliquée rompt la contrainte unique « primary_key_constaint_name » Détail : La clé existe déjà.
I have tried to detect and correct conflicts by insert in sym_conflict this row :
insert into sym_conflict(conflict_id, source_node_group_id, target_node_group_id, detect_type resolve_type, ping_back)
values('master-win', 'master', 'slave', 'USE_CHANGED_DATA', 'INGORE', 'SINGLE_ROW');
but this not working. On documentation have found this :
USE_CHANGED_DATA : Indicates that the primary key plus any data that has changed on the source system will be used to detect a conflict. If a row exists with the same old values on the target system as they were on the source system for the columns that have changed on the source system, then no conflict is detected during an update or a delete. If a row already exists during an insert then a conflict has been detected.
How symmetric can detect PK conflicts on a update and ignore it ? Thanks.

No conflict detection, neither resolution is required in such cases. By default symmetricDs on insert if there's already a row with the same primary key on the target node will fall back to update and vice versa for an update falling back to an insert: http://www.symmetricds.org/doc/3.6/user-guide/html-single/user-guide.html#d4e104

Related

How to figure out what exact entity resulted in DbContext.SaveChanges FK conflict failure

With Entity Framework Core (in case it matters, I'm using version 2.2), I update a number of entities in the DB context and call SaveChanges. In case saving fails because of the foreign key issue, I can't figure out what exact entities have foreign key issues. Is it possible to figure this out?
When Foreign Key conflict happens, SQL Server returns an error with code 547 and text The UPDATE statement conflicted with the FOREIGN KEY constraint "<Constraint>". The conflict occurred in database "<Database name>", table "<Table name>", column '<Column name>' without reference to exact invalid rows.
I have looked at DbUpdateException properties, but no luck:
var dbUpdateEx = ex as DbUpdateException;
var erroredEntries = dbUpdateEx.Entries;
// The documentation says that Entries property "Gets the entries that were involved in the error",
// but in my case it's always empty.
Also, I have tried validating entities manually before save, but such validation does not find FK conflicts. Code sample:
var valProvider = new ValidationDbContextServiceProvider(dbContext);
var valContext = new ValidationContext(entity, valProvider, null);
var entityErrors = new List<ValidationResult>();
var result = Validator.TryValidateObject(entity, valContext, entityErrors, true);
When I save more than 100 records and the save fails because of FK conflict in a single entity, it's quite frustrating to look for this single invalid record by hand.

Error in SQL Server trigger

I am writing a trigger for the first time. I want to check that if value =4 then Exon N, Date Fin,Date début must not be null
CREATE TRIGGER tgr_suspTVA
ON dbo.F_COMPTET
AFTER INSERT
AS
BEGIN
DECLARE #N_CatCompta int, #ExonN varchar(69),
#dateFin datetime, #dateDeb datetime
SELECT #N_CatCompta = N_CatCompta,
#ExonN = [Exon N°],
#dateFin = [Date Fin],
#dateDeb = [Date début]
IF (#N_CatCompta=4) AND (#ExonN IS NULL OR #dateFin IS NULL OR #dateDeb IS NULL)
BEGIN
RAISERROR('error',16,1);
END
END;
Here is the error that I get:
Msg 207, Niveau 16, État 1, Procédure tgr_suspTVA, Ligne 13
Nom de colonne non valide : 'N_CatCompta'.
Msg 207, Niveau 16, État 1, Procédure tgr_suspTVA, Ligne 13
Nom de colonne non valide : 'Exon N°'.
Msg 207, Niveau 16, État 1, Procédure tgr_suspTVA, Ligne 13
Nom de colonne non valide : 'Date Fin'.
Msg 207, Niveau 16, État 1, Procédure tgr_suspTVA, Ligne 14
Nom de colonne non valide : 'Date début'.
Triggers are not the best way to constrain your data and raise errors when an insert tries to break your rules.
The best way to do this is with constraints. Even a complex rule like this can be handled with a simple CHECK constraint:
ALTER TABLE dbo.F_COMPTET
ADD CONSTRAINT chkCompta4 CHECK (N_CatCompta<>4 OR
([Exon N°] IS NOT NULL
AND [Date Fin] IS NOT NULL
AND [Date début] IS NOT NULL
));
Add this constraint to your table, and any insert that tries to break this rule will raise a constraint violation error.
A trigger would be useful if, when a row breaks your rule, you wanted to do an insert into a different table. But as long as you are only dealing with the one table, there is no need for a trigger.
Although I think the check constraint that Tab Alleman posted is a better approach you might be stuck using a trigger.
If that is the case, you have two MAJOR problems here. The select statement for populating your variables doesn't have a FROM clause. The bigger issue is that you are using scalar variables in your trigger. Triggers fire once per operation in sql server not once per row. You need to reference the inserted virtual table and handle your code appropriately. Most likely an exists.

How do I fix #1062 error received while importing EE database to localhost from remote server

I am trying to import a MySQL database into the localhost database that was exported from the remote database and I am receiving a #1062 error (which is weirdly in French!):
#1062 - Duplicata du champ '1' pour la clef 'PRIMARY'
Google translate: # 1062 - Duplicate field '1' for key 'PRIMARY'
The code that it highlights is as follows:
--
-- Dumping data for table `exp_accessories`
--
INSERT INTO `exp_accessories` (`accessory_id`, `class`, `member_groups`, `controllers`, `accessory_version`) VALUES
(1, 'Expressionengine_info_acc', '1|5', 'content|members|admin_content|design|tools_communicate|homepage|addons_fieldtypes|content_files|admin_system|tools_data|addons|tools|tools_logs|tools_utilities|addons_accessories|content_files_modal|myaccount|addons_modules|addons_plugins|content_publish|content_edit|addons_extensions', '1.0'),
(2, 'Cartthrob_acc', '1|5', 'content|members|admin_content|design|tools_communicate|homepage|addons_fieldtypes|content_files|admin_system|tools_data|addons|tools|tools_logs|tools_utilities|addons_accessories|content_files_modal|myaccount|addons_modules|addons_plugins|content_publish|content_edit|addons_extensions', '1.0');
I am a novice with SQL and I can't see what it is on about. I can't see a duplicate in the primary key.
Can anyone help me with this please?
Many thanks
Gabe
By default, mysqldump writes information as SQL statements to the standard output. You can save the output in a file: shell> mysqldump [arguments] > file_name !!!!!!!!!!

Cayenne, Postgres: primary key generation

I'm using Cayenne 3.2M1 and Postgres 9.0.1 to create a database. Right now I'm having problems with the primary key generation of Cayenne since I have tables with more than one primary key and as far as I've read Cayenne cant generate more that one primary key per table. So I want the Postgres to do that work.
I have this table:
CREATE TABLE telefonocliente
(
cod_cliente integer NOT NULL DEFAULT currval('cliente_serial'::regclass),
cod_telefono integer NOT NULL DEFAULT nextval('telefonocliente_serial'::regclass),
fijo integer,
CONSTRAINT telefonocliente_pkey PRIMARY KEY (cod_cliente, cod_telefono)
)
WITH (
OIDS=FALSE
);
TelefonoCliente telefono = context.newObject(TelefonoCliente.class);
telefono.setFijo(4999000);
context.commitChanges();
and this is the error I get:
INFO: --- transaction started.
19/11/2013 22:46:17 org.apache.cayenne.access.dbsync.CreateIfNoSchemaStrategy processSchemaUpdate
INFO: Full or partial schema detected, skipping tables creation
19/11/2013 22:46:17 org.apache.cayenne.log.CommonsJdbcEventLogger logQuery
INFO: SELECT nextval('pk_telefonocliente')
Exception in thread "main" org.apache.cayenne.CayenneRuntimeException: [v.3.2M1 Jul 07 2013 16:23:58] Commit Exception
at org.apache.cayenne.access.DataContext.flushToParent(DataContext.java:759)
at org.apache.cayenne.access.DataContext.commitChanges(DataContext.java:676)
at org.example.cayenne.Main.main(Main.java:45)
Caused by: org.postgresql.util.PSQLException: ERROR: no existe la relaci?n ≪pk_telefonocliente≫
Position: 16
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:374)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:254)
at org.apache.cayenne.dba.postgres.PostgresPkGenerator.longPkFromDatabase(PostgresPkGenerator.java:79)
at org.apache.cayenne.dba.JdbcPkGenerator.generatePk(JdbcPkGenerator.java:272)
at org.apache.cayenne.access.DataDomainInsertBucket.createPermIds(DataDomainInsertBucket.java:171)
at org.apache.cayenne.access.DataDomainInsertBucket.appendQueriesInternal(DataDomainInsertBucket.java:76)
at org.apache.cayenne.access.DataDomainSyncBucket.appendQueries(DataDomainSyncBucket.java:78)
at org.apache.cayenne.access.DataDomainFlushAction.preprocess(DataDomainFlushAction.java:188)
at org.apache.cayenne.access.DataDomainFlushAction.flush(DataDomainFlushAction.java:144)
at org.apache.cayenne.access.DataDomain.onSyncFlush(DataDomain.java:685)
at org.apache.cayenne.access.DataDomain$2.transform(DataDomain.java:651)
at org.apache.cayenne.access.DataDomain.runInTransaction(DataDomain.java:712)
at org.apache.cayenne.access.DataDomain.onSyncNoFilters(DataDomain.java:648)
at org.apache.cayenne.access.DataDomain$DataDomainSyncFilterChain.onSync(DataDomain.java:852)
at org.apache.cayenne.access.DataDomain.onSync(DataDomain.java:629)
at org.apache.cayenne.access.DataContext.flushToParent(DataContext.java:727)
... 2 more
I've been trying the suggestions on Cayenne tutorial "generated columns", "primary key support" but I seems to always get some error.
INFO: SELECT nextval('pk_telefonocliente')
Exception in thread "main" org.apache.cayenne.CayenneRuntimeException: [v.3.2M1 Jul 07 2013 16:23:58] Primary Key autogeneration only works for a single attribute.
I want to know how to solve this.
Thanks in advance
From your description in comments, out of 2 columns comprising the PK of 'telefonocliente', only one is truly independent - 'cod_telefono'. This will be what Cayenne will generate. In case of PosgreSQL, you will need the following sequence in DB for this to happen:
CREATE SEQUENCE pk_telefonocliente INCREMENT 20 START 200;
Now, where does the second PK 'cod_cliente' come from? Since it is also FK to another table, it means it is a "dependent" PK, and must come from a relationship. So first you need to map a many-to-one relationship between 'telefonocliente' and 'cliente'. Check "To Dep Pk" checkbox on the 'telefonocliente' side. Generate a matching ObjRelationship for your Java objects. Now you can use it in your code:
Cliente c = .. // get a hold of this object somehow
TelefonoCliente telefono = context.newObject(TelefonoCliente.class);
telefono.setFijo(4999000);
telefono.setCliente(c); // this line is what will populate 'cod_cliente' PK/FK
That should be it.
The primary key is allowed just to be one per a table! In your case you create a primary key on two columns, that is right, it is defined in an SQL standard and Postgres supports it well.
However there is a not in Cayenne documentation:
Cayenne only supports automatic PK generation for a single column per table.
see http://cayenne.apache.org/docs/3.0/primary-key-generation.html at the bottom of the page.
Probably they can fix it in a newer version or you can put a request to the Cayenne community.

PostgreSQL JPA cascade partially working

Again we probably have a very simple problem;
our database look like:
CREATE TABLE Question (
idQuestion SERIAL,
questionContent VARCHAR,
CONSTRAINT Question_idQuestion_PK PRIMARY KEY (idQuestion),
);
CREATE TABLE Answer (
idAnswer SERIAL,
answerContent VARCHAR,
idQuestion INTEGER,
CONSTRAINT Answer_idAnswer_PK PRIMARY KEY (idAnswer),
CONSTRAINT Answer_idQuestion_FK FOREIGN KEY (idQuestion) REFERENCES Question(idQuestion),
);
So a Question have many Answers.
Following in entity generated by Netbeans 7.1.2 we have field:
#OneToMany(mappedBy = "idquestion", orphanRemoval=true, cascade= CascadeType.ALL, fetch= FetchType.EAGER)
private Collection<Answer> answerCollection;
As you can see I've already added all possible orphan removal and cascade instructions for cascade removal of collection. And it's working fine but for one moment:
You can delete a Question and connected Answers only if they were created in previous 'instance' of our Application. If I first create a new Question and even one Answer and then go straight and delete it we got an error like:
root cause
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: update or delete on table "question" violates foreign key constraint "answer_idquestion_fk" on table "answer"
Detail: Key (idquestion)=(30) is still referenced from table "answer".
Error Code: 0
Call: DELETE FROM question WHERE ((idquestion = ?) AND (version = ?))
bind => [2 parameters bound]
Query: DeleteObjectQuery(com.accenture.androidwebapp.entities.Question[ idquestion=30 ])
root cause
org.postgresql.util.PSQLException: ERROR: update or delete on table "question" violates foreign key constraint "answer_idquestion_fk" on table "answer"
Detail: Key (idquestion)=(30) is still referenced from table "answer".
If I restart (rebuild, redeploy) the application it's working though.. why? Thanks!
Try adding the EclipseLink #PrivateOwned extension annotation to your collection mapping.
As for the issue with deletion not working until you restart the app, two things come to mind:
You might be using very long EntityManager sessions where everything stays attached to the EnitityManager. If that's the case, it's the change of EntityManager session forced by a restart that's helping. Consider using shorter EntityManager sessions by calling EntityManager.close() when you're done with a session. Work with detached entities and EntityManager.merge() state back in when you want to modify it.
The second level cache, if any, will be cleared by a redeploy. Try disabling the second level cache and see if that helps.

Resources