This repository has been archived by the owner on Dec 1, 2019. It is now read-only.
/
spatialite.go
291 lines (245 loc) · 9.45 KB
/
spatialite.go
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package gtfsconv
import (
"fmt"
"database/sql"
)
// buildSpatialite enables Spatialite SQLite extension,
// and creates additional spatial-enhanced tables.
func buildSpatialite(db *sql.DB) error {
// sanity check that spatialite is loaded
if hasDBSpatialite(db) == false {
return fmt.Errorf("spatialite is not loaded")
}
// check for spatialite metadata tables
if hasDBTable(db, "geometry_columns") == false ||
hasDBTable(db, "spatial_ref_sys") == false {
if _, initErr := db.Exec(
// drop existing meta tables (for safety)
"drop table if exists geometry_columns;" +
"drop table if exists spatial_ref_sys;" +
// initialize spatialite metadata
"select InitSpatialMetaData();");
initErr != nil {
return fmt.Errorf(
"failed to call `InitSpatialMetaData()` [%s]", initErr)
}
}
if stopsErr := buildSpatialStops(db); stopsErr != nil {
return fmt.Errorf("buildSpatialStops() %s", stopsErr)
}
if hasDBTable(db, "shapes") { // only build, if "shapes" table exists
if shapesErr := buildSpatialShapes(db); shapesErr != nil {
return fmt.Errorf("buildSpatialShapes() %s", shapesErr)
}
if routesErr := buildSpatialRoutes(db); routesErr != nil {
return fmt.Errorf("buildSpatialRoutes() %s", routesErr)
}
}
return nil
}
// buildSpatialStops Helper: Build "stops_geo" spatialite table.
func buildSpatialStops(db *sql.DB) error {
// count current number of stops, for sanity checking,
numStops, nsErr := countDBTable(db, "*", "stops")
if nsErr != nil {
return fmt.Errorf("countDBTable() %s", nsErr)
}
// if "stops_geo" already exists
if hasDBTable(db, "stops_geo") {
// count current number of shapes_geo
numGeo, ngErr := countDBTable(db, "*", "stops_geo")
switch {
case ngErr != nil: return fmt.Errorf("countDBTable() %s", ngErr)
case numGeo == numStops: return nil // if complete table, do nothin
}
// otherwise, drop for rebuilding
if _, dgErr := db.Exec(
"select DiscardGeometryColumn('stops_geo', 'geom'); " +
"drop table stops_geo;"); dgErr != nil {
return fmt.Errorf("failed to drop prev stops_geo table [%s]", dgErr)
}
}
// create new "stops_geo" table
// with spatialite geometry column
if _, cErr := db.Exec(
"create table stops_geo (stop_id text);" +
"select AddGeometryColumn('stops_geo', 'geom', 4326, 'POINT');");
cErr != nil {
return fmt.Errorf("failed to create table `stops_geo` [%s]", cErr)
}
// process each existing "stops.stop_id" into "stops_geo"
if _, iErr := db.Exec("insert into stops_geo (stop_id, geom) " +
"select stop_id, geomfromtext(" +
"'POINT('||stop_lon||' '||stop_lat||')'" +
", 4326) from stops;");
iErr != nil {
return fmt.Errorf("failed to insert rows into `stops_geo` [%s]", iErr)
}
// add unique index
if _, ciErr := db.Exec(
"create unique index stopgeo_idx on stops_geo (stop_id);"); ciErr != nil {
return fmt.Errorf("failed add index(es) to stops_geo [%s]", ciErr)
}
// count "stops_geo" for final sanity check
numGeo, ngErr := countDBTable(db, "*", "stops_geo")
switch {
case ngErr != nil: return fmt.Errorf("countDBTable() %s", ngErr)
case numGeo != numStops: return fmt.Errorf(
"failed to sanity check stops_geo rows: %v expected, %v actual",
numStops, numGeo)
}
return nil
}
// buildSpatialShapes Helper: Build "shapes_geo" spatialite table.
// note: "shapes" table must exist in db!
func buildSpatialShapes(db *sql.DB) error {
// count current number of shapes, for sanity checking,
numShapes, nsErr := countDBTable(db, "distinct(shape_id)", "shapes")
if nsErr != nil {
return fmt.Errorf("countDBTable() %s", nsErr)
}
// if "shapes_geo" already exists
if hasDBTable(db, "shapes_geo") {
// count current number of shapes_geo
numGeo, ngErr := countDBTable(db, "*", "shapes_geo")
switch {
case ngErr != nil: return fmt.Errorf("countDBTable() %s", ngErr)
case numGeo == numShapes: return nil // if complete table, do nothing
}
// otherwise, drop for rebuilding
if _, dgErr := db.Exec(
"select DiscardGeometryColumn('shapes_geo', 'geom'); " +
"drop table shapes_geo;"); dgErr != nil {
return fmt.Errorf("failed to drop prev shapes_geo table [%s]", dgErr)
}
}
// create new "shapes_geo" table
// with spatialite geometry column
if _, cErr := db.Exec(
"create table shapes_geo (shape_id text);" +
"select AddGeometryColumn('shapes_geo', 'geom', 4326, 'LINESTRING');");
cErr != nil {
return fmt.Errorf("failed to create table `shapes_geo` [%s]", cErr)
}
// process each existing "shapes.shape_id" into "shapes_geo"
if _, iErr := db.Exec("insert into shapes_geo " +
"select shape_id, geomfromtext(" +
"'LINESTRING(' || " +
"group_concat(shape_pt_lon || ' ' || shape_pt_lat) " +
" || ')', " +
"4326) as geom " +
"from shapes group by shape_id;");
iErr != nil {
return fmt.Errorf("failed to insert rows into `shapes_geo` [%s]", iErr)
}
// add unique index
if _, ciErr := db.Exec(
"create unique index shapegeo_idx on shapes_geo (shape_id);");
ciErr != nil {
return fmt.Errorf("failed add index(es) to shapes_geo [%s]", ciErr)
}
// count "shapes_geo" for final sanity check
numGeo, ngErr := countDBTable(db, "*", "shapes_geo")
switch {
case ngErr != nil: return fmt.Errorf("countDBTable() %s", ngErr)
case numGeo != numShapes: return fmt.Errorf(
"failed to sanity check shapes_geo rows: %v expected, %v actual",
numShapes, numGeo)
}
return nil
}
// buildSpatialRoutes Helper: Build "routes_geo" spatialite table.
// note: "shapes" table must exist in db!
func buildSpatialRoutes(db *sql.DB) error {
// count current number of routes, for sanity checking,
numRoutes, nsErr := countDBTable(db,
"distinct(route_id||direction_id)", "trips")
if nsErr != nil {
return fmt.Errorf("countDBTable() %s", nsErr)
}
// if "routes_geo" already exists
if hasDBTable(db, "routes_geo") {
// count current number of routes_geo
numGeo, ngErr := countDBTable(db, "*", "routes_geo")
switch {
case ngErr != nil: return fmt.Errorf("countDBTable() %s", ngErr)
case numGeo == numRoutes: return nil // if complete table, do nothing
}
// otherwise, drop for rebuilding
if _, dgErr := db.Exec(`
select DiscardGeometryColumn('routes_geo', 'geom'),
DiscardGeometryColumn('routes_geo', 'stopgeom'),
DiscardGeometryColumn('routes_geo', 'pathgeom');
drop table routes_geo;`); dgErr != nil {
return fmt.Errorf("failed to drop prev routes_geo table [%s]", dgErr)
}
}
// create new "routes_geo" table
// with spatialite geometry column
if _, cErr := db.Exec(`
create table routes_geo (route_id text, direction_id text);
select AddGeometryColumn('routes_geo', 'geom', 4326, 'MULTILINESTRING'),
AddGeometryColumn('routes_geo', 'stopgeom', 4326, 'MULTIPOINT'),
AddGeometryColumn('routes_geo', 'pathgeom', 4326, 'MULTILINESTRING');`);
cErr != nil {
return fmt.Errorf("failed to create table `routes_geo` [%s]", cErr)
}
// select all distinct route:direction
rts, rErr := db.Query("select distinct route_id, direction_id from trips;")
if rErr != nil {
return fmt.Errorf("failed to query distinct trips [%s]", rErr)
}
var routes [][2]string
var rid, did string
for rts.Next() {
if sErr := rts.Scan(&rid, &did); sErr != nil {
return fmt.Errorf("failed to scan routes [%s]", sErr)
}
routes = append(routes, [2]string{rid, did})
}
rts.Close()
for _, rt := range routes {
rid = rt[0]
did = rt[1]
// generate and insert new routes_geo rows
if _, irErr := db.Exec(fmt.Sprintf(`
insert into routes_geo
(route_id, direction_id, geom, stopgeom, pathgeom)
select
'%s', '%s',
castToMulti(SHAPES.geom),
castToMulti(STOPS.geom),
castToMulti(st_linescutatnodes(
st_linemerge(snap(SHAPES.geom, STOPS.geom, 0.0005)), STOPS.geom))
from
(select linemerge(st_union(ts.geom)) as geom from
(select distinct(t.shape_id), sg.geom as geom
from trips t left join shapes_geo sg on t.shape_id = sg.shape_id
where t.route_id = '%s' and t.direction_id = '%s') ts) SHAPES
left join
(select st_union(ts.geom) as geom from
(select distinct(sg.stop_id), sg.geom as geom
from trips t
left join stop_times st on t.trip_id = st.trip_id
left join stops_geo sg on st.stop_id = sg.stop_id
where t.route_id = '%s' and t.direction_id = '%s') ts) STOPS
on 1=1;`, rid, did, rid, did, rid, did)); irErr != nil {
return fmt.Errorf("failed to generate new row [%s]", irErr)
}
}
// add unique index
if _, ciErr := db.Exec(`
create index routegeo_idx on routes_geo (route_id);
create unique index routegeo_dir_idx on routes_geo (route_id, direction_id);`); ciErr != nil {
return fmt.Errorf("failed add index(es) to routes_geo [%s]", ciErr)
}
// count "routes_geo" for final sanity check
numGeo, ngErr := countDBTable(db, "*", "routes_geo")
switch {
case ngErr != nil: return fmt.Errorf("countDBTable() %s", ngErr)
case numGeo != numRoutes: return fmt.Errorf(
"failed to sanity check routes_geo rows: %v expected, %v actual",
numRoutes, numGeo)
}
return nil
}