@opengis/fastify-table 1.1.39 → 1.1.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,27 +1,27 @@
1
- import getRedis from '../../redis/funcs/getRedis.js';
2
- import config from '../../config.js';
3
-
4
- function sprintf(str, ...args) {
5
- return str.replace(/%s/g, () => args.shift());
6
- }
7
-
8
- const keys = {
9
- r: '%s:token:view:%s',
10
- a: '%s:token:add:%s',
11
- w: '%s:token:edit:%s',
12
- e: '%s:token:exec:%s',
13
- };
14
-
15
- async function getToken({
16
- uid, token, mode = 'r', json,
17
- }) {
18
- if (mode === 'r') return token;
19
-
20
- const rclient = getRedis({ db: 0 });
21
-
22
- const key = sprintf(keys[mode], config?.pg?.database, uid?.toString());
23
- const id = await rclient.hget(key, token);
24
- return json && id?.[0] === '{' ? JSON.parse(id) : id;
25
- }
26
-
27
- export default getToken;
1
+ import getRedis from '../../redis/funcs/getRedis.js';
2
+ import config from '../../config.js';
3
+
4
+ function sprintf(str, ...args) {
5
+ return str.replace(/%s/g, () => args.shift());
6
+ }
7
+
8
+ const keys = {
9
+ r: '%s:token:view:%s',
10
+ a: '%s:token:add:%s',
11
+ w: '%s:token:edit:%s',
12
+ e: '%s:token:exec:%s',
13
+ };
14
+
15
+ async function getToken({
16
+ uid, token, mode = 'r', json,
17
+ }) {
18
+ if (mode === 'r') return token;
19
+
20
+ const rclient = getRedis({ db: 0 });
21
+
22
+ const key = sprintf(keys[mode], config?.pg?.database, uid?.toString());
23
+ const id = await rclient.hget(key, token);
24
+ return json && id?.[0] === '{' ? JSON.parse(id) : id;
25
+ }
26
+
27
+ export default getToken;
@@ -1,13 +1,13 @@
1
- import { access } from 'fs/promises';
2
-
3
- const isFileExists = async (filepath) => {
4
- try {
5
- await access(filepath);
6
- return true;
7
- }
8
- catch (err) {
9
- return false;
10
- }
11
- };
12
-
13
- export default isFileExists;
1
+ import { access } from 'fs/promises';
2
+
3
+ const isFileExists = async (filepath) => {
4
+ try {
5
+ await access(filepath);
6
+ return true;
7
+ }
8
+ catch (err) {
9
+ return false;
10
+ }
11
+ };
12
+
13
+ export default isFileExists;
@@ -1,53 +1,53 @@
1
- import { createHash, randomUUID } from 'crypto';
2
-
3
- import config from '../../config.js';
4
- import getRedis from '../../redis/funcs/getRedis.js';
5
-
6
- const generateCodes = (ids, userToken) => {
7
- const token = userToken || randomUUID();
8
- const notNullIds = ids.filter((el) => el);
9
- const obj = {};
10
- const codes = notNullIds.reduce((acc, id) => {
11
- const newToken = createHash('sha1').update(token + id).digest('base64url').replace(/-/g, '');
12
- acc[newToken] = id; obj[id] = newToken;
13
- return acc;
14
- }, {});
15
- return { codes, obj };
16
- };
17
-
18
- function setToken({
19
- ids: idsOrigin, mode = 'r', uid, referer, array,
20
- }) {
21
- const rclient2 = getRedis({ db: 0 });
22
- // const rclient5 = getRedis({ db: 0, funcs });
23
-
24
- if (!uid) return { user: 'empty' };
25
- if (!Object.keys(idsOrigin).length) return { ids: 'empty' };
26
-
27
- const ids = idsOrigin.map((el) => (typeof el === 'object' ? JSON.stringify(el) : el));
28
- // update/delete
29
-
30
- if (mode === 'r') return null;
31
-
32
- // TODO generate salt
33
- const { codes, obj } = generateCodes(ids, uid);
34
-
35
- if (!Object.keys(codes).length) return { ids: 'empty' };
36
-
37
- rclient2.hmset(`${config.pg.database}:token:${{
38
- e: 'exec', r: 'view', w: 'edit', a: 'add',
39
- }[mode]}:${uid}`, codes);
40
-
41
- // log token for debug. add extra data - uid, mode, date
42
- /* const dt = new Date().toISOString();
43
- const codesLog = Object.keys(codes).reduce((acc, key) => {
44
- acc[key] = `{"referer": "${referer}" ,"uid":"${uid}","mode":"${mode}","date":"${dt}",${codes[key].substr(1)}`;
45
- return acc;
46
- }, {});
47
- rclient5.hmset(`${config.pg.database}:token:edit`, codesLog); // 'EX', 64800 */
48
-
49
- // TODO дополнительно писать в hset token -> uid
50
- return array ? Object.values(obj) : obj;
51
- }
52
-
53
- export default setToken;
1
+ import { createHash, randomUUID } from 'crypto';
2
+
3
+ import config from '../../config.js';
4
+ import getRedis from '../../redis/funcs/getRedis.js';
5
+
6
+ const generateCodes = (ids, userToken) => {
7
+ const token = userToken || randomUUID();
8
+ const notNullIds = ids.filter((el) => el);
9
+ const obj = {};
10
+ const codes = notNullIds.reduce((acc, id) => {
11
+ const newToken = createHash('sha1').update(token + id).digest('base64url').replace(/-/g, '');
12
+ acc[newToken] = id; obj[id] = newToken;
13
+ return acc;
14
+ }, {});
15
+ return { codes, obj };
16
+ };
17
+
18
+ function setToken({
19
+ ids: idsOrigin, mode = 'r', uid, referer, array,
20
+ }) {
21
+ const rclient2 = getRedis({ db: 0 });
22
+ // const rclient5 = getRedis({ db: 0, funcs });
23
+
24
+ if (!uid) return { user: 'empty' };
25
+ if (!Object.keys(idsOrigin).length) return { ids: 'empty' };
26
+
27
+ const ids = idsOrigin.map((el) => (typeof el === 'object' ? JSON.stringify(el) : el));
28
+ // update/delete
29
+
30
+ if (mode === 'r') return null;
31
+
32
+ // TODO generate salt
33
+ const { codes, obj } = generateCodes(ids, uid);
34
+
35
+ if (!Object.keys(codes).length) return { ids: 'empty' };
36
+
37
+ rclient2.hmset(`${config.pg.database}:token:${{
38
+ e: 'exec', r: 'view', w: 'edit', a: 'add',
39
+ }[mode]}:${uid}`, codes);
40
+
41
+ // log token for debug. add extra data - uid, mode, date
42
+ /* const dt = new Date().toISOString();
43
+ const codesLog = Object.keys(codes).reduce((acc, key) => {
44
+ acc[key] = `{"referer": "${referer}" ,"uid":"${uid}","mode":"${mode}","date":"${dt}",${codes[key].substr(1)}`;
45
+ return acc;
46
+ }, {});
47
+ rclient5.hmset(`${config.pg.database}:token:edit`, codesLog); // 'EX', 64800 */
48
+
49
+ // TODO дополнительно писать в hset token -> uid
50
+ return array ? Object.values(obj) : obj;
51
+ }
52
+
53
+ export default setToken;
@@ -1,49 +1,49 @@
1
- import path from 'path';
2
- import { existsSync } from 'fs';
3
- import { fileURLToPath } from 'url';
4
-
5
- const fileName = fileURLToPath(import.meta.url);
6
- const dirName = path.dirname(fileName);
7
-
8
- import notification from '../funcs/sendNotification.js';
9
-
10
- export default async function testNotification({
11
- pg, funcs = {}, log, query = {}, session = {},
12
- }) {
13
- const { local } = funcs.config || {};
14
- if (!session?.passport?.user?.user_type?.includes('admin') && !local) {
15
- return { message: 'Forbidden', status: 403 };
16
- }
17
-
18
- const date = new Date().toISOString().split('T')[0];
19
- if (!query.to) {
20
- return { message: 'param to is required', status: 400 };
21
- }
22
-
23
- try {
24
- const {
25
- to, template, table, id, nocache,
26
- } = query;
27
- const file = [path.join(dirName, '../../', 'changelog.md'), path.join(dirName, 'utils', 'pin-m-ty-media-record-outline+303070.png')].filter((el) => existsSync(el));
28
- const data = await notification({
29
- pg,
30
- funcs,
31
- log,
32
- to,
33
- template,
34
- title: `Test Softpro ${date}`,
35
- table,
36
- nocache,
37
- file,
38
- id,
39
- message: `Test mail Softpro ${date} Lorem Ipsum Lorem Ipsum`,
40
- });
41
-
42
- return {
43
- message: data || 'ok',
44
- };
45
- }
46
- catch (err) {
47
- return { error: err.toString(), status: 500 };
48
- }
49
- }
1
+ import path from 'path';
2
+ import { existsSync } from 'fs';
3
+ import { fileURLToPath } from 'url';
4
+
5
+ const fileName = fileURLToPath(import.meta.url);
6
+ const dirName = path.dirname(fileName);
7
+
8
+ import notification from '../funcs/sendNotification.js';
9
+
10
+ export default async function testNotification({
11
+ pg, funcs = {}, log, query = {}, session = {},
12
+ }) {
13
+ const { local } = funcs.config || {};
14
+ if (!session?.passport?.user?.user_type?.includes('admin') && !local) {
15
+ return { message: 'Forbidden', status: 403 };
16
+ }
17
+
18
+ const date = new Date().toISOString().split('T')[0];
19
+ if (!query.to) {
20
+ return { message: 'param to is required', status: 400 };
21
+ }
22
+
23
+ try {
24
+ const {
25
+ to, template, table, id, nocache,
26
+ } = query;
27
+ const file = [path.join(dirName, '../../', 'changelog.md'), path.join(dirName, 'utils', 'pin-m-ty-media-record-outline+303070.png')].filter((el) => existsSync(el));
28
+ const data = await notification({
29
+ pg,
30
+ funcs,
31
+ log,
32
+ to,
33
+ template,
34
+ title: `Test Softpro ${date}`,
35
+ table,
36
+ nocache,
37
+ file,
38
+ id,
39
+ message: `Test mail Softpro ${date} Lorem Ipsum Lorem Ipsum`,
40
+ });
41
+
42
+ return {
43
+ message: data || 'ok',
44
+ };
45
+ }
46
+ catch (err) {
47
+ return { error: err.toString(), status: 500 };
48
+ }
49
+ }
@@ -1,39 +1,39 @@
1
- import nodemailer from 'nodemailer';
2
-
3
- /**
4
- * Надсилає поваідомлення на пошту
5
- *
6
- * @type function
7
- * @alias sendEmail
8
- * @summary Функція здійснює розсилку по email
9
- */
10
-
11
- export default async function sendEmail({
12
- funcs, to, from, subject, html, attachments,
13
- }) {
14
- const { config = {} } = funcs;
15
-
16
- if (!to?.length) {
17
- throw new Error('empty to list');
18
- }
19
-
20
- const { mailSetting = {} } = config;
21
-
22
- /*= == check service and setting === */
23
- if (!mailSetting.service) {
24
- throw new Error('service is not defined in config');
25
- }
26
-
27
- Object.assign(mailSetting, { rejectUnauthorized: false });
28
-
29
- if (mailSetting.port === 465) {
30
- Object.assign(mailSetting, { secure: true });
31
- }
32
-
33
- const transport = nodemailer.createTransport(mailSetting);
34
-
35
- const result = await transport.sendMail({
36
- from: from || mailSetting.from, to, subject, html, attachments,
37
- });
38
- return result;
39
- }
1
+ import nodemailer from 'nodemailer';
2
+
3
+ /**
4
+ * Надсилає поваідомлення на пошту
5
+ *
6
+ * @type function
7
+ * @alias sendEmail
8
+ * @summary Функція здійснює розсилку по email
9
+ */
10
+
11
+ export default async function sendEmail({
12
+ funcs, to, from, subject, html, attachments,
13
+ }) {
14
+ const { config = {} } = funcs;
15
+
16
+ if (!to?.length) {
17
+ throw new Error('empty to list');
18
+ }
19
+
20
+ const { mailSetting = {} } = config;
21
+
22
+ /*= == check service and setting === */
23
+ if (!mailSetting.service) {
24
+ throw new Error('service is not defined in config');
25
+ }
26
+
27
+ Object.assign(mailSetting, { rejectUnauthorized: false });
28
+
29
+ if (mailSetting.port === 465) {
30
+ Object.assign(mailSetting, { secure: true });
31
+ }
32
+
33
+ const transport = nodemailer.createTransport(mailSetting);
34
+
35
+ const result = await transport.sendMail({
36
+ from: from || mailSetting.from, to, subject, html, attachments,
37
+ });
38
+ return result;
39
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengis/fastify-table",
3
- "version": "1.1.39",
3
+ "version": "1.1.40",
4
4
  "type": "module",
5
5
  "description": "core-plugins",
6
6
  "main": "index.js",
package/pg/funcs/getPG.js CHANGED
@@ -1,30 +1,30 @@
1
- import pg from 'pg';
2
- import config from '../../config.js';
3
- import pgClients from '../pgClients.js';
4
- import init from './init.js';
5
-
6
- function getPG(param) {
7
- const {
8
- user, password, host, port, db, database, name: origin, funcs,
9
- } = param || {};
10
- if (funcs?.config) Object.assign(config, { ...funcs.config }); // unit test
11
- const name = origin || db || database || param || 'client';
12
- if (pgClients[name]) return pgClients[name];
13
-
14
- const dbConfig = {
15
- user: user || config.pg?.user,
16
- password: password || config.pg?.password,
17
- host: host || config.pg?.host,
18
- port: port || config.pg?.port,
19
- database: db || database || config.pg?.db || config.pg?.database,
20
- };
21
-
22
- pgClients[name] = new pg.Pool(dbConfig);
23
- pgClients[name].init = async () => {
24
- await init(pgClients[name]);
25
- };
26
- init(pgClients[name]);
27
- return pgClients[name];
28
- }
29
-
30
- export default getPG;
1
+ import pg from 'pg';
2
+ import config from '../../config.js';
3
+ import pgClients from '../pgClients.js';
4
+ import init from './init.js';
5
+
6
+ function getPG(param) {
7
+ const {
8
+ user, password, host, port, db, database, name: origin, funcs,
9
+ } = param || {};
10
+ if (funcs?.config) Object.assign(config, { ...funcs.config }); // unit test
11
+ const name = origin || db || database || param || 'client';
12
+ if (pgClients[name]) return pgClients[name];
13
+
14
+ const dbConfig = {
15
+ user: user || config.pg?.user,
16
+ password: password || config.pg?.password,
17
+ host: host || config.pg?.host,
18
+ port: port || config.pg?.port,
19
+ database: db || database || config.pg?.db || config.pg?.database,
20
+ };
21
+
22
+ pgClients[name] = new pg.Pool(dbConfig);
23
+ pgClients[name].init = async () => {
24
+ await init(pgClients[name]);
25
+ };
26
+ init(pgClients[name]);
27
+ return pgClients[name];
28
+ }
29
+
30
+ export default getPG;
@@ -1,23 +1,23 @@
1
- import Redis from 'ioredis';
2
- import config from '../../config.js';
3
- import redisClients from './redisClients.js';
4
-
5
- function getRedis({ db } = { db: 0 }) {
6
- if (!config.redis) return null;
7
- if (redisClients[db]) return redisClients[db];
8
-
9
- const redisConfig = {
10
- db,
11
- keyPrefix: `${config.db}:`,
12
- host: config.redis?.host || '127.0.0.1',
13
- port: config.redis?.port || 6379, // Redis port
14
- family: 4, // 4 (IPv4) or 6 (IPv6)
15
- closeClient: true,
16
- };
17
-
18
- redisClients[db] = new Redis(redisConfig);
19
-
20
- return redisClients[db];
21
- }
22
-
23
- export default getRedis;
1
+ import Redis from 'ioredis';
2
+ import config from '../../config.js';
3
+ import redisClients from './redisClients.js';
4
+
5
+ function getRedis({ db } = { db: 0 }) {
6
+ if (!config.redis) return null;
7
+ if (redisClients[db]) return redisClients[db];
8
+
9
+ const redisConfig = {
10
+ db,
11
+ keyPrefix: `${config.db}:`,
12
+ host: config.redis?.host || '127.0.0.1',
13
+ port: config.redis?.port || 6379, // Redis port
14
+ family: 4, // 4 (IPv4) or 6 (IPv6)
15
+ closeClient: true,
16
+ };
17
+
18
+ redisClients[db] = new Redis(redisConfig);
19
+
20
+ return redisClients[db];
21
+ }
22
+
23
+ export default getRedis;
@@ -1,81 +1,81 @@
1
- create schema if not exists log;
2
-
3
- -- DROP TABLE IF EXISTS log.table_changes cascade;
4
- CREATE TABLE IF NOT EXISTS log.table_changes();
5
- ALTER TABLE log.table_changes ADD COLUMN IF NOT EXISTS change_id text NOT NULL DEFAULT next_id();
6
- ALTER TABLE log.table_changes ADD COLUMN IF NOT EXISTS change_type text;
7
- ALTER TABLE log.table_changes ADD COLUMN IF NOT EXISTS change_date date;
8
- ALTER TABLE log.table_changes ADD COLUMN IF NOT EXISTS change_user_id text;
9
- ALTER TABLE log.table_changes ADD COLUMN IF NOT EXISTS entity_type text; -- table_name
10
- ALTER TABLE log.table_changes ADD COLUMN IF NOT EXISTS entity_id text; -- object_id
11
- ALTER TABLE log.table_changes ADD COLUMN IF NOT EXISTS uid text;
12
- ALTER TABLE log.table_changes ADD COLUMN IF NOT EXISTS cdate timestamp without time zone DEFAULT (now())::timestamp without time zone;
13
- ALTER TABLE log.table_changes ADD COLUMN IF NOT EXISTS editor_id text;
14
- ALTER TABLE log.table_changes ADD COLUMN IF NOT EXISTS editor_date timestamp without time zone;
15
-
16
- -- DROP TABLE IF EXISTS log.table_changes_data;
17
- CREATE TABLE IF NOT EXISTS log.table_changes_data();
18
- ALTER TABLE log.table_changes_data ADD COLUMN IF NOT EXISTS change_data_id text NOT NULL DEFAULT next_id();
19
- ALTER TABLE log.table_changes_data ADD COLUMN IF NOT EXISTS change_id text not null;
20
- ALTER TABLE log.table_changes_data ADD COLUMN IF NOT EXISTS entity_key text; -- column_name
21
- ALTER TABLE log.table_changes_data ADD COLUMN IF NOT EXISTS value_old text;
22
- ALTER TABLE log.table_changes_data ADD COLUMN IF NOT EXISTS value_new text;
23
- ALTER TABLE log.table_changes_data ADD COLUMN IF NOT EXISTS uid text;
24
- ALTER TABLE log.table_changes_data ADD COLUMN IF NOT EXISTS cdate timestamp without time zone DEFAULT (now())::timestamp without time zone;
25
- ALTER TABLE log.table_changes_data ADD COLUMN IF NOT EXISTS editor_id text;
26
- ALTER TABLE log.table_changes_data ADD COLUMN IF NOT EXISTS editor_date timestamp without time zone;
27
-
28
- -- DROP TABLE IF EXISTS log.user_auth;
29
- CREATE TABLE IF NOT EXISTS log.user_auth();
30
- ALTER TABLE log.user_auth ADD COLUMN IF NOT EXISTS user_auth_id text NOT NULL DEFAULT next_id();
31
- ALTER TABLE log.user_auth ADD COLUMN IF NOT EXISTS user_id text;
32
- ALTER TABLE log.user_auth ADD COLUMN IF NOT EXISTS auth_date timestamp without time zone;
33
- ALTER TABLE log.user_auth ADD COLUMN IF NOT EXISTS auth_type text;
34
- ALTER TABLE log.user_auth ADD COLUMN IF NOT EXISTS uid text;
35
- ALTER TABLE log.user_auth ADD COLUMN IF NOT EXISTS cdate timestamp without time zone DEFAULT (now())::timestamp without time zone;
36
- ALTER TABLE log.user_auth ADD COLUMN IF NOT EXISTS editor_id text;
37
- ALTER TABLE log.user_auth ADD COLUMN IF NOT EXISTS editor_date timestamp without time zone;
38
-
39
- COMMENT ON TABLE log.table_changes IS 'Логи подій змін в БД';
40
- COMMENT ON COLUMN log.table_changes.change_type IS 'Тип події (insert / update / delete)';
41
- COMMENT ON COLUMN log.table_changes.change_date IS 'Дата внесення змін до БД';
42
- COMMENT ON COLUMN log.table_changes.entity_type IS 'Таблиця, до якої вносяться зміни';
43
- COMMENT ON COLUMN log.table_changes.entity_id IS 'ID строки, до якої вносяться зміни';
44
- COMMENT ON COLUMN log.table_changes.change_user_id IS 'Ініціатор внесення змін';
45
-
46
- COMMENT ON TABLE log.table_changes_data IS 'Логи змін в таблицях БД';
47
- COMMENT ON COLUMN log.table_changes_data.change_id IS 'ID події зміни в БД';
48
- COMMENT ON COLUMN log.table_changes_data.entity_key IS 'Колонка таблиці, до якої вносяться зміни';
49
- COMMENT ON COLUMN log.table_changes_data.value_old IS 'Старе значення';
50
- COMMENT ON COLUMN log.table_changes_data.value_new IS 'Нове значення';
51
-
52
- COMMENT ON TABLE log.user_auth IS 'Логи авторизації';
53
- COMMENT ON COLUMN log.user_auth.user_id IS 'ID користувача';
54
- COMMENT ON COLUMN log.user_auth.auth_date IS 'Дата авторизації';
55
- COMMENT ON COLUMN log.user_auth.auth_type IS 'Тип авторизації';
56
-
57
- ALTER TABLE log.table_changes DROP CONSTRAINT IF EXISTS log_table_changes_pkey cascade;
58
- ALTER TABLE log.table_changes_data DROP CONSTRAINT IF EXISTS log_table_changes_data_pkey;
59
- ALTER TABLE log.table_changes_data DROP CONSTRAINT IF EXISTS log_table_changes_data_change_id_fkey;
60
- ALTER TABLE log.user_auth DROP CONSTRAINT IF EXISTS log_user_auth_pkey;
61
- ALTER TABLE log.user_auth DROP CONSTRAINT IF EXISTS log_user_auth_user_id_fkey;
62
-
63
- ALTER TABLE log.table_changes ADD CONSTRAINT log_table_changes_pkey PRIMARY KEY (change_id);
64
- ALTER TABLE log.table_changes_data ADD CONSTRAINT log_table_changes_data_pkey PRIMARY KEY (change_data_id);
65
- ALTER TABLE log.table_changes_data ADD CONSTRAINT log_table_changes_data_change_id_fkey FOREIGN KEY (change_id)
66
- REFERENCES log.table_changes (change_id);
67
- ALTER TABLE log.user_auth ADD CONSTRAINT log_user_auth_pkey PRIMARY KEY (user_auth_id);
68
- -- ALTER TABLE log.user_auth ADD CONSTRAINT log_user_auth_user_id_fkey FOREIGN KEY (user_id) REFERENCES admin.users (uid) MATCH SIMPLE;
69
-
70
- /* drop old columns */
71
- alter table log.table_changes drop column if exists date_new;
72
- alter table log.table_changes drop column if exists date_old;
73
- alter table log.table_changes drop column if exists number_new;
74
- alter table log.table_changes drop column if exists number_old;
75
- alter table log.table_changes drop column if exists json_new;
76
- alter table log.table_changes drop column if exists json_old;
77
- alter table log.table_changes drop column if exists text_new;
78
- alter table log.table_changes drop column if exists text_old;
79
- alter table log.table_changes drop column if exists bool_new;
80
- alter table log.table_changes drop column if exists bool_old;
1
+ create schema if not exists log;
2
+
3
+ -- DROP TABLE IF EXISTS log.table_changes cascade;
4
+ CREATE TABLE IF NOT EXISTS log.table_changes();
5
+ ALTER TABLE log.table_changes ADD COLUMN IF NOT EXISTS change_id text NOT NULL DEFAULT next_id();
6
+ ALTER TABLE log.table_changes ADD COLUMN IF NOT EXISTS change_type text;
7
+ ALTER TABLE log.table_changes ADD COLUMN IF NOT EXISTS change_date date;
8
+ ALTER TABLE log.table_changes ADD COLUMN IF NOT EXISTS change_user_id text;
9
+ ALTER TABLE log.table_changes ADD COLUMN IF NOT EXISTS entity_type text; -- table_name
10
+ ALTER TABLE log.table_changes ADD COLUMN IF NOT EXISTS entity_id text; -- object_id
11
+ ALTER TABLE log.table_changes ADD COLUMN IF NOT EXISTS uid text;
12
+ ALTER TABLE log.table_changes ADD COLUMN IF NOT EXISTS cdate timestamp without time zone DEFAULT (now())::timestamp without time zone;
13
+ ALTER TABLE log.table_changes ADD COLUMN IF NOT EXISTS editor_id text;
14
+ ALTER TABLE log.table_changes ADD COLUMN IF NOT EXISTS editor_date timestamp without time zone;
15
+
16
+ -- DROP TABLE IF EXISTS log.table_changes_data;
17
+ CREATE TABLE IF NOT EXISTS log.table_changes_data();
18
+ ALTER TABLE log.table_changes_data ADD COLUMN IF NOT EXISTS change_data_id text NOT NULL DEFAULT next_id();
19
+ ALTER TABLE log.table_changes_data ADD COLUMN IF NOT EXISTS change_id text not null;
20
+ ALTER TABLE log.table_changes_data ADD COLUMN IF NOT EXISTS entity_key text; -- column_name
21
+ ALTER TABLE log.table_changes_data ADD COLUMN IF NOT EXISTS value_old text;
22
+ ALTER TABLE log.table_changes_data ADD COLUMN IF NOT EXISTS value_new text;
23
+ ALTER TABLE log.table_changes_data ADD COLUMN IF NOT EXISTS uid text;
24
+ ALTER TABLE log.table_changes_data ADD COLUMN IF NOT EXISTS cdate timestamp without time zone DEFAULT (now())::timestamp without time zone;
25
+ ALTER TABLE log.table_changes_data ADD COLUMN IF NOT EXISTS editor_id text;
26
+ ALTER TABLE log.table_changes_data ADD COLUMN IF NOT EXISTS editor_date timestamp without time zone;
27
+
28
+ -- DROP TABLE IF EXISTS log.user_auth;
29
+ CREATE TABLE IF NOT EXISTS log.user_auth();
30
+ ALTER TABLE log.user_auth ADD COLUMN IF NOT EXISTS user_auth_id text NOT NULL DEFAULT next_id();
31
+ ALTER TABLE log.user_auth ADD COLUMN IF NOT EXISTS user_id text;
32
+ ALTER TABLE log.user_auth ADD COLUMN IF NOT EXISTS auth_date timestamp without time zone;
33
+ ALTER TABLE log.user_auth ADD COLUMN IF NOT EXISTS auth_type text;
34
+ ALTER TABLE log.user_auth ADD COLUMN IF NOT EXISTS uid text;
35
+ ALTER TABLE log.user_auth ADD COLUMN IF NOT EXISTS cdate timestamp without time zone DEFAULT (now())::timestamp without time zone;
36
+ ALTER TABLE log.user_auth ADD COLUMN IF NOT EXISTS editor_id text;
37
+ ALTER TABLE log.user_auth ADD COLUMN IF NOT EXISTS editor_date timestamp without time zone;
38
+
39
+ COMMENT ON TABLE log.table_changes IS 'Логи подій змін в БД';
40
+ COMMENT ON COLUMN log.table_changes.change_type IS 'Тип події (insert / update / delete)';
41
+ COMMENT ON COLUMN log.table_changes.change_date IS 'Дата внесення змін до БД';
42
+ COMMENT ON COLUMN log.table_changes.entity_type IS 'Таблиця, до якої вносяться зміни';
43
+ COMMENT ON COLUMN log.table_changes.entity_id IS 'ID строки, до якої вносяться зміни';
44
+ COMMENT ON COLUMN log.table_changes.change_user_id IS 'Ініціатор внесення змін';
45
+
46
+ COMMENT ON TABLE log.table_changes_data IS 'Логи змін в таблицях БД';
47
+ COMMENT ON COLUMN log.table_changes_data.change_id IS 'ID події зміни в БД';
48
+ COMMENT ON COLUMN log.table_changes_data.entity_key IS 'Колонка таблиці, до якої вносяться зміни';
49
+ COMMENT ON COLUMN log.table_changes_data.value_old IS 'Старе значення';
50
+ COMMENT ON COLUMN log.table_changes_data.value_new IS 'Нове значення';
51
+
52
+ COMMENT ON TABLE log.user_auth IS 'Логи авторизації';
53
+ COMMENT ON COLUMN log.user_auth.user_id IS 'ID користувача';
54
+ COMMENT ON COLUMN log.user_auth.auth_date IS 'Дата авторизації';
55
+ COMMENT ON COLUMN log.user_auth.auth_type IS 'Тип авторизації';
56
+
57
+ ALTER TABLE log.table_changes DROP CONSTRAINT IF EXISTS log_table_changes_pkey cascade;
58
+ ALTER TABLE log.table_changes_data DROP CONSTRAINT IF EXISTS log_table_changes_data_pkey;
59
+ ALTER TABLE log.table_changes_data DROP CONSTRAINT IF EXISTS log_table_changes_data_change_id_fkey;
60
+ ALTER TABLE log.user_auth DROP CONSTRAINT IF EXISTS log_user_auth_pkey;
61
+ ALTER TABLE log.user_auth DROP CONSTRAINT IF EXISTS log_user_auth_user_id_fkey;
62
+
63
+ ALTER TABLE log.table_changes ADD CONSTRAINT log_table_changes_pkey PRIMARY KEY (change_id);
64
+ ALTER TABLE log.table_changes_data ADD CONSTRAINT log_table_changes_data_pkey PRIMARY KEY (change_data_id);
65
+ ALTER TABLE log.table_changes_data ADD CONSTRAINT log_table_changes_data_change_id_fkey FOREIGN KEY (change_id)
66
+ REFERENCES log.table_changes (change_id);
67
+ ALTER TABLE log.user_auth ADD CONSTRAINT log_user_auth_pkey PRIMARY KEY (user_auth_id);
68
+ -- ALTER TABLE log.user_auth ADD CONSTRAINT log_user_auth_user_id_fkey FOREIGN KEY (user_id) REFERENCES admin.users (uid) MATCH SIMPLE;
69
+
70
+ /* drop old columns */
71
+ alter table log.table_changes drop column if exists date_new;
72
+ alter table log.table_changes drop column if exists date_old;
73
+ alter table log.table_changes drop column if exists number_new;
74
+ alter table log.table_changes drop column if exists number_old;
75
+ alter table log.table_changes drop column if exists json_new;
76
+ alter table log.table_changes drop column if exists json_old;
77
+ alter table log.table_changes drop column if exists text_new;
78
+ alter table log.table_changes drop column if exists text_old;
79
+ alter table log.table_changes drop column if exists bool_new;
80
+ alter table log.table_changes drop column if exists bool_old;
81
81
  alter table log.table_changes drop column if exists table_change_id;