to insert Empty value into Postgresql - postgresql

I am having a postgresql database. I am using liquibase to insert data into the tables in postgresql from CSV files.
Here I have table ABC with column of type SMALLINT.
CREATE TABLE ABC (
NAME VARCHAR(20),
REQUIRED SMALLINT DEFAULT 0,
SUMMARY VARCHAR(50)
);
My CSV
NAME,REQUIRED,SUMMARY
John,,Playing
I get the following error
liquibase.exception.DatabaseException: ERROR: syntax error at or near ","n
The changeset
<changeSet id="12345"
author="test" runOnChange="true">
<loadUpdateData
encoding="UTF-8"
file="/data/ABC.csv"
quotchar=""
separator=","
tableName="ABC">
<column name="NAME" type="STRING"/>
<column name="REQUIRED" type="NUMERIC"/>
<column name="SUMMARY" type="STRING"/>
</loadUpdateData>
</changeSet>
Can anyone please help here. Another question is , why is the default not working in this case ?

Required is defined as smallint - this means it can be any integer between -32768 and 32767 OR NULL.
NULLcan be inserted by
NAME,REQUIRED,SUMMARY
John,NULL,Playing
Something like '' can't be inserted into a int column. I assume [NULL] and empty(blank) is just a different rendering by different db tools.

Related

Postgres XMLTABLE with missing nodes

Assume Table A with an XML field. Table A has two rows, with the following XML data in the table.
Row 1
<fullname>
<firstName>John</firstName>
<lastName>Smith</lastName>
</fullname>
and Row 2
<fullname>
<firstName>Jane</firstName>
</fullname>
This query:
SELECT * FROM A
XMLTABLE(('/fullname'::text) PASSING (a.xml)
COLUMNS firstName text PATH ('firstName'::text), lastName text PATH ('lastName'::text)) a
will only return data on John and not Jane. Is there a work around for this?
https://www.postgresql.org/docs/13/functions-xml.html
"default X" resolved the issue.

Mybatis Insert PK manually

I am trying to single insert data into table with assigned PK. Manually assiging PK.
XML file
<insert id = "insertStd" parameterType = "com.org.springboot.dao.StudentEntity" useGeneratedKeys = "false" keyProperty = "insertStd.id", keyColumn = "id">
INSERT INTO STUDENT (ID, NAME, BRANCH, PERCENTAGE, PHONE, EMAIL )
VALUES (ID=#{insertStd.id}, NAME=#{insertStd.name}, BRANCH=#{insertStd.branch}, PERCENTAGE=#{insertStd.percentage}, PHONE=#{insertStd.phone}, EMAIL =#{insertStd.email});
</insert>
Service call method
public boolean saveStudent(Student student){
LOGGER.info("Student object save");
int savedId= studentMapper.insertStd(student);
}
Log file
org.springframework.jdbc.badsqlgrammarexception
### Error updating database Causes: cause org.postgresql.util.psqlexception error column id does not exist
HINT: There is a column named "id" in the table "student" but it can't be referenced from this part of the query.
Position 200
### Error may exist in file [c:\.....\StudentMapper.xml]
### Error may involve in com.org.springboot.dao.StudentMapper.insertStd-InLine
### The error occurred while setting parameters
### SQL INSERT INTO STUDENT (ID, NAME, BRANCH, PERCENTAGE, PHONE, EMAIL )
VALUES (ID=?, NAME=?,BRANCH=?, PERCENTAGE=?, PHONE=?, EMAIL=?);
### cause org.postgresql.util.psqlexception ERROR column "id" doesn't exist. //It did worked with JPA id assigned manually.
### There is a column named "ID" in the table "STUDENT", Bbut it cannot be referenced from the part of the query.
The INSERT statement of malformed. The VALUES clause should not include the column names.
Also, since there's no primary auto-generation, you can remove all the other attributes. Just leave the mapper id.
Note: if you want to manually assign the PK value, you need to make sure the table does not have a GENERATED ALWAYS clause for the column. If this is the case, the table will ignore the value you are providing and will use its own rules to generate the PK.
Use:
<insert id="insertStd">
INSERT INTO STUDENT (ID, NAME, BRANCH, PERCENTAGE, PHONE, EMAIL)
VALUES (
#{insertStd.id}, #{insertStd.name}, #{insertStd.branch},
#{insertStd.percentage}, #{insertStd.phone}, #{insertStd.email}
);
</insert>
Your error is easily reproduceable:
create table t (a int, b varchar(10));
insert into t (a, b) values (123, 'ABC'); -- succeeds
insert into t (a, b) values (a=123, b='ABC'); -- fails!
error: column "a" does not exist
See the Fiddle.

Querying one to many relationship in an XML Column

I have an XML column in a table.
The table looks has two columns:
ID
DepartmentXML
The DepartmentXML typically looks like this:
<Root>
<Department>
<dID>100</dID>
<DName>Engineering</DName>
</Department>
<Employee>
<EmployeeID>999</EmployeeID>
<EName>AAA BBB</EName>
</Employee>
<Employee>
<EmployeeID>888</EmployeeID>
<EName>XXX YYY</EName>
</Employee>
</Root>
How to query this XML, to get result like this?
+------------------------------------------+
|dID|DepartmentName|EmployeeID|EmployeeName|
+------------------------------------------+
|100|Engineering |999 |AAA BBB |
|100|Engineering |888 |XXX YYY |
+------------------------------------------+
I know CROSS APPLY may have to be used, but the syntax for this particular scenario is very difficult for me to understand.
Thank you.
Try it like this:
First a mockup table to simulate your issue:
DECLARE #tbl TABLE(ID INT IDENTITY, DepartmentXml XML);
INSERT INTO #tbl VALUES
(N'<Root>
<Department>
<dID>100</dID>
<DName>Engineering</DName>
</Department>
<Employee>
<EmployeeID>999</EmployeeID>
<EName>AAA BBB</EName>
</Employee>
<Employee>
<EmployeeID>888</EmployeeID>
<EName>XXX YYY</EName>
</Employee>
</Root>');
--The query
SELECT t.ID
,t.DepartmentXml.value('(/Root/Department/dID/text())[1]','int') AS DepartmentId
,t.DepartmentXml.value('(/Root/Department/DName/text())[1]','nvarchar(max)') AS DepartmentName
,A.e.value('(EmployeeID/text())[1]','int') AS EmployeeId
,A.e.value('(EName/text())[1]','nvarchar(max)') AS EmployeeName
FROM #tbl t
OUTER APPLY t.DepartmentXml.nodes('/Root/Employee') A(e);
The idea in short:
We can pick the row's ID directly
We can read the department's information directly from the XML (non-repeating)
We can retrieve repeating nodes using APPLY with .nodes().
We can use a relative XPath against A.e to get the employee's data

insert empty date on unitils dataset

I got error similar to this: Unitils dataset - insert into sybase datetime column
My case is that need to insert a date value that is empty. Empty String does not do the thing. Can anyone help me?
If you leave your date element off of the row definition, it won't add anything in that field. So with a table definition of:
CREATE TABLE Table (
id INTEGER,
name VARCHAR,
birthDate DATE
);
create a row like this:
<table id="3" name="Katie"/>
<table id="4" name="Christie" birthDate="2001-04-22"/>
to load an empty date in ID 3.

IBM DB2 recreate index on truncated table

After truncating table, and inserting new values in table, auto-increment values are not set to started value 1. When inserting new values it's remember last index-ed value of auto-increment.
Colum in table named: ID
Index: PRIMARY,
Initial Value: 1
Cache size: 1
Increment: 1
[checked on IBM DB2 Control Center]
This query:
TRUNCATE TABLE ".$this->_schema.$table." DROP STORAGE IGNORE DELETE TRIGGERS IMMEDIATE
table is EMPTY.
After INSERT NEW VALUES example: INSERT INTO DB2INST1.db (val) VALUES ('abc') it's INSERT with LAST
ID | val
55 | abc
But it SHOULD BE:
ID | val
1 | abc
I'm guessing here that your question is "how do you restart the IDENTITY sequence?" If that is the case, then you can reset it with the following SQL:
ALTER TABLE <table name> ALTER COLUMN <IDENTITY column> RESTART WITH 1
However, like #Ian said, what you are seeing is the expected behavior of a TRUNCATE.
First select in TABLE SCHEMA WHERE is name of IDENTITY column:
Query 1:
SELECT COLNAME FROM SYSCAT.COLUMNS WHERE TABSCHEMA = 'DB2INST1' AND
TABNAME = 'DB' AND IDENTITY = 'Y'
Then, truncate table and return it's example: ID for altering index:
Query 2:
This ID puts on query for reset and altering index identity:
ALTER TABLE DB2INST1.DB ALTER COLUMN ID RESTART WITH 1
Change ID above returned from Query 1, which returns name of ID to Query 2.
SOLVED!