· 6 years ago · Apr 22, 2019, 07:38 PM
1```sql
2begin;
3drop table if exists audit_data;
4create table audit_data ( id bigserial unique not null, payment_id text, payload text );
5insert into audit_data (payment_id, payload)
6select md5(i::text),
7 repeat(md5(i::text), 10)
8from generate_series(1, 1000*1000) s(i);
9commit;
10
11
12select pg_size_pretty(pg_total_relation_size('audit_data'));
13
14begin;
15
16drop table if exists audit_data_log;
17create table audit_data_log (id bigserial, storage_data json);
18
19do $$
20declare
21 cur cursor(id bigint)
22 for select * from audit_data;
23 pack json[];
24 count int;
25 rec record;
26begin
27 open cur(0);
28 loop
29 fetch cur into rec;
30 exit when not found;
31 pack := array_append(pack, row_to_json(rec.*));
32 count := count + 1;
33 if count = 100 then
34 insert into audit_data_log(storage_data) values (json_build_array(pack));
35 pack = null;
36 count = 0;
37 end if;
38 end loop;
39 close cur;
40 insert into audit_data_log(storage_data) values (json_build_array(pack));
41end
42$$ language plpgsql;
43
44commit;
45
46select pg_size_pretty(pg_total_relation_size('audit_data_log'));
47
48```