I have migrated an AnyDAC app to FireDAC and I can't get to work its Autoinc fields.
The ID field (primary key) has been defined on Postgre SQL as default to nextval('llistapanelspuzzle_id_seq'::regclass), BIGSERIAL, so the server automatically sets its values.
The column was recognized by AnyDAC as an TAutoincField and worked correctly, but when I now open that table on FireDAC it fails saying that the field found is a TLargeIntField. I change the persistent field to a TLargeIntField, but now when inserting records on Delphi, I don't get the new values from the server, it leaves the dataset with a 0 value, and when I add a second record it raises a Key Violation (two records with a 0 value on its primary key).
Do you know how to define AutoInc fields on FireDAC - PostgreSQL, when they are being recognized as LargeInt fields ?.
Update: I have added ID to the UpdateOptions.AutoIncFields, but it doesn't seem to have changed anything.
Thank you.
Looks like you have to activate the ExtendedMetada flag on the FDConnection in order for FireDAC to recognize automatically the PostgreSQL Autoinc columns.
Now it works correctly.
I have a web app backed by Postgres.
Each web app request should only read/write data for the current logged-in user.
Every table with user data has a user_id column.
I occasionally have bugs where I forget to add user_id = ? to the WHERE clause of an SQL request. To protect against this problem in a general way, I'm looking into Postgres row-level security (article):
Set a policy on every user data table: CREATE POLICY table_policy ON table USING (user_id::TEXT = current_setting('app.user_id'))
In the web app, when a request begins, set the current logged-in user ID on the request's connection: SET app.user_id = ?.
This allows me to completely ignore user_id when writing SELECT and UPDATE requests.
My remaining problem is INSERTs. Is there a way to avoid having to provide user_id on INSERTs?
Just having a look at the manual :
Existing table rows are checked against the expression specified in USING, while new rows that would be created via INSERT or UPDATE are
checked against the expression specified in WITH CHECK
it seems that you just have to add a WITH CHECK clause to your policy in addition of the USING clause, and which will apply to the INSERT and UPDATE statements.
I am seeking suggestions on methods to trigger the running of code based on specific event occurring.
Basically I need to monitor all inserts into a table and compare a column value against a parameter set in another table.
For example, when a new record is added to the table and the column [Temperature] is greater than 30 (which is a value set in another table). Send an alert email to notify of this situation.
You can create a trigger (special type of stored procedure) that is automatically executed after an insert happened. Documentation for triggers is here: https://technet.microsoft.com/en-us/library/ms189799(v=sql.120).aspx
You will not be able to send an email out of SQL Database though.
Depending on how quick you need the notification after the insert, maybe you could make an insert into yet another table from within the trigger and query this new table periodically (e.g. using a script in Azure automation) and have the email logic outside the database.
I need to migrate a DDL from Postgres to DB2, but I need that it works the same as in Postgres. There is a table that generates values from a sequence, but the values can also be explicitly given.
Postgres
create sequence hist_id_seq;
create table benchmarksql.history (
hist_id integer not null default nextval('hist_id_seq') primary key,
h_c_id integer,
h_c_d_id integer,
h_c_w_id integer,
h_d_id integer,
h_w_id integer,
h_date timestamp,
h_amount decimal(6,2),
h_data varchar(24)
);
(Look at the sequence call in the hist_id column to define the value of the primary key)
The business logic inserts into the table by explicitly providing an ID, and in other cases, it leaves the database to choose the number.
If I change this in DB2 to a GENERATED ALWAYS it will throw errors because there are some provided values. On the other side, if I create the table with GENERATED BY DEFAULT, DB2 will throw an error when trying to insert with the same value (SQL0803N), because the "internal sequence" does not take into account the already inserted values, and it does not retry with a next value.
And, I do not want to restart the sequence each time a provided ID was inserted.
This is the problem in BenchmarkSQL when trying to port it to DB2: https://sourceforge.net/projects/benchmarksql/ (File sqlTableCreates)
How can I implement the same database logic in DB2 as it does in Postgres (and apparently in Oracle)?
You're operating under a misconception: that sources external to the db get to dictate its internal keys. Ideally/conceptually, autogenerated ids will never need to be seen outside of the db, as conceptually there should be unique natural keys for export or reporting. Still, there are times when applications will need to manage some ids, often when setting up related entities (eg, JPA seems to want to work this way).
However, if you add an id value that you generated from a different source, the db won't be able to manage it. How could it? It's not efficient - for one thing, attempting to do so would do one of the following
Be unsafe in the face of multiple clients (attempt to add duplicate keys)
Serialize access to the table (for a potentially slow query, too)
(This usually shows up when people attempt something like: SELECT MAX(id) + 1, which would require locking the entire table for thread safety, likely including statements that don't even touch that column. If you try to find any "first-unused" id - trying to fill gaps - this gets more complicated and problematic)
Neither is ideal, so it's best to not have the problem in the first place. This is usually done by having id columns be autogenerated, but (as pointed out earlier) there are situations where we may need to know what the id will be before we insert the row into the table. Fortunately, there's a standard SQL object for this, SEQUENCE. This provides a db-managed, thread-safe, fast way to get ids. It appears that in PostgreSQL you can use sequences in the DEFAULT clause for a column, but DB2 doesn't allow it. If you don't want to specify an id every time (it should be autogenerated some of the time), you'll need another way; this is the perfect time to use a BEFORE INSERT trigger;
CREATE TRIGGER Add_Generated_Id NO CASCADE BEFORE INSERT ON benchmarksql.history
NEW AS Incoming_Entity
FOR EACH ROW
WHEN Incoming_Entity.id IS NULL
SET id = NEXTVAL FOR hist_id_seq
(something like this - not tested. You didn't specify where in the project this would belong)
So, if you then add a row with something like:
INSERT INTO benchmarksql.history (hist_id, h_data) VALUES(null, 'a')
or
INSERT INTO benchmarksql.history (h_data) VALUES('a')
an id will be generated and attached automatically. Note that ALL ids added to the table must come from the given sequence (as #mustaccio pointed out, this appears to be true even in PostgreSQL), or any UNIQUE CONSTRAINT on the column will start throwing duplicate-key errors. So any time your application needs an id before inserting a row in the table, you'll need some form of
SELECT NEXT VALUE FOR hist_id_seq
FROM sysibm.sysdummy1
... and that's it, pretty much. This is completely thread and concurrency safe, will not maintain/require long-term locks, nor require serialized access to the table.
I am using Sybase Advantage, I have 2 tables:
The first table has the data records
The second table stores a history of the first
The first table has triggers to populate records in the second table depending on which fields get changed.
I would like to store the connection name (PC which made the request), the name that is displayed in the active queries page (Server Info dialog) and not the username. Does anyone know if this is possible?
Thanks
The following SQL statement can be used to retrieve the computer name instead of the user name.
SELECT *
FROM
( EXECUTE PROCEDURE sp_mgGetConnectedUsers() ) ConnUsers
WHERE
ConnUsers.DictionaryUser = USER();
The stored procedure sp_mgGetConnectedUsers is documented here.