PostgreSQL 9.4 create table if not exists - ddl

I created tables on heroku using the following DDL.
CREATE TABLE IF NOT EXISTS "Team"(
"id" SERIAL,
"name" varchar(50) NOT NULL,
"description" varchar(255)
);
CREATE TABLE IF NOT EXISTS "Member"(
"id" SERIAL,
"name" varchar(50) NOT NULL,
"emp_number" integer NOT NULL,
"position" varchar(100) NOT NULL,
"team_id" integer references "Team"("id")
);
I got the following error:
play.api.UnexpectedException: Unexpected exception[ProvisionException: Unable to provision, see the following errors:
1) Error injecting constructor, javax.persistence.PersistenceException: Unable to execute JPA schema generation create command [CREATE TABLE IF NOT EXISTS "Team"(]
at play.db.jpa.DefaultJPAApi$JPAApiProvider.<init>(DefaultJPAApi.java:35)
at play.db.jpa.DefaultJPAApi$JPAApiProvider.class(DefaultJPAApi.java:30)
...
1 error]
at play.api.http.DefaultHttpErrorHandler.onServerError(HttpErrorHandler.scala:191) ~[com.typesafe.play.play_2.11-2.4.2.jar:2.4.2]
at play.api.http.HttpErrorHandlerExceptions$.throwableToUsefulException(HttpErrorHandler.scala:261) ~[com.typesafe.play.play_2.11-2.4.2.jar:2.4.2]
at play.api.GlobalSettings$class.onError(GlobalSettings.scala:179) [com.typesafe.play.play_2.11-2.4.2.jar:2.4.2]
...
Caused by: com.google.inject.ProvisionException: Unable to provision, see the following errors:
1) Error injecting constructor, javax.persistence.PersistenceException: Unable to execute JPA schema generation create command [CREATE TABLE IF NOT EXISTS "Team"(]
at play.db.jpa.DefaultJPAApi$JPAApiProvider.<init>(DefaultJPAApi.java:35)
...
1 error
at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1025) ~[com.google.inject.guice-4.0.jar:na]
at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1051) ~[com.google.inject.guice-4.0.jar:na]
...
Caused by: javax.persistence.PersistenceException: Unable to execute JPA schema generation create command [CREATE TABLE IF NOT EXISTS "Team"(]
at org.hibernate.jpa.internal.schemagen.GenerationTargetToDatabase.acceptCreateCommands(GenerationTargetToDatabase.java:64) ~[org.hibernate.hibernate-entitymanager-4.3.9.Final.jar:4.3.9.Final]
...
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at end of input
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850) ~[org.hibernate.hibernate-entitymanager-4.3.9.Final.jar:4.3.9.Final]
...
Position: 35
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2270) ~[org.postgresql.postgresql-9.4-1201-jdbc41.jar:9.4]
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1998) ~[org.postgresql.postgresql-9.4-1201-jdbc41.jar:9.4]
...
The error is quite obvious. The SQL contains errors. I am quite new to postgres sql. At least I know the current version used by heroku supports if not exists syntax but I am not sure where I went wrong.
Is anybody good at PostgreSQL here?

If you had run this query directly, you would have gotten the error:
ERROR: there is no unique constraint matching given keys for referenced table "Team"
This gives you a clue that there's something missing to identify the columns in the "Team" table uniquely. You have declared that the ids of the tables are serials, but forgot to add primary key constraints. Adding this, will let you execute the query:
CREATE TABLE IF NOT EXISTS "Team"(
"id" SERIAL primary key,
...
);
CREATE TABLE IF NOT EXISTS "Member"(
"id" SERIAL primary key,
...
);

Related

How to use keyword VALUE as a field name in H2 database

I inherited a project where in UnitTests an H2 database is being used. On the startup of the project a lot of tables are created and populated with data.
CREATE TABLE SRC_FIELD_VALUE
( ID NUMBER IDENTITY,
INPUT_SRC_FIELD_REF_ID NUMBER,
VALUE VARCHAR2(255),
DESCRIPTION VARCHAR2(255)
);
We recently migrated to the latest version of H2 : 2.1.214
In my POM.XML I added "NON_KEYWORDS=VALUE,ID" to the end of definition but still got an exception :
Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement "CREATE TABLE SRC_FIELD_VALUE ( ID NUMBER IDENTITY, INPUT_SRC_FIELD_REF_ID NUMBER, [*]VALUE VARCHAR2(255), DESCRIPTION VARCHAR2(255) )"; expected "identifier"; SQL statement:
CREATE TABLE TC_RULE_COMP_DATA ( ID NUMBER IDENTITY, RULE_REF_ID NUMBER, SORT_ORDER NUMBER, VALUE CLOB ) [42001-214]
I also tried to put double quote around "VALUE" but got the same exception. It's interesting that "ID" is not getting considered as KEYWORD though.
What are my options here? I can't rename the fields.

Spring SimpleJdbcInsert fails with 'INSERT has more target columns than expressions'

I am using a SimpleJdbcInsert to insert rows into a PostgreSQL database. However, I get an the following error:
Caused by: org.postgresql.util.PSQLException: ERROR: INSERT has more
target columns than expressions.
org.springframework.jdbc.UncategorizedSQLException:
PreparedStatementCallback; uncategorized SQLException for SQL [INSERT
INTO product (product_id,product_name,product_code,in_
stock,product_category) VALUES(?)]; SQL state [25P02]; error code [0];
ERROR: current transaction is aborted, commands ignored until end of
transaction block; nested exception is
org.postgresql.util.PSQLException: ERROR: current transaction is
aborted, commands ignored until end of transaction block
The number columns is exactly the same as the number of values I am trying to insert when I print out the MapSqlParameterSource object shown below:
Parameters Names ::
[
product_id,
product_name,
product_code,
in_ stock,
product_category
]
Parameters Values :: [{
product_id=1518,
product_name=Sofa,
product_code=150,
in_stock=true,
product_category=null,
}]
The product_id is the primary key and it is not null. Could the problem be because I am not using an auto-generated primary key? I still do not understand why that would be a problem.
The columns shown in the error message are precisely the same as the columns in the parameter list I'm printing. The values also tally with the number of columns as well, so I'm really baffled why PostgreSQL is giving this error. Please help!
I was able to solve it with a different solution to using Spring JDBC.

Spring H2 created table not found after successful creation

I am using Spring Boot's schema.sql magic to create an in memory H2 database. The script contains the following statements:
create table PERSON
(
ID BIGINT not null primary key,
NAME VARCHAR(255) not null
);
create index IDX_PERSON_NAME on PERSON (NAME);
Upon launch Spring Boo fails with the following exception:
Caused by: org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #2 of URL [file:/D:/git/.../build/resources/main/schema.sql]: create index IDX_PERSON_NAME on PERSON (NAME); nested exception is org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "PERSON" not found; SQL statement:
create index IDX_PERSON_NAME on PERSON (NAME) [42102-200]
How can the statement fail to find the table that was created in the preceding statement?
Simply because NAME is not mentioned as Unique constraint, you have only specified it as NOT NULL constraint
create table PERSON
(
ID BIGINT not null primary key,
NAME VARCHAR(255) not null,
CONSTRAINT Person_Name_Unique UNIQUE (NAME)
);
create index IDX_PERSON_NAME on PERSON (NAME);
Here are the possible reasons,
The schema needs to be mentioned on while referring to table like test_schema.person
Your syntax for creating the index might be wrong. Refer to this link for H2 Syntax,https://www.baeldung.com/spring-yaml

DBUnit fails with Oracle mixed-case column names

The problem is an existing Oracle table (that I cannot change) with mixed case column names, eg
create table BADTAB ( ID varchar(16) not null, "Name" varchar2(64),
constraint I_BADTAB_PK PRIMARY KEY(ID) );
When I try to do a DBUnit INSERT from an XML dataset it fails
Caused by: java.sql.SQLException: ORA-00904: "NAME": invalid identifier
When I enclose the column name in quotes it fails
<column>"Name"</column>
org.dbunit.dataset.NoSuchColumnException: BADTAB."NAME" - (Non-uppercase input column: "ReadingsPres") in ColumnNameToIndexes cache map.
Note that the map's column names are NOT case sensitive.
at org.dbunit.dataset.AbstractTableMetaData.getColumnIndex(AbstractTableMetaData.java:117)
...
QUESTION:
How can I override DBUnit's column metadata to make it recognize the lowercase column name?
What classes do I override and how do I inject them into the DBUnit test run?
There have been some previous discussions around this org.dbunit.dataset.NoSuchTableException: Did not find table 'xxx' in schema 'null'
You should be able to set a database configuration property to cater for case-sensitive names:
DatabaseConfig config = databaseConnection.getConfig();
config.setProperty(DatabaseConfig.FEATURE_CASE_SENSITIVE_TABLE_NAMES, true);

Can't use HSQL sequences in JUnit

I'm trying to run a JUnit test class for my Spring-Batch application. I had to create the following tables: http://static.springsource.org/spring-batch/reference/html/metaDataSchema.html. I create them in my initialization database script, including the following:
CREATE SEQUENCE BATCH_STEP_EXECUTION_SEQ;
CREATE SEQUENCE BATCH_JOB_EXECUTION;
CREATE SEQUENCE BATCH_JOB_SEQ;
The creation of all sequences and tables didn't generate any errors. But while executing my JUnit test, I get the following error:
org.springframework.dao.DataAccessResourceFailureException: Could not obtain identity(); nested exception is java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: BATCH_JOB_SEQ
at org.springframework.jdbc.support.incrementer.HsqlMaxValueIncrementer.getNextKey(HsqlMaxValueIncrementer.java:119)
That is caused when the class HsqlMaxValueIncrementer runs:
stmt.executeUpdate("insert into " + getIncrementerName() + " values(null)");
What am I doing wrong?
Thanks!!
For HSQLDB the 3 tables need the ID field.
CREATE TABLE BATCH_STEP_EXECUTION_SEQ (
ID BIGINT IDENTITY
);
CREATE TABLE BATCH_JOB_EXECUTION_SEQ (
ID BIGINT IDENTITY
);
CREATE TABLE BATCH_JOB_SEQ (
ID BIGINT IDENTITY
);
Reference: https://github.com/SpringSource/spring-batch/blob/master/spring-batch-core/src/main/resources/org/springframework/batch/core/schema-hsqldb.sql

Resources