CI / Сборка (push) Canceled after 0s
CI / Деплой на стейджинг (push) Canceled after 0s
CI / Проверка кода (push) Canceled after 0s
CI / Сборка (pull_request) Successful in 1m33s
Стенд master
CI / Деплой на стейджинг (pull_request) Successful in 8s
CI / Проверка кода (pull_request) Successful in 1m32s
92 lines
2.7 KiB
TypeScript
92 lines
2.7 KiB
TypeScript
import { access, mkdir, rm, writeFile } from 'fs/promises';
|
|
import path from 'path';
|
|
|
|
import { config } from 'dotenv';
|
|
import { Pool, types } from 'pg';
|
|
|
|
const nodeEnv = process.env.NODE_ENV || 'production';
|
|
config({ path: path.resolve(process.cwd(), `.env.${nodeEnv}`) });
|
|
config({ path: path.resolve(process.cwd(), '.env') });
|
|
|
|
const pool = new Pool({
|
|
host: process.env.POSTGRES_HOST,
|
|
port: +process.env.POSTGRES_PORT!,
|
|
user: process.env.POSTGRES_USER,
|
|
password: process.env.POSTGRES_PASSWORD,
|
|
database: process.env.POSTGRES_DB,
|
|
});
|
|
|
|
const snapshotDir = path.join(__dirname, '../db-snapshot');
|
|
|
|
const excludedTables = ['migrations', 'oauth_providers'];
|
|
|
|
// так как в ДБ используются поля без часового пояса, а по умолчанию pg будет ставить UTC
|
|
function disableTZProcessing() {
|
|
types.setTypeParser(1114, function (stringValue) {
|
|
return stringValue;
|
|
});
|
|
}
|
|
|
|
async function main() {
|
|
disableTZProcessing();
|
|
|
|
const db = await pool.connect();
|
|
|
|
console.log('ДБ подключена');
|
|
await db.query("SET timezone TO 'GMT';");
|
|
|
|
const tables = await db
|
|
.query(
|
|
`
|
|
SELECT c.relname AS tablename, (array_agg(a.attname))[1] AS key
|
|
FROM pg_index i
|
|
JOIN pg_class c ON c.oid = i.indrelid
|
|
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = ANY(i.indkey)
|
|
WHERE i.indisprimary
|
|
AND n.nspname = 'public'
|
|
AND c.relname NOT IN (${excludedTables.map(wrapInQuotes).join(',')})
|
|
GROUP BY c.relname
|
|
ORDER BY c.relname;
|
|
`,
|
|
)
|
|
.then((response): { tablename: string; key: string }[] => response.rows);
|
|
|
|
const promises = tables.map(async (table) => {
|
|
const data = await db.query(`SELECT * FROM ${table.tablename} ORDER BY "${table.key}"`);
|
|
|
|
return { ...table, rows: data.rows };
|
|
});
|
|
|
|
const entries = await Promise.all(promises);
|
|
|
|
await access(snapshotDir).then(
|
|
async () => {
|
|
await rm(snapshotDir, { recursive: true });
|
|
},
|
|
() => {},
|
|
);
|
|
|
|
await mkdir(snapshotDir, { recursive: true });
|
|
|
|
const report = await Promise.all(
|
|
entries.map(async (table) =>
|
|
writeFile(
|
|
path.join(snapshotDir, table.tablename + '.json'),
|
|
JSON.stringify(table.rows, null, 4) + '\n',
|
|
'utf8',
|
|
),
|
|
),
|
|
);
|
|
|
|
console.log('Сохранено таблиц: `\x1b[0;32m' + report.length + '\x1b[0m`');
|
|
db.release();
|
|
await pool.end();
|
|
}
|
|
|
|
function wrapInQuotes(text: string) {
|
|
return "'" + text + "'";
|
|
}
|
|
|
|
main();
|