DBeaver does not keep primary keys on import/export - dbeaver

I'm using DBeaver to migrate data from Postgres to Derby. When I use the wizard in DBeaver to go directly from one table to another, the primary key in Derby is being generated instead of inserted. This causes issues on foreign keys for subsequent tables.
If I generate the SQL, the primary key is part of the SQL statement and is properly inserted. However there are too many rows to handle in this way.
Is there a way to have DBeaver insert the primary key instead of letting it be generated when importing / exporting directly to database tables?
Schema of target table
CREATE TABLE APP.THREE_PHASE_MOTOR (
ID BIGINT NOT NULL DEFAULT GENERATED_BY_DEFAULT,
VERSION INTEGER NOT NULL,
CONSTRAINT SQL130812103636700 PRIMARY KEY (ID)
);
CREATE INDEX SQL160416184259290 ON APP.THREE_PHASE_MOTOR (ID);
Schema of source table
CREATE TABLE public.three_phase_motor (
id int8 NOT NULL DEFAULT nextval('three_phase_motor_id_seq'::regclass),
"version" int4 NOT NULL,
CONSTRAINT three_phase_motor_pkey PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);

I found a trick working with version 6.0.5; do these steps:
double click a table name
then select Data tab
then click the gray table corner (the one on top of row order numbers) in order to select all rows
then right click the same gray table corner
then select Generate SQL -> INSERT menu
a window with the INSERT instructions including id (primary key) will popup.
PS: when selecting a subset of rows the same menu would work for only those too

When you go to export, check the Include generated column option, and the primary key (auto-incremented) will be included in the export.
See this for more details: https://github.com/dbeaver/dbeaver/commit/d1f74ec88183d78c7c6620690ced217a52555262
Personally I think this needs to be more clear, and why they excluded it in the first place was not good data integrity.

As of now DBeaver version [22.0.5] you have to select Include generated columns as true, as shown in the following screenshot that will export the primary/generated columns.

Related

PGAdmin Edit data

I'm new to Postgres and can't seem to edit the data in the table. The test box pops up but doesn't allow me to change the text. This initial table didn't have any PK or SERIAL. So I added them and my table definition is now this:
CREATE TABLE public.weather
(
city character varying(80) COLLATE pg_catalog."default",
temp_lo integer,
temp_hi integer,
prcp real,
date date,
id integer NOT NULL DEFAULT nextval('weather_id_seq'::regclass),
CONSTRAINT weather_pkey PRIMARY KEY (id)
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default;
ALTER TABLE public.weather
OWNER to postgres;
It's probably very simple
Right-click on your table, select View Data/View All Rows (or one of the variants). That window will let you edit the data. Then press F6 to save changes (with thanks to leverglowh for pointing that out).
With pgadmin 4.6 the icon has changed (see screenshot):
a zoom to the icon:
You can also use the shortcut F6.
Right-click on your table, select View/Edit Data -> All Rows:
Then there is an icon in the top bar, looking like a table with an arrow pointing down (the icon on the right of the screenshot below):
The icon is gray but works nevertheless.
There is an image like Database with Save icon to save the edited data in the table
The above solutions all work for the specific case of the question, but I found that they did not work for me.
The reason is that my table did not have a primary key. As said on pgAdmin's official page:
To modify the content of a table, each row in the table must be
uniquely identifiable. If the table definition does not include an OID
or a primary key, the displayed data is read only.
I had believed that including:
CREATE TABLE IF NOT EXISTS public.mytable(
id INT GENERATED ALWAYS AS IDENTITY, [...]);
would automatically assign id as the primary key. I was wrong and thus could not edit "mytable" in pgAdmin.
Once I entered:
ALTER TABLE public.mytable
ADD CONSTRAINT mytable_pkey PRIMARY KEY (id);
The problem was solved.

How to associate an Sequence to a column in PowerDesigner?

I'm using powerdesigner 15.2 to model an postgresql database, but i can't associate sequences with PKs...
read on internet that:
"To associate the sequence with the column, double-click the column entry. Then, in the General tab, specify the name of the sequence."
but i already did this...
the problem is that when i generate database, the sequences are simply created, but not associated with the column...
create sequence SQ_CARGO;
create table CARGO (
ID INT4 not null,
NOME VARCHAR(20) not null,
ROLE VARCHAR(100) not null,
constraint PK_CARGO primary key (ID)
);
Current DBMS in Powerdesigner: PostgreSQL 8 (but i'm using postgresql 9.4)
anyone knows how to do this? or else i will be forced to set this manually for each table:
ALTER TABLE cargo ALTER COLUMN ID SET DEFAULT NEXTVAL('SQ_CARGO'::regclass);
To resolve this, i wrote this code and replace, in DBMS Properties, the value:(Script->Objects->Table->Create).
create [%Temporary% ]table [%QUALIFIER%]%TABLE% ( %TABLDEFN% )
[%OPTIONS%];
.foreach_item(Columns)
.if (%COLNNO%==1) && (%Primary% == TRUE) && (%SQNC% != "")
ALTER TABLE [%QUALIFIER%]%TABLE% ALTER COLUMN %COLUMN% SET DEFAULT
nextval('[%QUALIFIER%]%SQNC%')
.endif
.next(\n)
Taking advantage, I have a problem when it generated the creation of code SEQUENCE.
I can not get the code to be generated with the OWNER of the prefix object.
ex:
The code is generated as follows:
CREATE SEQUENCE TABLE_SQ;
And it should be generated like this:
CREATE SEQUENCE OWNER.TABLE_SQ;
#Gilvan: You must select the owner on the "New Sequence" window, on the "Owner" combobox.
was a bug!
download a new version and works fine.

T-SQL create table with primary keys

Hello I wan to create a new table based on another one and create primary keys as well.
Currently this is how I'm doing it. Table B has no primary keys defined. But I would like to create them in table A. Is there a way using this select top 0 statement to do that? Or do I need to do an ALTER TABLE after I created tableA?
Thanks
select TOP 0 *
INTO [tableA]
FROM [tableB]
SELECT INTO does not support copying any of the indexes, constraints, triggers or even computed columns and other table properties, aside from the IDENTITY property (as long as you don't apply an expression to the IDENTITY column.
So, you will have to add the constraints after the table has been created and populated.
The short answer is NO. SELECT INTO will always create a HEAP table and, according to Books Online:
Indexes, constraints, and triggers defined in the source table are not
transferred to the new table, nor can they be specified in the
SELECT...INTO statement. If these objects are required, you must
create them after executing the SELECT...INTO statement.
So, after executing SELECT INTO you need to execute an ALTER TABLE or CREATE UNIQUE INDEX in order to add a primary key.
Also, if dbo.TableB does not already have an IDENTITY column (or if it does and you want to leave it out for some reason), and you need to create an artificial primary key column (rather than use an existing column in dbo.TableB to serve as the new primary key), you could use the IDENTITY function to create a candidate key column. But you still have to add the constraint to TableA after the fact to make it a primary key, since just the IDENTITY function/property alone does not make it so.
-- This statement will create a HEAP table
SELECT Col1, Col2, IDENTITY(INT,1,1) Col3
INTO dbo.MyTable
FROM dbo.AnotherTable;
-- This statement will create a clustered PK
ALTER TABLE dbo.MyTable
ADD CONSTRAINT PK_MyTable_Col3 PRIMARY KEY (Col3);

How to copy table between two models in Mysql workbench?

I am doing some databese thing, I need copy one table from one model to another, but i try many ways there no effect.
Is there any way for doing this?
If you just want to do a single table through the MySQL Workbench.
In MySQL Workbench:
Connect to a MySQL Server
Expand a Database
Right Click on a table
Select Copy To Clipboard
Select Create Statement
A create statement for the table will be copied to your clipboard similar to the below:
CREATE TABLE `cache` (
`cid` varchar(255) NOT NULL DEFAULT '',
`data` longblob,
`expire` int(11) NOT NULL DEFAULT '0',
`created` int(11) NOT NULL DEFAULT '0',
`headers` text,
`serialized` smallint(6) NOT NULL DEFAULT '0',
PRIMARY KEY (`cid`),
KEY `expire` (`expire`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Create the table in the new database
Open a new SQL tab for executing queries (File->New Query Tab)
Alter the create table code to include the database to create the table on.
CREATE TABLE `databaseName`.`cache` (
`cid` varchar(255) NOT NULL DEFAULT '',
`data` longblob,
`expire` int(11) NOT NULL DEFAULT '0',
`created` int(11) NOT NULL DEFAULT '0',
`headers` text,
`serialized` smallint(6) NOT NULL DEFAULT '0',
PRIMARY KEY (`cid`),
KEY `expire` (`expire`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Then click the Execute button (looks like a lightening Bolt)
That will copy the table schema from one db to another using the MySQL workbench. Just refresh the tables in the database and you should see your newly added table
Select tab with source database
In menu: Server->Data Export
Select Schema and the Table as Schema Object
Select option Export to Self-Contained File and check Create Dump in a Single Transaction (self-contained only)
Copy full file path to clipboard
Start Export
Select tab with target database
In menu: Server->Data Import. Make sure your target database name is at the top left corner of the Data Import view
Select Import from self contained file and paste full file path from clipboard
Select Default Target Schema
Select Dump Content (Dump Structure and Data etc…)
Start Import
Your best option is probably to create a stripped down version of the model that contains the objects you want to carry over. Then open the target model and run File -> Include Model.... Select the stripped down source model and there you go.
You can just use a select statement. Here I am creating a duplicate of "original_table" table from the "original_schema" schema/database to the "new_schema" schema :
CREATE TABLE new_schema.duplicate_table AS
Select * from original_schema.original_table;
You can just put any select statement you need ,add a condition and select the columns :
CREATE TABLE new_schema.duplicate_table AS
SELECT column1, column2
FROM original_schema.original_table
WHERE column2 < 11000000;
I think it is worth mentioning that
a copied table may reference fields in tables of the original schema, that do not exist, in the schema where it's to be copied. It might be a good idea, to inspect the table for these discrepancies, before adding it to the other schema.
it's probably a good idea, to check engine compatibility (e.g. InnoDB vs MyISAM) and character set.
step 1 : Righit click on table > copy to clipboard > create statement
step 2: paste clipboard in the query field of workbench.
step 3: remove (``) from the name of the table and name of the model(schema)followed by a dot.
eg : `cusine_menus` -> schema_name.cusine_menus
execute
If you already have your table created and just want to copy the data, I'd recommend using the "Export Data Wizard" and "Import Data Wizard". It is basically choosing stuff in the program for exporting and then importing the data and is easy to use.
MySQL has an article on the wizards here: Table Data Export and Import Wizard
To copy data using the wizards, do the following:
Find the table in the list from which you want to copy data from.
Right click and choose "Table Data Export Wizard."
Choose the columns you wish to copy.
Choose a location to save a *.csv or *.json file with the copied data.
Find the table to insert the copied data to.
Right click and choose "Table data import wizard".
Choose the file you just exported.
Map the columns from the table you copied from to the table you insert to.
Press "Finish". The data is inserted as you chose.
In this post, we are going to show you how to copy a table in MySQL
First, this query will copy the data and structure, but the indexes are not included:
CREATE TABLE new_table SELECT * FROM old_table;
Second, this query will copy the table structure and indexes, but not data:
CREATE TABLE new_table LIKE old_table;
So, to copy everything, including database objects such as indexes, primary key constraint, foreign key constraints, triggers, etc., run these queries:
CREATE TABLE new_table LIKE old_table;
INSERT new_table SELECT * FROM old_table;
If you want to copy a table from one database to another database:
CREATE TABLE destination_db.new_table LIKE source_db.old_table;
INSERT destination_db.new_table
SELECT
*
FROM
source_db.old_table;
create table .m_property_nature like .m_property_nature;
INSERT INTO .m_property_nature SELECT * from .m_property_nature;
You can get the crate table query from table info and use the same query on different database instance.
show create table TABLENAME.content and copy the query;
Run the generated query on another Db instance connected.

CREATE TABLE AS with PRIMARY KEY in one statement (PostgreSQL)

Is there a way to set the PRIMARY KEY in a single "CREATE TABLE AS" statement?
Example - I would like the following to be written in 1 statement rather than 2:
CREATE TABLE "new_table_name" AS SELECT a.uniquekey, a.some_value + b.some_value FROM "table_a" AS a, "table_b" AS b WHERE a.uniquekey=b.uniquekey;
ALTER TABLE "new_table_name" ADD PRIMARY KEY (uniquekey);
Is there a better way of doing this in general (assume there are more than 2 tables, e.g. 10)?
According to the manual: create table and create table as you can either:
create table with primary key first, and use select into later
create table as first, and use add primary key later
But not both create table as with primary key - what you wanted.
If you want to create a new table with the same table structure of another table, you can do this in one statement (both creating a new table and setting the primary key) like this:
CREATE TABLE mytable_clone (
LIKE mytable
INCLUDING defaults
INCLUDING constraints
INCLUDING indexes
);
No, there is no shorter way to create the table and the primary key.
See the command below, it will create a new table with all the constraints and with no data. Worked in postgres 9.5
CREATE TABLE IF NOT EXISTS <ClonedTableName>(like <OriginalTableName> including all)
well in mysql ,both is possible in one command
the command is
create table new_tbl (PRIMARY KEY(`id`)) as select * from old_tbl;
where id is column with primary key of old_tbl
done...
You may do this way
CREATE TABLE IOT (EMPID,ID,Name, CONSTRAINT PK PRIMARY KEY( ID,EMPID))
ORGANIZATION INDEX NOLOGGING COMPRESS 1 PARALLEL 4
AS SELECT 1 as empid,2 id,'XYZ' Name FROM dual;