-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
executable file
·157 lines (135 loc) · 4.33 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
const { Client } = require('pg')
const fs = require('fs-extra')
const path = require('path')
const recursiveReadDir = require('recursive-readdir')
function parseComments(file) {
const lines = file.split('\n'), require = []
let i = 0, dropCode = ''
while(lines[i].startsWith('--') || lines[i].trim() === '') {
if (lines[i].startsWith('-- drop-code')) {
dropCode = lines[i].slice(13)
}
if (lines[i].startsWith('-- require')) {
require.push(lines[i].slice(11))
}
i++
}
return { require, dropCode }
}
function removeNode(adjacencyLists, node) {
delete adjacencyLists[node]
Object.keys(adjacencyLists).forEach(key => {
const index = adjacencyLists[key].indexOf(node)
if (index > -1) {
adjacencyLists[key].splice(index, 1)
}
})
}
async function syncFiles(client, config) {
if (config.schema) {
await client.query(`SET SCHEMA '${config.schema}'`)
}
await client.query('CREATE TABLE IF NOT EXISTS pgcodebase_dropcodes (id bigserial PRIMARY KEY, dropcode text)')
if (!config.createOnly) {
const dropCodesResult = await client.query('SELECT dropcode FROM pgcodebase_dropcodes ORDER BY id DESC')
await dropCodesResult.rows
.map(row => async () => await client.query(row.dropcode))
.reduce(
(promise, func) => promise.then(func).catch(console.error),
Promise.resolve()
)
await client.query('TRUNCATE TABLE pgcodebase_dropcodes RESTART IDENTITY')
}
if (config.dropOnly) {
return;
}
const filePaths = await recursiveReadDir(config.dir);
const entities = await Promise.all(filePaths.map(async (filePath) => {
const file = await fs.readFile(filePath, 'utf-8')
return { ...parseComments(file), filePath, file }
}))
const entitiesByFilePath = entities.reduce(
(accumulator, entity) => ({ ...accumulator, [entity.filePath]: entity }),
{}
)
const adjacencyLists = {}
entities.forEach(entity => {
if (!adjacencyLists[entity.filePath]) {
adjacencyLists[entity.filePath] = []
}
entity.require.forEach(relativePath => {
const configRelativePath = path.join(config.dir, relativePath)
let lstat;
try {
lstat = fs.lstatSync(path.resolve(process.cwd(), configRelativePath))
} catch (err) {
throw new Error(`Required file/folder "${relativePath}" not found`);
}
const matchingPathes = lstat.isDirectory() ?
entities.filter(e => e.filePath.includes(configRelativePath)).map(x => x.filePath)
: [configRelativePath]
matchingPathes.forEach(matchingPath => {
adjacencyLists[entity.filePath].push(matchingPath);
})
})
})
while (Object.keys(adjacencyLists).length !== 0) {
let key = Object.keys(adjacencyLists)[0]
const visited = [key]
if (!adjacencyLists[key]) {
throw new Error(`Required file "${key}" not found`);
}
while (adjacencyLists[key].length !== 0) {
key = adjacencyLists[key][0]
if (!adjacencyLists[key]) {
throw new Error(`Required file "${key}" not found`);
}
if (visited.indexOf(key) > -1) {
throw new Error(`Cyclic dependency for file: ${key}`)
}
visited.push(key)
}
console.log(key)
await client.query(entitiesByFilePath[key].file)
await client.query('INSERT INTO pgcodebase_dropcodes (dropcode) VALUES ($1)', [entitiesByFilePath[key].dropCode])
removeNode(adjacencyLists, key)
}
}
async function recreateEntities(config) {
let client;
let usingExternalConnection = false;
try {
if (config.client) {
client = config.client
usingExternalConnection = true;
} else {
client = new Client({
user: config.user,
host: config.host,
password: config.password,
database: config.database,
port: config.port,
connectionString: config.connectionString
})
await client.connect()
await client.query('START TRANSACTION')
console.log('START TRANSACTION')
}
await syncFiles(client, config)
if (!usingExternalConnection) {
await client.query('COMMIT')
console.log('COMMIT')
}
} catch (e) {
if (!usingExternalConnection) {
await client.query('ROLLBACK')
console.log('ROLLBACK')
}
throw e;
} finally {
if (!usingExternalConnection) {
await client.end()
}
}
}
module.exports = recreateEntities