I have the following table called client:
Table "public.client"
Column | Type | Collation | Nullable | Default
---------------------+---------+-----------+----------+------------------------------
clientid | integer | | not null | generated always as identity
account_name | text | | not null |
last_name | text | | |
first_name | text | | |
address | text | | not null |
suburbid | integer | | |
cityid | integer | | |
post_code | integer | | not null |
business_phone | text | | |
home_phone | text | | |
mobile_phone | text | | |
alternative_phone | text | | |
email | text | | |
quote_detailsid | integer | | |
invoice_typeid | integer | | |
payment_typeid | integer | | |
job_typeid | integer | | |
communicationid | integer | | |
accessid | integer | | |
difficulty_levelid | integer | | |
current_lawn_price | numeric | | |
square_meters | numeric | | |
note | text | | |
client_statusid | integer | | |
reason_for_statusid | integer | | |
Indexes:
"client_pkey" PRIMARY KEY, btree (clientid)
"account_name_check" UNIQUE CONSTRAINT, btree (account_name)
Foreign-key constraints:
"client_accessid_fkey" FOREIGN KEY (accessid) REFERENCES access(accessid)
"client_cityid_fkey" FOREIGN KEY (cityid) REFERENCES city(cityid)
"client_client_statusid_fkey" FOREIGN KEY (client_statusid) REFERENCES client_status(client_statusid)
"client_communicationid_fkey" FOREIGN KEY (communicationid) REFERENCES communication(communicationid)
"client_difficulty_levelid_fkey" FOREIGN KEY (difficulty_levelid) REFERENCES difficulty_level(difficulty_levelid)
"client_invoice_typeid_fkey" FOREIGN KEY (invoice_typeid) REFERENCES invoice_type(invoice_typeid)
"client_job_typeid_fkey" FOREIGN KEY (job_typeid) REFERENCES job_type(job_typeid)
"client_payment_typeid_fkey" FOREIGN KEY (payment_typeid) REFERENCES payment_type(payment_typeid)
"client_quote_detailsid_fkey" FOREIGN KEY (quote_detailsid) REFERENCES quote_details(quote_detailsid)
"client_reason_for_statusid_fkey" FOREIGN KEY (reason_for_statusid) REFERENCES reason_for_status(reason_for_statusid)
"client_suburbid_fkey" FOREIGN KEY (suburbid) REFERENCES suburb(suburbid)
Referenced by:
TABLE "work" CONSTRAINT "work_clientid_fkey" FOREIGN KEY (clientid) REFERENCES client(clientid)
I want to move all phone columns (business_phone, home_phone, mobile_phone, alternative_phone) as an array to one column called phone_numbers and get rid of the four phone_columns. Any idea how to do this safely without losing any records?
Add the array column.
ALTER TABLE client
ADD COLUMN phone_numbers text[];
Then use an UPDATE command to set the value of the array column based on the other four.
UPDATE client
SET phone_numbers = [business_phone,home_phone,mobile_phone,alternate_phone]; -- test and modify if needed
You can repeat this UPDATE as many times as it takes to get it right. Then you can safely DROP the four old columns.
ALTER TABLE client
DROP COLUMN business_phone
DROP COLUMN home_phone
DROP COLUMN mobile_phone
DROP COLUMN alternate_phone;
Related
I am trying to change the type of one of the columns on my table from one that takes arrays filled with strings to one that takes JSON.
The SQL I'm trying to execute looks like:
ALTER TABLE my_table
ALTER COLUMN my_column TYPE JSON USING my_column::json
But I get an error back saying "cannot cast type character varying[] to json".
The column I'm trying to change is empty, there are no rows so there is no data that needs to be cast to JSON. Since it's empty I've thought of dropping the column and remaking it but I'd like to keep the column and just change its type if possible. I'm not a whizz with PostgreSQL so any nudge in the right direction would be appreciated.
array_test
Table "public.array_test"
Column | Type | Collation | Nullable | Default
---------------+---------------------+-----------+----------+---------
id | integer | | |
array_fld | integer[] | | |
numeric_array | numeric[] | | |
jsonb_array | jsonb[] | | |
varchar_array | character varying[] | | |
text_array | text[] | | |
ALTER TABLE array_test
ALTER COLUMN varchar_array TYPE json
USING array_to_json(varchar_array);
\d array_test
Table "public.array_test"
Column | Type | Collation | Nullable | Default
---------------+-----------+-----------+----------+---------
id | integer | | |
array_fld | integer[] | | |
numeric_array | numeric[] | | |
jsonb_array | jsonb[] | | |
varchar_array | json | | |
text_array | text[] | | |
I have below tables and trying to do an update from second table to first one, it seems to take more than 15 minutes and I killed it at that point.
Basically just trying to set one field from a table to another field. Both tables have around 2.5 million rows. How can we optimize this operation?
first table:
\d table1
Table "public.fa_market_urunu"
Column | Type | Collation | Nullable | Default
--------------+-----------------------------+-----------+----------+-----------------------
id | character varying | | not null |
ad | character varying | | |
url | character varying | | |
image_url | character varying | | |
satici_id | character varying | | not null |
satici | character varying | | not null |
category_id | character varying | | |
date_created | timestamp with time zone | | not null | now()
last_updated | timestamp(3) with time zone | | not null | now()
fiyat | double precision | | |
Indexes:
"tbl1_pkey" PRIMARY KEY, btree (id)
"tbl1_satici" UNIQUE, btree (id, satici)
"tbl1_satici_id" UNIQUE, btree (satici, id)
"tbl1_satici_id_last_updated" UNIQUE, btree (satici, id, last_updated)
"tbl1_satici_id_satici_key" UNIQUE CONSTRAINT, btree (satici_id, satici)
"tbl1_satici_last_updated_id" UNIQUE, btree (satici, last_updated, id)
"tbl1_last_updated" btree (last_updated)
"tbl1_satici_category" btree (satici, category_id)
"tbl1_satici_category_last_updated" btree (satici, category_id, last_updated)
"tbl1_satici_last_updated" btree (satici, last_updated)
second table:
\d table2
Table "public.temp_son_fiyat"
Column | Type | Collation | Nullable | Default
---------+-------------------+-----------+----------+---------
urun_id | character varying | | |
satici | character varying | | |
fiyat | double precision | | |
Indexes:
"ind_u" UNIQUE, btree (urun_id, satici)
My operation:
UPDATE table1 mu
SET fiyat = fn.fiyat
FROM table2 AS fn
WHERE mu.satici_id = fn.urun_id AND mu.satici = fn.satici;
This happens because of the indexes. Every update in postgres is considered as reinsertion of that row regardless of the column getting updated, so all indexes are recalculated. To make it faster, dropping indexes or swapping to a new table would work (if it is possible to do those).
I have a record that holds 2 license "keys" (actually GUIDs). When a request comes to our service it includes a key (GUID) in the request. I then do a query looking for a record that has this value in either the column Key1 or Key2.
The purpose of this is users will use Key1 for everything. Then they discover that Key1 has become public. So they switch to Key2 and then after 15 minutes, change the value of Key1. Now the old Key1 value is of no use.
By having the 2 keys, it allows the switch over with no downtime.
I need any key value to be unique. Not that any pair of values is unique. Not that a value in Key1 is unique in all rows for Key 1. But that a new value is unique in all rows.Key1 and rows.Key2.
Is there a way to force this in Sql Server. Or do I need to do this myself with a select before doing an insert or update?
-------------------------------------------------------------------------------------------
| LicenseId | ApiKey1 | APiKey2 |
| 1 | af53d192-7fa3-4be0-b3d4-7efe17a397b5 | 1a87cc4a-1941-4af7-aeaa-bf9690f47eef |
| 2 | 5bbc2d06-ed6f-4444-aa22-73820dd6f3f6 | c2bdd9d9-fd47-4727-83f8-02ed0e7537e1 |
| 3 | 8acfa8b4-aa4b-41a7-9d3d-b6ba1eac838e | 30c18f2d-5d89-4e5d-8e8e-2d2b647d6ab6 |
-------------------------------------------------------------------------------------------
I need to insure if I am going to create record LicenseId = 4, that if it has ApiKey2 = 'af53d192-7fa3-4be0-b3d4-7efe17a397b5', that the insert will fail because that guid is ApiKey1 for LicenseId = 1.
The most natural way to enforce this in the database is to put all keys in a single column. Eg
create table ApiKeys
(
LicenceId int,
KeyId int check (KeyId in (0,1)),
constraint pk_ApiKeys primary key (LicenceId,KeyId),
KeyGuid uniqueidentifier unique
)
Arguably having both the keys on the same row violates 1NF, and certainly your desire for uniqueness across the two column strongly suggests that they belong to a single domain.
So instead of storing ApiKey1 and ApiKey2 on the same row, you store them on two separate rows.
So instead of
---------------
| LicenseId | ApiKey1 | APiKey2 |
| 1 | af53d192-7fa3-4be0-b3d4-7efe17a397b5 | 1a87cc4a-1941-4af7-aeaa-bf9690f47eef |
| 2 | 5bbc2d06-ed6f-4444-aa22-73820dd6f3f6 | c2bdd9d9-fd47-4727-83f8-02ed0e7537e1 |
| 3 | 8acfa8b4-aa4b-41a7-9d3d-b6ba1eac838e | 30c18f2d-5d89-4e5d-8e8e-2d2b647d6ab6 |
-------------------------------------------------------------------------------------------
You would have:
----------------------------------------------------------
| LicenseId | KeyId | ApiKey |
| 1 | 0 | af53d192-7fa3-4be0-b3d4-7efe17a397b5|
| 1 | 1 | 1a87cc4a-1941-4af7-aeaa-bf9690f47ee4|
| 2 | 0 | 5bbc2d06-ed6f-4444-aa22-73820dd6f3f6|
| 2 | 1 | c2bdd9d9-fd47-4727-83f8-02ed0e7537e1|
| 3 | 0 | 8acfa8b4-aa4b-41a7-9d3d-b6ba1eac838e|
| 3 | 1 | 30c18f2d-5d89-4e5d-8e8e-2d2b647d6ab6|
----------------------------------------------------------
I have the following Psql table structure.
Table "public.kart_user":
Column | Type | Modifiers | Storage | Stats target | Description
------------+------------------------+-----------+----------+--------------+-------------
token | character varying(35) | not null | extended | |
cycle | character varying(200) | | extended | |
userid | character varying(200) | | extended | |
proxyid | character varying(200) | | extended | |
salesrepid | character varying(200) | | extended | |
buyer | character varying(200) | | extended | |
salesrep | character varying(200) | | extended | |
discount | integer[] | | extended | |
custid | character varying(200) | | extended | |
category | character varying(200) | | extended | |
users | character varying(500) | | extended | |
validto | date | | plain | |
ratioonly | boolean | | plain | |
proxy | character varying(500) | | extended | |
validfrom | date | | plain | |
notified | boolean | | plain | |
Indexes:
"kartuser_pkey" PRIMARY KEY, btree (token)
Referenced by:
TABLE "kart_space" CONSTRAINT "kart_space_token_fkey" FOREIGN KEY (token) REFERENCES kart_user(token)
TABLE "kart_order" CONSTRAINT "kartorder_token_fkey" FOREIGN KEY (token) REFERENCES kart_user(token)
I'd like to change the column token from an varchar to a uuid without dropping the foreign key
I have tried the following, but failed.
ALTER TABLE kart_user alter token type uuid using token::uuid;
Note: I don't want to drop the relation ship in any case
How can i fix this issue? Thank you for your response
I am writing a CakePHP application to log the work I do for various clients, but after trying for days I seem unable to get it to do what I want. I have read most of the book CakePHP's website.
and googled for all I'm worth, so I presume I am missing something obvious!
Every 'log item' belongs to a 'sub-project, which in turn belongs to a 'project', which in turn belongs to a 'sub-client' which finally belongs to a client. These are the 5 MySQL tables I am using:
mysql> DESCRIBE log_items;
+-----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| date | date | NO | | NULL | |
| time | time | NO | | NULL | |
| time_spent | int(11) | NO | | NULL | |
| sub_projects_id | int(11) | NO | MUL | NULL | |
| title | varchar(100) | NO | | NULL | |
| description | text | YES | | NULL | |
| created | datetime | YES | | NULL | |
| modified | datetime | YES | | NULL | |
+-----------------+--------------+------+-----+---------+----------------+
mysql> DESCRIBE sub_projects;
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(100) | NO | | NULL | |
| projects_id | int(11) | NO | MUL | NULL | |
| created | datetime | YES | | NULL | |
| modified | datetime | YES | | NULL | |
+-------------+--------------+------+-----+---------+----------------+
mysql> DESCRIBE projects;
+----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(100) | NO | | NULL | |
| sub_clients_id | int(11) | NO | MUL | NULL | |
| created | datetime | YES | | NULL | |
| modified | datetime | YES | | NULL | |
+----------------+--------------+------+-----+---------+----------------+
mysql> DESCRIBE sub_clients;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(100) | NO | | NULL | |
| clients_id | int(11) | NO | MUL | NULL | |
| created | datetime | YES | | NULL | |
| modified | datetime | YES | | NULL | |
+------------+--------------+------+-----+---------+----------------+
mysql> DESCRIBE clients;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(100) | NO | | NULL | |
| created | datetime | YES | | NULL | |
| modified | datetime | YES | | NULL | |
+----------+--------------+------+-----+---------+----------------+
I have set up the following associations in CakePHP:
LogItem belongsTo SubProjects
SubProject belongsTo Projects
Project belongsTo SubClients
SubClient belongsTo Clients
Client hasMany SubClients
SubClient hasMany Projects
Project hasMany SubProjects
SubProject hasMany LogItems
Using 'cake bake' I have created the models, controllers (index, view add, edit and delete) and views, and things seem to function - as in I am able to perform simple CRUD operations successfully.
The Question
When editing a 'log item' at www.mydomain/log_items/edit I am presented with the view you would all suspect; namely the columns of the log_items table with the appropriate textfields/select boxes etc. I would also like to incorporate select boxes to choose the client, sub-client, project and sub-project in the 'log_items' edit view.
Ideally the 'sub-client' select box should populate itself depending upon the 'client' chosen, the 'project' select box should also populate itself depending on the 'sub-client' selected etc, etc.
I guess the way to go about populating the select boxes with relevant options is Ajax, but I am unsure of how to go about actually accessing a model from the child view of a indirectly related model, for example how to create a 'sub-client' select box in the 'log_items' edit view.
I have have found this example:
http://forum.phpsitesolutions.com/php-frameworks/cakephp/ajax-cakephp-dynamically-populate-html-select-dropdown-box-t29.html
where someone achieves something similar for US states, counties and cities. However, I noticed in the database schema - which is downloadable from the site above link - that the database tables don't have any foreign keys, so now I'm wondering if I'm going about things in the correct manner.
Any pointers and advice would be very much appreciated.
Kind regards,
Chris
Your foreign key names should be singular. So projects_id should be project_id and sub_projects_id should be sub_project_id and so forth. If you are using cake bake or scaffolding, you should not be able to edit associated data in each model edit page. As a side note, make sure all you created model classes are singular (in the /models/folder).
To edit multiple levels of association, it maybe as easy as setting the $recursive class member to 2 in each of the models where you want the edit page to have multiple levels of association. Let me know how this works out for you.
In response to your second issue.
Make sure your models have all the proper association. If you baked them they should include them but given your error it looks like they somehow weren't included. So in log_item.php you should have something like
var $belongsTo = array('SubProject');