-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3-build-regexes.ts
65 lines (52 loc) · 1.94 KB
/
3-build-regexes.ts
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
import { writeFileSync } from 'fs';
import { exec } from 'child_process';
import { resolve } from 'path';
import { promisify } from 'util';
import { Client } from 'pg';
import QueryStream from 'pg-query-stream';
import tmp from 'tmp';
interface ConstituencyIdToRegex {
[constituencyId: string]: string
}
const grexLocation = resolve(__dirname, '..', '..', 'grex', 'grex');
const execPromise = promisify(exec);
(async () => {
const db = new Client({
host: 'localhost',
user: 'johnnoel',
password: 'johnnoel',
database: 'johnnoel',
port: 2502,
});
await db.connect();
const letter = process.argv[2];
const constituencies = await db.query(
'SELECT DISTINCT constituency_id AS id FROM postcodes WHERE constituency_id IS NOT NULL AND substring(postcode FROM 1 FOR 1) = $1 ORDER BY id',
[ letter ]
);
if (constituencies.rows.length === 0) {
console.log('No constituencies found for ' + letter);
process.exit(0);
return;
}
const output: ConstituencyIdToRegex = {};
for (const constituency of constituencies.rows) {
console.log(constituency.id);
const tmpFile = tmp.fileSync();
const query = db.query(
new QueryStream(
'SELECT postcode FROM postcodes WHERE constituency_id = $1 AND substring(postcode FROM 1 FOR 1) = $2 ORDER BY postcode ASC',
[ constituency.id, letter ]
)
);
for await (const row of query) {
writeFileSync(tmpFile.name, row.postcode.replace(/\s+/i, '') + "\n", { flag: 'a' });
}
const regex = await execPromise(grexLocation + ' -f ' + tmpFile.name);
output[constituency.id] = regex.stdout.trim();
}
const filename = resolve(__dirname, '..', 'public', 'data', letter + '.json');
console.log(filename);
writeFileSync(filename, JSON.stringify(output), { flag: 'w' });
process.exit(0);
})();