Spring Test H2 Flyway - error in sql statement - h2

I have the following sql migration, that doesn't work with h2. If I remove the following SQL - everything works fine. How can i solve it?
SQL State : 42001
Error Code : 42001
Message : Syntax error in SQL statement "CREATE TABLE USER_AUTHORITY
(
USER_AUTHORITY_ID BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
USER_ID BIGINT REFERENCES USR (USER_ID) NOT NULL[*],
AUTHORITY_ID BIGINT REFERENCES AUTHORITY (AUTHORITY_ID) NOT NULL,
OPERATION VARCHAR(2) NOT NULL,
CREATION_DATETIME TIMESTAMP WITH TIME ZONE NOT NULL,
MODIFYING_DATETIME TIMESTAMP WITH TIME ZONE NOT NULL
)"; expected "DEFERRABLE";
Location : db/migration/V1__Schema.sql (/home/v/IdeaProjects/stocky/user-service/build/resources/main/db/migration/V1__Schema.sql)
Line : 29
Statement : create table user_authority

This is a bug of the parser. I filled a new issue about it:
https://github.com/h2database/h2database/issues/3413
You can specify NOT NULL before REFERENCES as a workaround.
USER_ID BIGINT NOT NULL REFERENCES USR (USER_ID),
AUTHORITY_ID BIGINT NOT NULL REFERENCES AUTHORITY (AUTHORITY_ID),

Related

error creating table and also MysqlInnoBDailect is not coming in propeties

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table dept (dept_id bigint not null, dep_name varchar(255), hod varchar(255), primary key (dept_id)) type=InnoDB" via JDBC Statement

Springboot test fail because of table not found from H2 database, but the table has been created

The problem that I can see is that the table is created with the name 'article' and the query is done with ARTICLE in capital letter. I tried to change the application.properties file to this:
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL;NON_KEYWORDS=USER;IGNORECASE=TRUE;CASE_INSENSITIVE_IDENTIFIERS=TRUE;DATABASE_TO_LOWER=TRUE
but it doesn't help the problem.
Here is some output from the console that demonstrate the table has been created:
Hibernate: create table "article" ("id" bigint generated by default as identity, "content" clob, "language" integer, "last_edited" timestamp, "published" timestamp, "title" varchar(255), "image_id" bigint, "user_id" bigint not null, primary key ("id"))
and later this pops up:
Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "ARTICLE" not found; SQL statement: select * from Article where language=? ORDER BY published desc
I tried to name the table in uppercase letter with
DATABASE_TO_LOWER=FALSE, DATABASE_TO_UPPER=TRUE;
and it didn't help either.
What could I try next?

ERROR: duplicate key value violates unique constraint "spring_session_attributes_pk"\n Detail: Key (session_primary_id, attribute_name)

Currently, I'm using:
Spring boot 2.2.2
Spring jdbc 2.5.0
Spring core 2.5.0
Sometimes, I got errors when accessing my endpoints, here is the stack trace, this happen after upgrading my library from:
spring boot 2.1.7
spring jdbc 2.1.8
spring core 2.1.8
Handle DataIntegrityViolationException: PreparedStatementCallback;
SQL [INSERT INTO SPRING_SESSION_ATTRIBUTES(SESSION_PRIMARY_ID, ATTRIBUTE_NAME, ATTRIBUTE_BYTES) SELECT PRIMARY_ID, ?, ? FROM SPRING_SESSION WHERE SESSION_ID = ?];
ERROR: duplicate key value violates unique constraint \"spring_session_attributes_pk\"
Detail: Key (session_primary_id, attribute_name)=(a9427ef5-92a4-4845-8769-e034c3b50b70, SPRING_SECURITY_CONTEXT) already exists.; nested exception is org.postgresql.util.PSQLException:
ERROR: duplicate key value violates unique constraint \"spring_session_attributes_pk\"
Detail: Key (session_primary_id, attribute_name)=(a9427ef5-92a4-4845-8769-e034c3b50b70, SPRING_SECURITY_CONTEXT) already exists.
org.springframework.dao.DuplicateKeyException: PreparedStatementCallback; SQL [INSERT INTO SPRING_SESSION_ATTRIBUTES(SESSION_PRIMARY_ID, ATTRIBUTE_NAME, ATTRIBUTE_BYTES) SELECT PRIMARY_ID, ?, ? FROM SPRING_SESSION WHERE SESSION_ID = ?];
ERROR: duplicate key value violates unique constraint \"spring_session_attributes_pk\"
Detail: Key (session_primary_id, attribute_name)=(a9427ef5-92a4-4845-8769-e034c3b50b70, SPRING_SECURITY_CONTEXT) already exists.; nested exception is org.postgresql.util.PSQLException:
ERROR: duplicate key value violates unique constraint \"spring_session_attributes_pk\"
Detail: Key (session_primary_id, attribute_name)=(a9427ef5-92a4-4845-8769-e034c3b50b70, SPRING_SECURITY_CONTEXT) already exists.
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:243)
Here is my session tables:
CREATE TABLE APP_SPRING_SESSION (
PRIMARY_ID CHAR(36) NOT NULL,
SESSION_ID CHAR(36) NOT NULL,
CREATION_TIME BIGINT NOT NULL,
LAST_ACCESS_TIME BIGINT NOT NULL,
MAX_INACTIVE_INTERVAL INT NOT NULL,
EXPIRY_TIME BIGINT NOT NULL,
PRINCIPAL_NAME VARCHAR(100),
CONSTRAINT APP_SPRING_SESSION_PK PRIMARY KEY (PRIMARY_ID)
);
CREATE UNIQUE INDEX APP_SPRING_SESSION_IX1 ON APP_SPRING_SESSION (SESSION_ID);
CREATE INDEX APP_SPRING_SESSION_IX2 ON APP_SPRING_SESSION (EXPIRY_TIME);
CREATE INDEX APP_SPRING_SESSION_IX3 ON APP_SPRING_SESSION (PRINCIPAL_NAME);
CREATE TABLE APP_SPRING_SESSION_ATTRIBUTES (
SESSION_PRIMARY_ID CHAR(36) NOT NULL,
ATTRIBUTE_NAME VARCHAR(200) NOT NULL,
ATTRIBUTE_BYTES BYTEA NOT NULL,
CONSTRAINT APP_SPRING_SESSION_ATTRIBUTES_PK PRIMARY KEY (SESSION_PRIMARY_ID, ATTRIBUTE_NAME),
CONSTRAINT APP_SPRING_SESSION_ATTRIBUTES_FK FOREIGN KEY (SESSION_PRIMARY_ID) REFERENCES APP_SPRING_SESSION(PRIMARY_ID) ON DELETE CASCADE
);
Does anyone know how to fix the problem?
These errors mean that there are already records with such keys in your database.
You can clear the database or change the keys and the Insert queries.

H2DB - executeUpdate() returns 0 or 1 on DELETE depending on table definition

I wonder if someone could explain the behaviour of the H2 JDBC driver when deleting an entry from a rather simple table.
When using the following table definition, the method executeUpdate() for a PreparedStatement instance returns 1 if one entry has been deleted (expected behaviour).
CREATE TABLE IF NOT EXISTS "MATERIAL" (
"CODE" VARCHAR(5) NOT NULL,
"NAME" VARCHAR(100) NOT NULL
);
When adding a PRIMARY KEY constraint on the CODE column, the same method returns 0 although the entry gets deleted successfully (behaviour not expected).
CREATE TABLE IF NOT EXISTS "MATERIAL" (
"CODE" VARCHAR(5) NOT NULL,
"NAME" VARCHAR(100) NOT NULL,
PRIMARY KEY ("CODE")
);
Most interestingly, when adding an INT typed column to serve as PRIMARY KEY the return value is 1 again:
CREATE TABLE IF NOT EXISTS "MATERIAL" (
"ID" INT NOT NULL AUTO_INCREMENT,
"CODE" VARCHAR(5) NOT NULL,
"NAME" VARCHAR(100) NOT NULL,
PRIMARY KEY ("ID")
);
Is someone able to reconstruct this behaviour and probably somehow explain it to me?
I have included the current version of H2 DB using maven.
EDIT:
If I eventually add a UNIQUE constraint for the CODE column, the return value is 0 again ...
CREATE TABLE IF NOT EXISTS "MATERIAL" (
"ID" INT NOT NULL AUTO_INCREMENT,
"CODE" VARCHAR(5) NOT NULL UNIQUE,
"NAME" VARCHAR(100) NOT NULL,
PRIMARY KEY ("CODE")
);
EDIT 2:
The query used to delete an entry looks like the following (used in PreparedStatement):
DELETE FROM MATERIAL WHERE CODE = ?
SOLUTION:
I'm sorry to have you bothered with this. Actually, there was no problem with the table definition or the JDBC driver. It was my test data - from earlier testing I had wanted to INSERT two entries having the same CODE. It was a multiple row insert - obviously this failed, when CODE was the PK or having a UNIQUE index. Thus, in this cases executeUpdate() could only return 0 because there was no data in the table at all.

H2 Schema initialization. Syntax error in SQL statement

I have a spring boot application and I trying to initialize some data on application startup.
This is my application properties:
#Database connection
spring.datasource.url=jdbc:h2:mem:test_db
spring.datasource.username=...
spring.datasource.password=...
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.initialize=true
spring.datasource.schema=schema.sql
spring.datasource.data=schema.sql
#Hibernate configuration
#spring.jpa.hibernate.ddl-auto = none
This is schema.sql:
CREATE TABLE IF NOT EXISTS `Person` (
`id` INTEGER PRIMARY KEY AUTO_INCREMENT,
`first_name` VARCHAR(50) NOT NULL,
`age` INTEGER NOT NULL,
PRIMARY KEY(`id`)
);
and data.sql
INSERT INTO `Person` (
`id`,
`first_name`,
`age`
) VALUES (
1,
'John',
20
);
But I got 'Syntax error in SQL statement' on application startup:
19:08:45.642 6474 [main] INFO o.h.tool.hbm2ddl.SchemaExport - HHH000476: Executing import script '/import.sql'
19:08:45.643 6475 [main] ERROR o.h.tool.hbm2ddl.SchemaExport - HHH000388: Unsuccessful: CREATE TABLE Person (
19:08:45.643 6475 [main] ERROR o.h.tool.hbm2ddl.SchemaExport - Syntax error in SQL statement "CREATE TABLE PERSON ( [*]"; expected "identifier"
Syntax error in SQL statement "CREATE TABLE PERSON ( [*]"; expected "identifier"; SQL statement:
I can't understand, what's wrong with this SQL.
Try this code. Remove PRIMARY KEY(id) and execute it.
CREATE TABLE IF NOT EXISTS `Person` (
`id` INTEGER PRIMARY KEY AUTO_INCREMENT,
`first_name` VARCHAR(50) NOT NULL,
`age` INTEGER NOT NULL
);
This error results from the structure of the CREATE TABLE declaration.
It will be the result when you have an extra comma in the end of your SQL declaration--no column declaration following the comma. For example:
CREATE TABLE IF NOT EXISTS `Person` (
`id` INTEGER PRIMARY KEY AUTO_INCREMENT,
`first_name` VARCHAR(50) NOT NULL,
`age` INTEGER NOT NULL, --note this line has a comma in the end
);
That's because CREATE TABLE expects a list of the columns that will be created along with the table, and the first parameter of the column is the identifier. As you check here, the column declaration follows the structure:
identifier datatype <constraints> <autoincrement> <functions>
Thus, in your case, as #budthapa and #Vishwanath Mataphati have mentioned, you could simply remove the PRIMARY KEY(id) line from the CREATE TABLE declaration. Moreover, you have already stated that id is a primary key on the first line of the column definitions.
In case you do not have a statement as the PRIMARY KEY declaration, be sure to check for the extra comma following your last column declaration.
Try this, as you have used Table_name
CREATE TABLE IF NOT EXISTS Person (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(50) NOT NULL,
age INTEGER NOT NULL
);
I was add below in to application.properties and it work for me
spring.jpa.properties.hibernate.globally_quoted_identifiers=true
spring.jpa.properties.hibernate.globally_quoted_identifiers_skip_column_definitions = true
What helped in my case was removing single quotes from the table name in my insert query
I had to change this:
INSERT INTO 'translator' (name, email) VALUES ('John Smith', 'john#mail.com');
to this:
INSERT INTO translator (name, email) VALUES ('John Smith', 'john#mail.com');
You set auto increment id, so you can't insert new record with id.
Try INSERT INTO `Person` (
`first_name`,
`age`
) VALUES (
'John',
20
);
I ran into same issue. I fixed that with these application.properties:
spring.jpa.properties.hibernate.connection.charSet=UTF-8
spring.jpa.properties.hibernate.hbm2ddl.import_files_sql_extractor=org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor
Some issue with multi-line and default encoding.

Resources