I have 2 tables:
\d folder
Table "public.folder"
Column | Type | Modifiers
---------+-----------------------+----------------------------------------------------
id | integer | not null default nextval('folder_id_seq'::regclass)
name | character varying(20) |
parent_id | integer |
Indexes:
"folder_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"fk_folder_1" FOREIGN KEY (parent_id) REFERENCES folder(id)
Referenced by:
TABLE "files" CONSTRAINT "fk_files_1" FOREIGN KEY (folder_id) REFERENCES folder(id)
TABLE "folder" CONSTRAINT "fk_folder_1" FOREIGN KEY (parent_id) REFERENCES folder(id)
\d files
Table "public.files"
Column | Type | Modifiers
----------+-----------------------+---------------------------------------------------
id | integer | not null default nextval('files_id_seq'::regclass)
name | character varying(20) |
folder_id | integer |
Indexes:
"files_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"fk_files_1" FOREIGN KEY (folder_id) REFERENCES folder(id)
select * from folder;
id | name | parent_id
----+---------+-----------
1 | home |
2 | folder2 | 1
3 | folder3 | 1
4 | folder4 | 2
5 | folder5 | 4
6 | folder6 | 5
(6 rows)
select * from files;
id | name | folder_id
----+-------+-----------
1 | file1 | 4
2 | file2 | 4
3 | file3 | 5
4 | file4 | 6
5 | file5 | 6
6 | file6 | 2
(6 rows)
Now I need a function or cursor or any thing which will get two inputs,folder to copy and destination folder to copy, the function should copy the folder and its child folders into the same table with new id and parent id as below, same time when folder is copied and inserted the file in files table is also to be inserted, plz help me get the below result..
if I am coping folder5 to folder3 my output should be like this:
select * from folder;
id | name | parent_id
----+---------+-----------
1 | home |
2 | folder2 | 1
3 | folder3 | 1
4 | folder4 | 2
5 | folder5 | 4
6 | folder6 | 5
7 | folder5 | 3
8 | folder6 | 7
(8 rows)
and files table is also to be updated when folder is copied and inserted like this:
select * from files;
id | name | folder_id
----+-------+-----------
1 | file1 | 4
2 | file2 | 4
3 | file3 | 5
4 | file4 | 6
5 | file5 | 6
6 | file6 | 2
7 | file3 | 7
8 | file4 | 8
9 | file5 | 8
(9 rows)
this will do as i thought…