Table invisible in PostgreSQL - Undefined relation issue at different sessions - postgresql

I have executed the following create statement using SQLWorkbench at my target postgresql database:
CREATE TABLE Config (
id serial PRIMARY KEY,
pub_ip_range_low varchar(100),
pub_ip_range_high varchar(100)
);
Right after table creation I request the table content by typing 'select * from config;' and see that table could be retrieved. Nevertheless, my java program that uses JDBC type 4 driver cannot access the table when I issue the same select statement in it. An exception is thrown when the program tries to access it which says says "Undefined relation" for the config table.
My questions are:
Why sqlworkbench where I had previously run the create statement recognizes the table while my java program cannot find it?
Where does the postgressql DBMS puts the tables I created? I don't see them neither in public nor in information schema.
NOTE:
I checked target postgres database and cannot see the table Config anywhere although SQL workbench can query it. Then I opened another SQL workbench instance and noticed that the table cannot be queried (i.e. not found). So, my conclusion is that PostgreSQL puts the table I created in the first running SQLBench instance into some location that is bound to that session. Another SQL Workbench instance or my java program is not bound to session, so cannot query the previously created table config.

The only "bloody location" that is session-local in PostgreSQL is the schema pg_temp, in other words: temporary tables. But your CREATE command does not display the keyword TEMP[ORARY]. Of course, as long as the transaction is not commited, nobody sees anything outside the transaction.
It's more likely you are seeing a switcheroo of hosts / databases / ports / or the schema search_path. A mixup with the mixed-case table name is a hot candidate, too. If you don't double-quote "Config", the table ends up all lower case in the system, so: config. If you later double quote the name, it won't match. The manual has the details.

Maybe the create failed on the extra trailing comma?
CREATE TABLE config (
id serial PRIMARY KEY,
pub_ip_range_low varchar(100),
pub_ip_range_high varchar(100) -- >> ,
);

Related

PostgreSQL rename table named with a keyword

I have a table named import.
I want to rename the table with the following statement in a sql script below.
Unfortunately I can't, because sql treats the term import as a psql keyword.
How can I change the name in a sql script?
I have a Database change management also called database migration or database upgrading. Database change management is the process of managing the change of a database over the course of an application's lifecycle. What could change in a database? The database structure (i.e. the tables), master data but even indices, triggers and stored procedures could be added, changed or deleted over time.
ALTER TABLE import
RENAME TO api_exchange;
I am aware I can change the table name with a PostgreSQL client, but I need to do it in a SQL script for postgreSQL 10 in order to keep my Database change management intact.
You can quote reserved words using double quotes:
-- \i tmp.sql
CREATE TABLE "select"(id integer);
ALTER TABLE "select"
RENAME TO api_exchange;
\d api_exchange

DB2 'list tables' returns nothing found even though there are 50+ tables defined?

This one is most odd, I've got a DB2 instance with 50+ tables defined, and whilst I can insert and query data. DB2 is being extremely picky about formatting and keeps complaining about both table / column context whilst insisting on everything being quoted.
Most weird is that none of the tables show in the results of a 'list tables' command whilst 2 other tables defined by API do..?
Syntax I used to create the tables..
CREATE TABLE Shell.Customers
(
"idCustomers" BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT BY 1 NO CYCLE ORDER ),
"Name" VARCHAR(64) NOT NULL,
"Code" VARCHAR(6) NOT NULL,
PRIMARY KEY ("idCustomers")
) COMPRESS YES ADAPTIVE WITH RESTRICT ON DROP;
Any ideas where I messed it up?
Thanks in advance.. :)
LIST TABLES command without ‘FOR’ clause shows tables for the current user. Your table is not listed unless your current user name is SHELL.
Use LIST TABLES FOR SCHEMA SHELL (or FOR ALL) command to list the table you mentioned.

How to Check if a Foreign Key Exists on a Specific Table in PostgreSQL

I have a foreign key named user__fk__store_id that was supposed to be created on the user table.
However, I made a mistake and instead have it created on another table I have named client.
My servers have an automated process that reads from a JSON file I created with what new tables to create, remove, etc... Every time a server needs to be upgraded with new stuff, it will run through this JSON file and run the queries it needs to.
In this case, in the json file, I'm trying to have it drop the existing incorrect foreign key constraint that was created on the client table, and recreate it correctly on the user table. So technically, it should be running these 2 queries back to back:
ALTER TABLE client DROP CONSTRAINT user__fk__store_id;
ALTER TABLE user ADD CONSTRAINT user__fk__store_id;
The problem I'm having is I can't figure out the query to run in order to see if the user__fk__store_id exists on the client table. I only know how to check if the constraint exists on any table in the database with the following:
SELECT COUNT(1) FROM pg_constraint WHERE conname='user__fk__store_id';
This would be a problem because this means every time I run my upgrade script on my servers, it will always think the constraint of that name already exists, but when it attempts to run the drop query it will error out because it can't find that constraint in the client table.
Is there a query I can run to check not just if the constraint exists, but also if it exists in a specific table?
I found the answer to my own question, I can just run the following query:
SELECT COUNT(1) FROM information_schema.table_constraints WHERE constraint_name='user__fk__store_id' AND table_name='client';
Above answer works fine, but following returns true/false and also checks for schema
SELECT EXISTS (SELECT 1 FROM information_schema.table_constraints
WHERE table_schema='schema_name' AND table_name='MyTable' AND
constraint_name='myTable_fkName_fkey');

How to rename a PostgreSQL table by prefixing an underscore?

I have a database which relies on a PostgreSQL system and I am maintaining it so I want to change tables and overall scheme. For this I thought of renaming the older tables so they have an underscore as a prefix. But this is not working:
DROP TABLE IF EXISTS _my_table; -- table does not exists, this does nothing
ALTER TABLE my_table
RENAME TO _my_table;
The result of the query is the following:
NOTICE: table "_my_table" does not exist, skipping ERROR:
type "_my_table" already exists
********** Error **********
ERROR: type "_my_table" already exists SQL state: 42710
The '_my_table' table is a fake name, but this error is reproduced by actually creating a '_my_table' table and running the same script above.
I am using pgAdmin III to access the database tables and making use of it's 'rename' operation results in the same error.
The postgresql documentation for the alter table method does not tell me explicitly about this particular problem: http://www.postgresql.org/docs/9.3/static/sql-altertable.html
Do I really need to use a prefix like 'backup' instead of '_' ? Or would it be possible to rename it, my only interest is to maintain the information in the table whilst having the minimal changes to the table name.
You cannot simply put an underscore in front of the existing table name because every table has an associated type that is... a leading underscore before the table name. You can verify this in the pg_catalog.pg_type table. Having a table name start with an underscore is not the problem, but the internal procedure is that a new table is created physically from the old table and only when the old table is no longer in use by other processes will the old table, and its associated type, be deleted. Hence the error referencing the type (and not the relation).
So if you really want to keep the old name with an underscore, you should first ALTER TABLE to some temp name and then ALTER TABLE to the underscore + original name. Or simply use another prefix...
ERROR: type "_my_table" already exists
Both tables and types are stored in the internal table pg_class. A unique name is required, that's why you get this error message.

Way to migrate a create table with sequence from postgres to DB2

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.