I'm using MyBatis as DB framework in JAVA and I'm trying to generate automatically two values when inserting rows in a table: the task id and another value. This is my query:
<insert id="insertTwoValuesSequentialluy" parameterType="com.example.autogenerated.Task" >
<selectKey resultType="java.lang.String" keyProperty="taskId" order="BEFORE" >
select MY_TASK_ID_SEQUENCE.nextval from dual
</selectKey>
insert into DYDA_D.TASK_TABLE (taskId, otherVariable, autogeneratedValue)
values ( #{taskId,jdbcType=VARCHAR},
#{otherVariable,jdbcType=VARCHAR},
MY_SECOND_SEQUENCE.nextval = #{autogeneratedValue,jdbcType=VARCHAR})
</insert>
The code works fine but I'm having the following problem: while at runtime the Task instance gets its member taskId setted, it doesn't happen the same with autogeneratedValue, although when I check the database I can see the column matching autogeneratedValue isn't null for this new row. How can I get autogeneratedValue setted at runtime with no need of making a select query?
PS: don't pay attention to commas and the like, I have lots of columns and I've deleted most of them and changed names on the rest for this snippet. My point with the code is for you to see how I've generated the values, tags I've used etc.
You can do this like this:
<insert id="insertTwoValuesSequentialluy"
parameterType="com.example.autogenerated.Task"
useGeneratedKeys="true"
keyProperty="taskId,autogeneratedValue"
keyColumn="taksId,autogeneratedValue">
insert into DYDA_D.TASK_TABLE (taskId, otherVariable, autogeneratedValue)
values (MY_TASK_ID_SEQUENCE.nextval,
#{otherVariable,jdbcType=VARCHAR},
MY_SECOND_SEQUENCE.nextval)
</insert>
Related
I'm trying to write a java sql query, the simplified table would be table(name,version) with a unique constraint on (name, version).
I'm trying to insert a row into my database with a conditional statement. Meaning that when a entry with the same name exists, it should insert the row with same name and its version increased by 1.
I have tried with the following:
INSERT INTO table(name,version)
VALUES(?, CASE WHEN EXISTS(SELECT name from table where name=?)
THEN (SELECT MAX(version) FROM table WHERE name = ?) +1
ELSE 1 END)
values are sent by user.
My question is, how can I access the 'name' inside the values so I could compare them?
If you want to write this as a single query:
INSERT INTO table (name, version)
SELECT ?, COLAESCE(MAX(t2.version) + 1, 1)
FROM table t2
WHERE t2.name = ?;
That said, this is dangerous. Two threads could execute this query "at the same time" and possibly create the same version number. You can prevent this from happening by adding a unique index/constraint on (name, version).
With the unique index/constraint, one of the updates will fail if there is a conflict.
I see at least two approaches:
1. For each pair of name and version you first query the max version:
SELECT MAX(VERSION) as MAX FROM <table> WHERE NAME = <name>
And then you insert the result + 1 with a corresponding insert query:
INSERT INTO <table>(NAME,VERSION) VALUES (<name>,result+1)
This approach is very straight-forward, easy-to-read and implement, however, not really performant because of so many queries necessary.
You can achieve that with sql alone with sql analytics and window functions, e.g.:
SELECT NAME, ROW_NUMBER() over (partition BY NAME ORDER BY NAME) as VERSION FROM<table>
You can then save the result of this query as a table using CREATE TABLE as SELECT...
(The assumption here is that the first version is 1, if it is not the case, then one could slightly rework the query). This solution would be very performant even for large datasets.
You should get the name before insertion. In your case, if something went wrong then how would you know about it so you get the name before insert query.
Not sure but you try this:
declare int version;
if exists(SELECT name from table where name=?)
then
version = SELECT MAX(version) FROM table WHERE name = ?
version += 1
else
version = 1
end
Regards.
This is actually a bad plan, you might be changing what the user's specified data. That is likely to not be what is desired, maybe they're not trying to create a new version but just unaware that the one wanted already exists. But, you can create a function, which your java calls, not only inserts the requested version or max+1 if the requested version already exists. Moreover it returns the actual values inserted.
-- create table
create table nv( name text
, version integer
, constraint nv_uk unique (name, version)
);
-- function to create version or 1+max if requested exists
create or replace function new_version
( name_in text
, version_in integer
)
returns record
language plpgsql strict
as $$
declare
violated_constraint text;
return_name_version record;
begin
insert into nv(name,version)
values (name_in,version_in)
returning (name, version) into return_name_version;
return return_name_version;
exception
when unique_violation
then
GET STACKED DIAGNOSTICS violated_constraint = CONSTRAINT_NAME;
if violated_constraint like '%nv\_uk%'
then
insert into nv(name,version)
select name_in, 1+max(version)
from nv
where name = name_in
group by name_in
returning (name, version) into return_name_version;
return return_name_version;
end if;
end;
$$;
-- create some data
insert into nv(name,version)
select 'n1', gn
from generate_series( 1,3) gn ;
-- test insert existing
select new_version('n2',1);
select new_version('n1',1);
select *
from nv
order by name, version;
<insert id="insertIntoScheduleReportUserLink" parameterType="com.mypackage.model.ScheduleReport">
<selectKey keyProperty="id" resultType="java.lang.Integer" order="BEFORE">
select NEXTVAL('schedule_report_user_link_sequence')
</selectKey>
INSERT INTO schedule_report_user_link(
id, schedule_report_detail_id, to_user_id)
<foreach collection="selectedUsers" item="user" separator=",">
VALUES (#{id}, #{scheduleReportDetail.id}, #{user.id})
</foreach>;
</insert>
Here I am using for each loop to multiple insert. I need to know if selectKey generate new id for each insert?
Is there any better approach?
The loop is running only of the insert section not on the key generation part.
So its seems the key will be generated once.
Don't depend on hypothesis run for a little data and see it for your self.
With jooq 3.4 I can't figure out how to do this (with Postgresql):
Query query = dsl.insertInto(TABLE)
.set(TABLE.ID, Sequences.TABLE_ID_SEQ.nextval());
but in a case when I don't know which is the exact table, something like this:
TableImpl<?> tableImpl;
Query query = dsl.insertInto(tableImpl)
.set(tableImpl.getIdentity(), tableImpl.getIdentity().getSequence().nextval());
Is it somehow possible?
I tried this:
dsl.insertInto(tableImpl)
.set(DSL.field("id"),
tableImpl.getSchema().getSequence("table_id_seq").nextval())
This works but I still don't know how to get the sequence name from the TableImpl object.
Is there a solution for this? Or is there a problem with my approach?
In plain SQL I would do this:
insert into table_A (id) VALUES nextval('table_A_id_seq');
insert into table_B (table_A_id, some_val) VALUES (currval('table_A_id_seq'), some_val);
So I need the value or a reference to that id for later use of the id that was generated for the inserted record as default, but I don't want to set any other values.
jOOQ currently doesn't have any means of associating a table with its implicitly used sequence for the identity column. The reason for this is that the sequence is generated when the table is created, but it isn't formally connected to that table.
Usually, you don't have to explicitly set the serial value of a column in a PostgreSQL database. It is generated automatically on insert. In terms of DDL, this means:
CREATE TABLE tablename (
colname SERIAL
);
is equivalent to specifying:
CREATE SEQUENCE tablename_colname_seq;
CREATE TABLE tablename (
colname integer NOT NULL DEFAULT nextval('tablename_colname_seq')
);
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;
The above is taken from:
http://www.postgresql.org/docs/9.3/static/datatype-numeric.html#DATATYPE-SERIAL
In other words, just leave out the ID values from the INSERT statements.
"Empty" INSERT statements
Note that if you want to create an "empty" INSERT statement, i.e. a statement where you pass no values at all, generating a new column with a generated ID, you can use the DEFAULT VALUES clause.
With SQL
INSERT INTO tablename DEFAULT VALUES
With jOOQ
DSL.using(configuration)
.insertInto(TABLENAME)
.defaultValues()
.execute();
Returning IDs
Note that PostgreSQL has native support for an INSERT .. RETURNING clause, which is also supported by jOOQ:
With SQL
INSERT INTO tablename (...) VALUES (...) RETURNING ID
With jOOQ
DSL.using(configuration)
.insertInto(TABLENAME, ...)
.values(...)
.returning(TABLENAME.ID)
.fetchOne();
I would like to use the db2 merge statement submitting it as a statement from jdbc.
I am in the following scenario. I'm working with a proprietary persistence layer and I'm handling an entity I don't know whether it's already persisted or not and I would like to use the merge statement in order to insert or update a row on the database.
Is it possible?
Suppose I'm working with the table people with three columns: id, name, surname and I'm handling an entity with id="5", name="chuck", surname="norris" Am I able to issue:
MERGE INTO people AS t
USING (select '5' as id, 'chuck' as name, 'norris' as surname from SYSIBM.SYSDUMMY1)As s
ON (t.id = s.id)
WHEN MATCHED THEN
UPDATE SET t.name=s.name, t.surmane=s.surname
WHEN NOT MATCHED THEN
INSERT
(id, name, surname)
VALUES (s.id, s.name, s.surname)
such a statement? I'm trying to do that but I got an error. I don't think it's allowed to use a select after USING:
USING (select '5' as id, 'chuck' as name, 'norris' as surname from SYSIBM.SYSDUMMY1)As s
I also tryed to do:
USING VALUES('5','chuck','norris') AS s(id,chuck,norris)
but it dosn't work. Any help would be appreciated.
Besides, does anybody know if it's possible to use such a statement in a prepared statement, replacing the real values expressed into the USING part with '?' placeholders in order to set them to the prepared statement using the setXXX() methods?
Thanks
Thanks
Fil
The syntax for MERGE for your data would be something like this, assuming you're using DB2 Linux/Unix/Windows (LUW). The VALUES clause goes inside the parenthesis for the USING part.
Also, if you are using LUW, you cannot dynamically prepare a MERGE (I.E., your query can't have parameter markers) in LUW 9.5 or less. This was added in LUW 9.7.
MERGE INTO people AS t USING (
VALUES (5, 'Chuck', 'Norris'),
(6, 'John', 'Smith'),
(7, 'Abraham', 'Lincoln')
-- maybe more rows
) AS s (id, name, surname)
ON t.id = s.id
WHEN MATCHED THEN
UPDATE SET t.name=s.name, t.surname=s.surname
WHEN NOT MATCHED THEN
INSERT (id, name, surname)
VALUES (s.id, s.name, s.surname)
However, your actual problem with the fullselect may be that you have some typos in your query... for example "surmane" in UPDATE SET t.name=s.name, t.surmane=s.surname
If I have a SQL table with columns:
NR_A, NR_B, NR_C, NR_D, R_A, R_B, R_C
and on runtime, I add columns following the column's sequence such that the next column above would be R_D followed by R_E.
My problem is I need to reset the values of columns that starts with R_ (labeled that way to indicate that it is resettable) back to 0 each time I re-run my script . NR_ columns btw are fixed, so it is simpler to just say something like:
UPDATE table set col = 0 where column name starts with 'NR_'
I know that is not a valid SQL but I think its the best way to state my problem.
Any thoughts?
EDIT: btw, I use postgres (if that would help) and java.
SQL doesn't support dynamically named columns or tables--your options are:
statically define column references
use dynamic SQL to generate & execute the query/queries
Java PreparedStatements do not insulate you from this--they have the same issue, just in Java.
Are you sure you have to add columns during normal operations? Dynamic datamodels are most of the time a realy bad idea. You will see locking and performance problems.
If you need a dynamic datamodel, take a look at key-value storage. PostgreSQL also has the extension hstore, check the contrib.
If you don't have many columns and you don't expect the schema to change, just list them explicitly.
UPDATE table SET NR_A=0;
UPDATE table SET NR_B=0;
UPDATE table SET NR_C=0;
UPDATE table SET NR_D=0;
Otherwise, a simple php script could dynamically build and execute your query:
<?php
$db = pg_connect("host=localhost port=5432 user=postgres password=mypass dbname=mydb");
if(!$db) die("Failed to connect");
$reset_cols = ["A","B","C","D"];
foreach ($col in $reset_cols) {
$sql = "UPDATE my_table SET NR_" . $col . "=0";
pg_query($db,$sql);
}
?>
You could also lookup table's columns in Postgresql by querying the information schema columns tables, but you'll likely need to write a plpgsql function to loop over the query results (one row per table column starting with "NR_").
if you rather using sql query script, you should try to get the all column based on given tablename.
maybe you could try this query to get all column based on given tablename to use in your query.
SELECT attname FROM
pg_attribute, pg_type
WHERE typname = 'tablename' --your table name
AND attrelid = typrelid
AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')
--note that this attname is sys column
the query would return all column with given tablename except system column