How to restore table from dump to database? - sql

I create a table dump using pg_dump:
pg_dump -h server1 -U postgres -t np_points gisurfo > D:\np_point.sql
After I go in psql and says:
-f D:\np_point.sql
But get list of standart PostgreSQL tables.
Next I try to exequte np_point.sql in pgAdmin and get error:
ERROR: Syntax error (near: "1")
LINE 78: 1 Сухово 75244822005 75644000 Челябинская обл. Нязепетровски...
Its snippet of this sql where I get error:
COPY np_point (gid, full_name, okato, oktmo, obl_name, region_nam, the_geom) FROM stdin;
1 Сухово 75244822005 75644000 Челябинская обл. Нязепетровский район 0101000020E6100000312A7936BD9F4D402A3C580DE9FF4B40
How can I restore table from sql file?
UPDATE
PostgreSQL 8.4
And first part of sql file.
PostgreSQL database dump
SET statement_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = off;
SET check_function_bodies = false;
SET client_min_messages = warning;
SET escape_string_warning = off;
SET search_path = public, pg_catalog;
SET default_tablespace = '';
SET default_with_oids = false;
--
-- Name: np_point; Type: TABLE; Schema: public; Owner: postgres; Tablespace:
--
CREATE TABLE np_point (
gid integer NOT NULL,
full_name character varying(254),
okato character varying(254),
oktmo character varying(254),
obl_name character varying(254),
region_nam character varying(254),
the_geom geometry,
CONSTRAINT enforce_dims_the_geom CHECK ((st_ndims(the_geom) = 2)),
CONSTRAINT enforce_geotype_the_geom CHECK (((geometrytype(the_geom) = 'POINT'::text) OR (the_geom IS NULL))),
CONSTRAINT enforce_srid_the_geom CHECK ((st_srid(the_geom) = 4326))
);

Did you install posgis in destinations db? If not , install postgis first。
If you install postgis and still have the problem, try to dump a table without geometry filed
and restore it in another db ,and see if the problem still appears.

Related

Where does psql import import to?

I got a SQL dump file and try to import it into my database with the following command:
psql -U postgres timetable < /tmp/restores/2\ Restore\ Rooms.sql
It contains several SET commands, a CREATE TABLE timetable.rooms and several other commands.
I logged in via psql -U postgres before and created the schema timetable and ran the above import command, but it returned some errors. So I logged back in and dropped the schema timetable to start again. After that the import returned the following:
postgres#ubuntu:~$ psql -U postgres timetable < /tmp/restores/2\ Restore\ Rooms.sql
SET
SET
SET
SET
SET
set_config
------------
(1 row)
SET
SET
SET
SET
SET
SET
ERROR: relation "rooms" already exists
ALTER TABLE
ERROR: relation "rooms_id_seq" already exists
ALTER TABLE
ALTER SEQUENCE
ALTER TABLE
ERROR: duplicate key value violates unique constraint "rooms_pkey"
DETAIL: Key (id)=(50) already exists.
CONTEXT: COPY rooms, line 1
setval
--------
57
(1 row)
ERROR: multiple primary keys for table "rooms" are not allowed
postgres#ubuntu:~$ psql -U postgres
psql (12.4 (Ubuntu 12.4-0ubuntu0.20.04.1))
Type "help" for help.
I then tried to access the table timetable.rooms but it wasn't there:
postgres=# select * from
information_schema. pg_catalog. pg_temp_1. pg_toast. pg_toast_temp_1. public.
Where did it import the tables then and how do I access it, if not via psql -U postgres?

Drop table only if it exists, or ignore drop error

I have a table MYLOG and would like to try drop it before creating it using the SQL script below.
If the table does not exist yet, the error below is throw.
How could I bypass this error if the table does not exist?
The schema gets set in an earlier script, which is not available in the SQL script:
set current schema MYSCHEMA
SQL script:
DROP TABLE MYLOG;
CREATE TABLE MYLOG (
TIME_STARTED TIMESTAMP NOT NULL,
USER_EMAIL VARCHAR(254) NOT NULL,
CONSTRAINT PK_TIME_STARTED_USER_EMAIL PRIMARY KEY (TIME_STARTED, USER_EMAIL)) ORGANIZE BY ROW;
COMMIT;
Error:
DROP TABLE MYLOG
SQLError: rc = 0 (SQL_SUCCESS)
SQLGetDiagRec: SQLState : S0002
fNativeError : -204
szErrorMsg : [IBM][CLI Driver][DB2/6000] SQL0204N "MYSCHEMA.MYLOG" is an undefined name. SQLSTATE=42704
This is a FAQ
There's more than one way to do it.
You can use compound-SQL in your script with a continue-handler for the SQLSTATE corresponding to the error you get if the table is not found, but this requires that you also use an alternative statement delimiter like shown below
--#SET TERMINATOR #
set current schema myschema#
BEGIN
DECLARE CONTINUE HANDLER FOR SQLSTATE '42704'
BEGIN end;
EXECUTE IMMEDIATE 'DROP TABLE MYLOG';
END #
CREATE TABLE MYLOG(... )#
You can also change the abort-on-first-error logic (if you use +s when running your script via the command line). You can udate the Db2 CLP options on the fly inside your script via update command options using s off (to continue on error) or update command options using s on to abort on error.
by using this query
select tabname from syscat.tables where
tabschema='myschema' and tabname='MYLOG'
check that table in your schema
if exist then
drop table myschema.MYLOG
then create

Adding an extra column and constraint but then when updating the column it fails

I am attempting to run the following query on SQL Server 2008 in SSMS, however it constantly fails on the third query stating:
Invalid column name 'hasCodeMappingDefaults'.
BEGIN
ALTER TABLE [SIntegrationProvider]
ADD [hasCodeMappingDefaults] BIT NULL;
END
BEGIN
ALTER TABLE [SIntegrationProvider]
ADD CONSTRAINT [DF_SIntegrationProvider_hasCodeMappingDefaults] DEFAULT ((1)) FOR [hasCodeMappingDefaults];
END
BEGIN
UPDATE [SIntegrationProvider]
SET [hasCodeMappingDefaults] = 1
WHERE [provider] = 'EmployeeNavigator';
END
When each query is run individually in order they work, I just cannot figure out why I cannot run all three combined (this needs to be done as part of a much larger script being rolled out).
Actually I think I may have found the problem, doing this seems to have resolved the issue:
ALTER TABLE [SIntegrationProvider]
ADD [hasCodeMappingDefaults] BIT NULL
GO
ALTER TABLE [SIntegrationProvider]
ADD CONSTRAINT [DF_SIntegrationProvider_hasCodeMappingDefaults] DEFAULT ((1)) FOR [hasCodeMappingDefaults]
GO
-- Set the new value for ENav
IF EXISTS(SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'SIntegrationProvider'
AND COLUMN_NAME = 'hasCodeMappingDefaults')
UPDATE [SIntegrationProvider]
SET [hasCodeMappingDefaults] = 1
WHERE [provider] = 'EmployeeNavigator';

Importing a pgsql file via pgadmin

I work on MySQL, but one of my client gave me a project that uses postgreSql. He gives me the project files and db file with extension '.pgsql'.
I installed pgadmin and created a test db, but don't know how to import pgsql file. I tries copy-paste of queries in script editor, till tables everything is executing fine, but at the time of data queries, its throwing error.
And data format is also strange, don't know whether its the correct query format or not.
This is the glimpse of pgsql file:
--
-- PostgreSQL database dump
--
SET statement_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = off;
SET check_function_bodies = false;
SET client_min_messages = warning;
SET escape_string_warning = off;
SET search_path = public, pg_catalog;
SET default_tablespace = '';
SET default_with_oids = false;
--
-- Name: kjh; Type: TABLE; Schema: public; Owner: design; Tablespace:
--
CREATE TABLE kjh (
mknh integer NOT NULL,
jkh integer NOT NULL
);
ALTER TABLE public.kjh OWNER TO design;
--
-- Name: TABLE kjh; Type: COMMENT; Schema: public; Owner: design
--
//..And so on
These lines in pgsql files are throwing error:
--
-- Data for Name: kjh; Type: TABLE DATA; Schema: public; Owner: design
--
COPY kjh (mknh, jkh) FROM stdin;
1 1
\.
--
-- Data for Name: w_ads; Type: TABLE DATA; Schema: public; Owner: design
--
COPY w_ads (id, link, city, type, name, enabled, "time", hits, isimg) FROM stdin;
44 # -1 0 1 t 1 20 1
\.
Any suggestions?
You are likely running into problems with delimiters, try something like this:
COPY kjh (mknh, jkh) FROM stdin WITH DELIMITER ' ';
1 1
\.
This should execute just fine.
Also, note, that your pgsql file have inconsistent spaces count between values, so you may have to prepare this file replacing multiple spaces in values with single delimiter (two spaces with single space delimiter will result in error, since postgres will assume you providing empty column value).
And I would suggest you to choose another delimiter instead of space, something like ; or ^.
Not sure if COPY ... FROM stdin will work from pgadmin (well, it should), but if it fails, try to run this query from CLI using psql command.
For more info on delimiters and copy syntax, refer to docs.

Dropping unique constraint for column in H2

I try to drop unique constraint for column in h2, previously created as info varchar(255) unique.
I tried:
sql> alter table public_partner drop constraint (select distinct unique_index_name from in
formation_schema.constraints where table_name='PUBLIC_PARTNER' and column_list='INFO');
But with no success (as follows):
Syntax error in SQL statement "ALTER TABLE PUBLIC_PARTNER DROP CONSTRAINT ([*]SELECT DISTI
NCT UNIQUE_INDEX_NAME FROM INFORMATION_SCHEMA.CONSTRAINTS WHERE TABLE_NAME='PUBLIC_PARTNER
' AND COLUMN_LIST='INFO') "; expected "identifier"; SQL statement:
alter table public_partner drop constraint (select distinct unique_index_name from informa
tion_schema.constraints where table_name='PUBLIC_PARTNER' and column_list='INFO') [42001-1
60]
How this constraint should be correctly removed?
By the way:
sql> (select unique_index_name from information_schema.constraints where table_name='PUBLI
C_PARTNER' and column_list='INFO');
UNIQUE_INDEX_NAME
CONSTRAINT_F574_INDEX_9
(1 row, 0 ms)
seems to return a correct output.
In the SQL language, identifier names can't be expressions. You need to run two statements:
select distinct constraint_name from information_schema.constraints
where table_name='PUBLIC_PARTNER' and column_list='INFO'
and then get the identifier name, and run the statement
ALTER TABLE PUBLIC_PARTNER DROP CONSTRAINT <xxx>
You could use a user defined function to execute a dynamically created statement. First to create the execute alias (only once):
CREATE ALIAS IF NOT EXISTS EXECUTE AS $$ void executeSql(Connection conn, String sql)
throws SQLException { conn.createStatement().executeUpdate(sql); } $$;
Then to call this method:
call execute('ALTER TABLE PUBLIC_PARTNER DROP CONSTRAINT ' ||
(select distinct unique_index_name from in formation_schema.constraints
where table_name='PUBLIC_PARTNER' and column_list='INFO'));
... where execute is the user defined function that runs a statement.
If you are using H2 with Spring Boot in PosgreSQL Mode the query has to include the schema public and the tables are likely in lower case mode. (see application.yml below)
Check the letter case in the information schema table and use the upper and lower case as seen in table information_schema.constraints.
Verbose Query Set
SET #constraint_name = QUOTE_IDENT(
SELECT DISTINCT constraint_name
FROM information_schema.constraints
WHERE table_schema = 'public'
AND table_name = 'public_partner'
AND constraint_type = 'UNIQUE'
AND column_list = 'info');
SET #command = 'ALTER TABLE public.public_partner DROP CONSTRAINT public.' || #constraint_name;
SELECT #command;
EXECUTE IMMEDIATE #command;
Explanation:
SELECT DISTINCT constraint_name [...]
Select the Columns constraint_name with the UNIQUE constrain from the schema info
QUOTE_IDENT([...])
I don't know why this is needed, it will quote the resulting string
SET #constraint_name = [...];
Store in Variable #constraint_name
SET #command = [...];
Compose whole command by concatenation of strings and store in variable #command
SELECT #command;
Show the composed Query on Screen, just for debugging
EXECUTE IMMEDIATE #command;
Execute #command
Typical H2 Configuration in PostgreSQL Mode in the Spring Boot application.yml (extract)
spring:
# [...]
jpa:
database-platform: org.hibernate.dialect.H2Dialect
# [...]
datasource:
url: jdbc:h2:mem:testdb;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false
username: sa
password: sa
# [...]