-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtosqlite.js
83 lines (72 loc) · 2.12 KB
/
tosqlite.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
const sqlite3 = require( 'sqlite3' ),
fs = require( 'fs' ),
rcv = require( './rcv.js' );
function formatVote( vote ) {
return ( {
undervote: '(blank)',
overvote: '(overvote)'
} )[ vote ] || vote;
}
function getDistrict( precinct ) {
if ( precinct.startsWith( 'Pct 11' ) ) {
return 11;
}
let secondDigit = Number( precinct.charAt( 'Pct N'.length ) );
return secondDigit === 0 ? 10 : secondDigit;
}
function keyById( buckets ) {
let result = {};
for ( let candidate in buckets ) {
result[candidate] = {};
for ( let ballot of buckets[candidate] ) {
result[candidate][ballot.id] = ballot;
}
}
return result;
}
if ( process.argv.length < 4 ) {
console.error( 'Usage: node tosqlite.js data.json db.sqlite3' );
return;
}
const data = JSON.parse( fs.readFileSync( process.argv[2], { encoding: 'utf8' } ) ),
db = new sqlite3.Database( process.argv[3] );
let contestData = {};
for ( let contest in data ) {
let ballots = data[contest];
for ( let id in ballots ) {
ballots[id].id = id;
}
contestData[contest] = rcv.runContest( Object.values( ballots ), true );
}
db.serialize( function () {
db.run( 'CREATE TABLE ballots(id INT, contest TEXT, first TEXT, second TEXT, third TEXT, precinct TEXT, district INT, machine INT, tallyType TEXT,' +
'round1 TEXT, round2 TEXT, round3 TEXT, round4 TEXT, round5 TEXT, round6 TEXT, round7 TEXT, round8 TEXT)' );
db.run( 'BEGIN' );
let statement = db.prepare( 'INSERT INTO ballots VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' );
for ( let contest in data ) {
let roundData = contestData[contest].map( (c) => keyById( c.buckets ) );
for ( let id in data[contest] ) {
let vote = data[contest][id], roundCandidates = [];
for ( let r = 0; r < 8; r++ ) {
for ( let candidate in roundData[r] ) {
if ( id in roundData[r][candidate] ) {
roundCandidates[r] = candidate;
break;
}
}
}
statement.run(
Number( id ),
contest,
...vote.votes.map( formatVote ),
vote.precinct,
getDistrict( vote.precinct ),
vote.machine,
vote.tallyType,
...roundCandidates
);
}
}
statement.finalize();
db.run( 'END' );
} );