FNH Mappings with DB2 GeneratedBy Identity - db2

I am trying to map a table with an identity key field.
When I try to save I get the error SQL0803 Duplicate key value specified
INSERT INTO libpjk/Audit (AuditId, AuditDate, UserId, Keys, ValBefore, ValAfter, FieldId) VALUES (default, ?, ?, ?, ?, ?, ?)
I'm thinking the AuditId should not appear in the field list and the value of default should not be there either. I just don't know how to do this.
SQL for the table creation:
CREATE TABLE libpjk.Audit (
AuditId integer not null GENERATED ALWAYS AS IDENTITY
(START WITH 1, INCREMENT BY 1),
AuditDate timestamp not null,
UserId char(10) not null,
FieldId integer not null,
Keys varchar(50) not null,
ValBefore varchar(50),
ValAfter varchar(50),
CONSTRAINT libpjk.pk_Audit PRIMARY KEY(FieldId))
Here's how the AuditId is defined in my Audit class:
<Required()> Public Overridable Property AuditId As Integer
here's my mappings:
MyBase.New()
Table("libpjk/Audit")
LazyLoad()
Id(Function(x) x.AuditId).Column("AuditId").GeneratedBy.Identity()
References(Function(x) x.AuditField).Column("FieldId")
Map(Function(x) x.Timestamp).Column("AuditDate").Not.Nullable()
Map(Function(x) x.UserId).Column("UserId").Not.Nullable()
Map(Function(x) x.Keys).Column("Keys").Not.Nullable()
Map(Function(x) x.Value_Before).Column("ValBefore")
Map(Function(x) x.Value_After).Column("ValAfter")
Thanks for your help

Related

Default constraint not being enforced

Given the following table definition:
CREATE TABLE ControlledSubstances.NationalDrugCode
(
NationalDrugCodeID INT NOT NULL
,NationalDrugCode VARCHAR(20) NOT NULL
,Product VARCHAR(100)
,Ingredient VARCHAR(500)
,ClassID VARCHAR(50)
,Class VARCHAR(50)
,DrugEnforcementAgencyClassID VARCHAR(50)
,DrugEnforcementAgencyClass VARCHAR(50)
,GenericDrug VARCHAR(50)
,Form VARCHAR(50)
,Drug VARCHAR(50)
,StrengthPerUnit NUMERIC(6,2)
,UnitOfMeasure VARCHAR(50)
,ConversionFactor NUMERIC(4,2)
,LongOrShortActing VARCHAR(50)
,IsPreventionForStates BIT NOT NULL
)
;
ALTER TABLE ControlledSubstances.NationalDrugCode
ADD CONSTRAINT PK_ControlledSubstances_NationalDrugCode PRIMARY KEY (NationalDrugCodeID)
,CONSTRAINT DF_ControlledSubstances_NationalDrugCode_IsPreventionForStates DEFAULT 0 FOR IsPreventionForStates
;
CREATE UNIQUE INDEX UQ_ControlledSubstances_NationalDrugCode_NationalDrugCode ON ControlledSubstances.NationalDrugCode (NationalDrugCode);
Why would I be receiving an error on insert for the column I defined as NOT NULL and created a default constraint of 0? I know I can handle the logic in the insert statement to not pass in NULL values, but I use this logic in multiple tables and have never gotten an error before. The error I receive is:
Cannot insert the value NULL into column 'IsPreventionForStates', table 'Staging.ControlledSubstances.NationalDrugCode'; column does not allow nulls. INSERT fails.
This will happen if you explicitly provide NULL as its value. The default constraint only kicks in when you don't supply a value at all, or when you use the DEFAULT keyword:
For example, if NationalDrugCodeID and IsPreventionForStates were your only two columns in the table (for illustration), this will fail:
INSERT INTO NationalDrugCode(NationalDrugCodeID, IsPreventionForStates) VALUES (5, NULL);
But either of these would work:
INSERT INTO NationalDrugCode(NationalDrugCodeID) VALUES (5);
INSERT INTO NationalDrugCode(NationalDrugCodeID, IsPreventionForStates) VALUES (5, DEFAULT);
In the edge case where you need ALL columns to have default values inserted, you can use:
INSERT INTO NationalDrugCode DEFAULT VALUES;

Default ID with Korma and Postgresql?

I have the following schema:
CREATE TABLE IF NOT EXISTS art_pieces
(
-- Art Data
ID SERIAL PRIMARY KEY,
title TEXT NOT NULL,
description TEXT,
price INT NULL,
-- Relations
artists_id INT NULL
);
--;;
CREATE TABLE IF NOT EXISTS artists
(
-- Art Data
ID SERIAL PRIMARY KEY,
name TEXT NOT NULL
);
This is the corresponding art-piece entity:
(defentity art-pieces
(table :art_pieces)
(entity-fields
:id
:title
:description
:price
:artists_id)
(belongs-to artists))
I'm wondering why the following returns PSQLException ERROR: null value in column "id" violates not-null constraint:
(create-piece {:title "The Silence of the Lambda"
:description "Something something java beans and a nice chianti"
:price 5000})
Shouldn't the ID SERIAL PRIMARY KEY field populate automatically? Is this something to do with Korma's interaction with PSQL?
INSERT INTO "art_pieces" ("description", "id", "price", "title") VALUES (?, NULL, ?, ?)
The problem here is that you try to insert NULL value into id column. Default value is inserted only if you omit the column or use DEFAULT keyword (instead of NULL).
To insert the next value of the sequence into the serial column, specify that the serial column should be assigned its default value. This can be done either by excluding the column from the list of columns in the INSERT statement, or through the use of the DEFAULT key word
PostgreSQL Serial Types
So you have to change the query to:
INSERT INTO "art_pieces" ("description", "id", "price", "title") VALUES (?, DEFAULT, ?, ?)
-- or
INSERT INTO "art_pieces" ("description", "price", "title") VALUES (?, ?, ?)
Another workaround (in case you don't have permissions to change the query) would be to add a trigger function that will replace NULL value in id column automatically:
CREATE OR REPLACE FUNCTION tf_art_pieces_bi() RETURNS trigger AS
$BODY$
BEGIN
-- if insert NULL value into "id" column
IF TG_OP = 'INSERT' AND new.id IS NULL THEN
-- set "id" to the next sequence value
new.id = nextval('art_pieces_id_seq');
END IF;
RETURN new;
END;
$BODY$
LANGUAGE plpgsql;
CREATE TRIGGER art_pieces_bi
BEFORE INSERT
ON art_pieces
FOR EACH ROW EXECUTE PROCEDURE tf_art_pieces_bi();

Storing timestamp in PostgreSQL gives an error: "cannot cast type bigint to timestamp without time zone"

I've created my table with the following code:
CREATE TABLE "STORES" (
"STOREGLOBALID" SERIAL NOT NULL ,
"STOREUPDATEDATETIME" TIMESTAMP NOT NULL,
"CHAINID" BIGINT ,
"CHAINNAME" VARCHAR(50) ,
"SUBCHAINID" SMALLINT ,
"SUBCHAINNAME" VARCHAR(50) ,
"STOREID" SMALLINT ,
"STORENAME" VARCHAR(50) ,
"STORETYPE" SMALLINT ,
"ADDRESS" VARCHAR(50) ,
"CITY" VARCHAR(50) ,
PRIMARY KEY ("STOREGLOBALID")
);
When I try to insert timestamp by using the following SQL for preparing statement:
INSERT INTO "STORES"
("STOREGLOBALID",
"STOREUPDATEDATETIME",
"CHAINID",
"CHAINNAME",
"SUBCHAINID",
"SUBCHAINNAME",
"STOREID",
"STORENAME",
"STORETYPE",
"ADDRESS",
"CITY")
VALUES (DEFAULT, cast(? as timestamp), ?, ?, ?, ?, ?, ?, ?, ?, ?)
And the following Java code:
ps = con.prepareStatement(sql);
ps.setLong(1, store.getChainId());
ps.setTimestamp(2, new Timestamp(1000000000)); //this value is only for test purposes, actual value gives the same error
I get the following error:
cannot cast type bigint to timestamp without time zone Position: 235
I understand that I need to provide a timestamp, but when I do it as following:
ps.setTimestamp(2, new Timestamp(1000000000), Calendar.getInstance(TimeZone.getTimeZone("UTC")));
I get the same error. What am I doing wrong? Thank you.
The first argument of your prepared statement is used in
cast(? as timestamp)
and the result is stored in STOREUPDATEDATETIME, of type TIMESTAMP. And you're passing a long (store.getChainId()) as argument. So you're trying to cast a long to a timestamp.
The second argument of your prepared statement is stored in CHAINID, of type BIGINT. And you're passing a Timestamp as argument (new Timestamp(1000000000)). So PostgreSQL tries to transform this timestamp into a bigint.
The SQL should be
INSERT INTO "STORES"
("STOREGLOBALID",
"STOREUPDATEDATETIME",
"CHAINID",
"CHAINNAME",
"SUBCHAINID",
"SUBCHAINNAME",
"STOREID",
"STORENAME",
"STORETYPE",
"ADDRESS",
"CITY")
VALUES (DEFAULT, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
And the Java should be
ps.setTimestamp(1, new Timestamp(1000000000));
ps.setLong(2, store.getChainId());

Notnull and empty string in My SQL

Hy I have problem. I wanna to create table with some atributes, and some of them shoud be specified as NOT NULL.. And here comes the problem. When I insert some data into table, and when I insert '' (empty single string) it input data into table, but I dont want this... How to restrict inserting data from inputing single string or inputing nothing..
here are my table
CREATE TABLE tbl_Film
(
ID INT UNSIGNED PRIMARY KEY,
Naziv VARCHAR(50) NOT NULL,
Zanr VARCHAR(50) NOT NULL,
Opis VARCHAR(150) NULL,
Kolicina INT UNSIGNED NOT NULL
);
INSERT INTO tbl_Film VALUES (1,'','Animirani','Mala ribica',2)
This input blank data into Naziv, and I don't want that.. I need to restrict that..
http://prntscr.com/21gfgd
I dont know if this is possible in SQL, but why dont you exchange the '' in your application into the String NULL?
In SQL, NULL is not the same as '' (with the exception of MS SQL via OleDB AFAIR, in which '' should be stored as NULL).
NULL values represent missing unknown data.
See http://www.w3schools.com/sql/sql_null_values.asp
In regular SQL, you should use a CHECK constraint, e.g.
CREATE TABLE tbl_Film (
ID INT UNSIGNED PRIMARY KEY,
Naziv VARCHAR(50) NOT NULL,
Zanr VARCHAR(50) NOT NULL,
Opis VARCHAR(150) NULL,
Kolicina INT UNSIGNED NOT NULL,
CHECK (Naziv <> '')
);
Sadly, this CHECK constraint is NOT implemented by MySQL:
The CHECK clause is parsed but ignored by all storage engines.
See http://dev.mysql.com/doc/refman/5.7/en/alter-table.html
So the only solution I see, at DB level, is to write a P/SQL trigger...

ORA-00913: too many values Error (Even though I have checked my table and entries)

Here's is the table :
create table Student(
student_id char(6) primary key,
name varchar(10) not null,
department char(20),
grade char(6),
percentage smallint,
contact_no char(12),
address varchar(50)
);
This is what I'm inserting :
insert into Student
values ('ST-01','Zain','coe','A+',74,'9999777865','New Delhi');
Why ORA-00913: too many values error when I'm not inserting extra values ?