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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
|
package main
import (
"database/sql"
)
// Busy timeouts. Readers should fail fast: in WAL mode a reader never
// contends with the writer, so a read blocking this long means something is
// wrong. The ingester must instead wait out whatever holds the write lock.
const (
readBusyTimeout = 5000
writeBusyTimeout = 30000
)
// mapPlace is a plottable place as handed to the browser. Fields are short
// because this struct is serialised ~20k times into the page payload; the
// names are the JSON wire format, not documentation.
type mapPlace struct {
Q string `json:"q"`
N string `json:"n"` // name
C string `json:"c,omitempty"` // country label
Lat float64 `json:"y"`
Lon float64 `json:"x"`
Pop int64 `json:"p,omitempty"`
}
// edge is a drawable twinning: two indices into the places slice, plus the
// year it began (0 when unrecorded) and the year it ended (0 when it did
// not). Years rather than full dates because that is all the client uses —
// filtering by decade and colouring by age — and it keeps the payload small.
type edge struct {
A, B int32
Start int16
End int16
}
// loadMap returns every plottable place plus the twinning edges between them,
// as index pairs into the returned slice.
//
// The whole dataset ships to the client in one payload (~1.5 MB of JSON,
// gzipped to a few hundred KB). That is deliberate: hovering must feel
// instant, and a round-trip per hover over 20k dots would not. It also means
// the server does no per-request work at all beyond serving a cached blob.
//
// Edges are emitted as indices rather than QIDs because "12345,678" is a
// third the size of "Q12345","Q678" and the client wants an index anyway.
func loadMap(db *sql.DB) ([]mapPlace, []edge, error) {
// Ordering by qid is not required, but it makes the payload byte-identical
// between calls on unchanged data, which lets the ETag actually match.
rows, err := db.Query(`
SELECT qid, label, COALESCE(country_label, ''), lat, lon, COALESCE(pop, 0)
FROM place
WHERE lat IS NOT NULL AND lon IS NOT NULL
ORDER BY qid`)
if err != nil {
return nil, nil, err
}
defer rows.Close()
var places []mapPlace
index := make(map[string]int32)
for rows.Next() {
var p mapPlace
if err := rows.Scan(&p.Q, &p.N, &p.C, &p.Lat, &p.Lon, &p.Pop); err != nil {
return nil, nil, err
}
index[p.Q] = int32(len(places))
places = append(places, p)
}
if err := rows.Err(); err != nil {
return nil, nil, err
}
// Only edges whose *both* endpoints are plottable can be drawn. The
// others still exist in the DB and are surfaced on the place page, which
// can name a twin it cannot place on the map.
// substr(…,1,4) rather than a date function: the stored value is either a
// full ISO date or a bare year (when Wikidata recorded month/day as 00),
// and the leading four characters are the year in both cases.
erows, err := db.Query(`
SELECT t.a, t.b,
COALESCE(CAST(substr(t.started, 1, 4) AS INTEGER), 0),
COALESCE(CAST(substr(t.ended, 1, 4) AS INTEGER), 0)
FROM twin t
JOIN place pa ON pa.qid = t.a
JOIN place pb ON pb.qid = t.b
WHERE pa.lat IS NOT NULL AND pb.lat IS NOT NULL
ORDER BY t.a, t.b`)
if err != nil {
return nil, nil, err
}
defer erows.Close()
var edges []edge
for erows.Next() {
var a, b string
var start, end int
if err := erows.Scan(&a, &b, &start, &end); err != nil {
return nil, nil, err
}
ia, oka := index[a]
ib, okb := index[b]
if !oka || !okb {
continue
}
edges = append(edges, edge{ia, ib, int16(start), int16(end)})
}
return places, edges, erows.Err()
}
// twinRow is one twin of a place, for the server-rendered place page.
type twinRow struct {
QID string
Label string
Country string
HasCoord bool
// Started/Ended are the raw stored values: either a full ISO date, a bare
// year, or empty when Wikidata does not record one. Empty is the common
// case — most twinnings are undated.
Started string
Ended string
}
// twinsOf lists every twin of a place. The UNION is what re-expands the
// normalised (a<b) storage back into both directions: a place can appear on
// either side of the stored pair, and callers want "its twins" regardless.
func twinsOf(db *sql.DB, q string) ([]twinRow, error) {
// The dates live on the twin row, not the place, so they are carried out
// of the UNION alongside the other endpoint. UNION ALL rather than UNION:
// a pair is stored once, so the two arms are disjoint by construction and
// deduplicating would only cost a sort.
//
// Ordered by date first so a city's page reads as a chronology, with the
// undated remainder (the majority) after it.
rows, err := db.Query(`
SELECT p.qid, p.label, COALESCE(p.country_label, ''), p.lat IS NOT NULL,
COALESCE(t.started, ''), COALESCE(t.ended, '')
FROM (
SELECT b AS other, started, ended FROM twin WHERE a = ?
UNION ALL
SELECT a AS other, started, ended FROM twin WHERE b = ?
) t
JOIN place p ON p.qid = t.other
ORDER BY t.started IS NULL, t.started, p.label`, q, q)
if err != nil {
return nil, err
}
defer rows.Close()
var out []twinRow
for rows.Next() {
var t twinRow
if err := rows.Scan(&t.QID, &t.Label, &t.Country, &t.HasCoord, &t.Started, &t.Ended); err != nil {
return nil, err
}
out = append(out, t)
}
return out, rows.Err()
}
// placeByQID loads a single place, or nil when it is not in the database.
func placeByQID(db *sql.DB, q string) (*twinRow, error) {
var t twinRow
err := db.QueryRow(`
SELECT qid, label, COALESCE(country_label, ''), lat IS NOT NULL
FROM place WHERE qid = ?`, q).Scan(&t.QID, &t.Label, &t.Country, &t.HasCoord)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
return nil, err
}
return &t, nil
}
// stats are the totals shown in the page footer.
type stats struct {
Places int
Plottable int
Pairs int
Dated int
Ended int
FirstYear int
LastYear int
IngestedAt string
}
func loadStats(db *sql.DB) (stats, error) {
var s stats
if err := db.QueryRow(`SELECT COUNT(*), COUNT(lat) FROM place`).Scan(&s.Places, &s.Plottable); err != nil {
return s, err
}
if err := db.QueryRow(
`SELECT COUNT(*), COUNT(started), COUNT(ended) FROM twin`,
).Scan(&s.Pairs, &s.Dated, &s.Ended); err != nil {
return s, err
}
// NULL on a database with no dated pairs, hence the COALESCE.
if err := db.QueryRow(`
SELECT COALESCE(MIN(CAST(substr(started,1,4) AS INTEGER)), 0),
COALESCE(MAX(CAST(substr(started,1,4) AS INTEGER)), 0)
FROM twin WHERE started IS NOT NULL`).Scan(&s.FirstYear, &s.LastYear); err != nil {
return s, err
}
// Absent on a database that has never been ingested; not an error.
_ = db.QueryRow(`SELECT value FROM meta WHERE key = 'ingested_at'`).Scan(&s.IngestedAt)
return s, nil
}
|