-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathconfig.go
More file actions
424 lines (374 loc) · 11 KB
/
config.go
File metadata and controls
424 lines (374 loc) · 11 KB
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
package pgpush
import (
"errors"
"fmt"
"github.com/jackc/pgx"
_ "github.com/lib/pq"
"github.com/paulmach/go.geojson"
"reflect"
"strconv"
"strings"
)
var DefaultIncrement = 1000
var DefaultSRID = 4326
var WebMercatorSRID = 3857
type ColumnType string
// int types
var SmallInt ColumnType = "smallint" // int
var Integer ColumnType = "integer" // int
var BigInt ColumnType = "bigint" // int
// float types
var Decimal ColumnType = "decimal" // float
var Numeric ColumnType = "numeric" // float
var Real ColumnType = "real" // float
//var Double ColumnType = "double" // float
// serial types
var SmallSerial ColumnType = "smallserial" // int
var Serial ColumnType = "serial" // int
var BigSerial ColumnType = "bigserial" // int
// character types
var VarChar ColumnType = "varchar" // string
var Char ColumnType = "Char" // string
var Text ColumnType = "text" // string
// Binary Data Types
var Bytea ColumnType = "bytea" // string
// timestamps & timezones
var TimestampWithoutTimezone ColumnType = "timestamp without timezone" // int
var TimestampWithTimezone ColumnType = "timestamp with timezone" // int
var Date ColumnType = "date" // int
var TimeWithoutTimezone ColumnType = "time without timezone" // int
var TimeWithTimezone ColumnType = "time with timezone" // int
var Interval ColumnType = "interval" // int
// boolean type
var Boolean ColumnType = "boolean" // bool
// geometry data types
var Geometry ColumnType = "geometry" // geometry
// hstore column type
var HStore ColumnType = "hstore_tags"
var TypeMap = map[ColumnType]string{
SmallInt: "int",
Integer: "int",
BigInt: "int",
Decimal: "float",
Numeric: "float",
Real: "float",
//Double: "float",
SmallSerial: "int",
Serial: "int",
BigSerial: "int",
VarChar: "string",
Char: "string",
Text: "string",
Bytea: "string",
TimestampWithoutTimezone: "int",
TimestampWithTimezone: "int",
Date: "int",
TimeWithoutTimezone: "int",
TimeWithTimezone: "int",
Interval: "int",
Boolean: "bool",
Geometry: "geometry",
HStore: "hstore",
}
// column data type
type Column struct {
Name string
Type ColumnType
TargetSRID int
GivenSRID int
}
// table structrue
type Table struct {
TableName string
InsertStmt string
CreateStmt string
CurrentInsertStmt string
InsertValue string
CurrentInterfaceList []interface{}
Count int
ColumnMap map[string]string
Tx *pgx.Tx
Columns []Column
Inserts int
HStoreFormatString string
HStoreColumns []string
Conn *pgx.ConnPool
}
// Creates a table structure to map to.
func CreateTable(tablename string, columns []Column, config pgx.ConnPoolConfig) (*Table, error) {
columnmap := map[string]string{}
createlist, insertlist := []string{}, []string{}
var hstore_bool bool
for _, column := range columns {
mytype := TypeMap[column.Type]
if mytype == "hstore" {
hstore_bool = true
}
}
hstore_lines := []string{}
hstore_columns := []string{}
//pos := 0
new_columns := []Column{}
column_names := []string{}
for _, column := range columns {
var hstore_val bool
mytype := TypeMap[column.Type]
val := fmt.Sprintf("%s %s", column.Name, string(column.Type))
if hstore_bool && mytype == "string" {
columnmap[column.Name] = mytype
hstore_lines = append(hstore_lines, fmt.Sprintf(`"%s" `, column.Name)+`=> "%s",`)
hstore_columns = append(hstore_columns, column.Name)
hstore_val = true
} else if strings.Contains(mytype, "hstore") {
insertlist = append(insertlist, "$%d")
//pos++
column_names = append(column_names, column.Name)
new_columns = append(new_columns, column)
val = fmt.Sprintf("%s %s", column.Name, "hstore")
} else if mytype != "geometry" {
columnmap[column.Name] = mytype
insertlist = append(insertlist, "$%d")
//pos++
new_columns = append(new_columns, column)
column_names = append(column_names, column.Name)
} else if mytype == "geometry" {
if column.GivenSRID == 0 {
column.GivenSRID = DefaultSRID
}
if column.TargetSRID == 0 {
column.TargetSRID = DefaultSRID
}
var insertval string
if column.GivenSRID != column.TargetSRID {
insertval = "ST_Transform(" + "ST_GeomFromWKB($%d," + strconv.Itoa(column.GivenSRID) + ")" + fmt.Sprintf(",%d)", column.TargetSRID)
} else {
insertval = "ST_GeomFromWKB($%d," + strconv.Itoa(column.GivenSRID) + ")"
}
//insertval := "ST_GeomFromWKB($%d," + strconv.Itoa(column.GivenSRID) + ")"
insertlist = append(insertlist, insertval)
//pos++
new_columns = append(new_columns, column)
column_names = append(column_names, column.Name)
}
if !hstore_val {
createlist = append(createlist, val)
}
}
hstore_string := ""
if hstore_bool {
val := strings.Join(hstore_lines, "\n")
val = val[:len(val)-1]
hstore_string = val
columns = new_columns
}
column_string := strings.Join(column_names, ", ")
createval := strings.Join(createlist, ",")
createstmt := fmt.Sprintf("CREATE TABLE %s (%s);", tablename, createval)
insertval := strings.Join(insertlist, ",")
insertstmt := fmt.Sprintf("INSERT INTO %s (%s) VALUES ", tablename, column_string)
insertvalupdate := fmt.Sprintf("(%s), ", insertval)
p, err := pgx.NewConnPool(config)
if err != nil {
return &Table{}, err
}
// creating extension for postgis
_, _ = p.Exec("create extension postgis;")
// creating extension for hstore
_, _ = p.Exec("create extension hstore;")
// exectuing create table stmt
_, err = p.Exec(createstmt)
if err != nil {
fmt.Println(err)
}
tx, err := p.Begin()
if err != nil {
return &Table{}, err
}
return &Table{
TableName: tablename,
InsertStmt: insertstmt,
CreateStmt: createstmt,
ColumnMap: columnmap,
Tx: tx,
Columns: columns,
Inserts: 0,
Conn: p,
InsertValue: insertvalupdate,
CurrentInsertStmt: insertstmt,
HStoreColumns: hstore_columns,
HStoreFormatString: hstore_string,
}, nil
}
// writes a value and returns the bytes of such value
// does not implement write sint currently
func ParseValue(value interface{}) (interface{}, string) {
vv := reflect.ValueOf(value)
kd := vv.Kind()
var typeval string
var myval interface{}
// switching for each type
switch kd {
case reflect.String:
typeval = "string"
myval = vv.String()
case reflect.Float32:
typeval = "float"
myval = float64(vv.Float())
case reflect.Float64:
typeval = "float"
myval = float64(vv.Float())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
typeval = "int"
myval = int(vv.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
typeval = "int"
myval = int(vv.Uint())
case reflect.Bool:
typeval = "bool"
myval = vv.Bool()
}
return myval, typeval
}
func ValidPolygonFeature(feature *geojson.Feature) bool {
// simpl
totalbool := false
totalbool = len(feature.Geometry.Polygon) == 0
if feature.Geometry.Type == "Polygon" {
for _, i := range feature.Geometry.Polygon {
boolval := len(i) < 4
if boolval {
totalbool = true
}
}
} else {
for _, i := range feature.Geometry.MultiPolygon {
for _, ii := range i {
boolval := len(ii) < 4
if boolval {
totalbool = true
}
}
}
}
return !totalbool
}
// adds a feature to the postgis table
func (table *Table) AddFeature(feature *geojson.Feature) error {
if strings.Contains(string(feature.Geometry.Type), "Polygon") {
totalbool := ValidPolygonFeature(feature)
if !totalbool {
return errors.New("Polygon Geometry Invalid.")
}
}
newlist := []interface{}{}
newlist2 := []interface{}{}
for pos, i := range table.Columns {
newlist2 = append(newlist2, table.Count*len(table.Columns)+pos+1)
if string(i.Type) == "hstore_tags" {
hstore_vals := []interface{}{}
for _, name := range table.HStoreColumns {
hstore_vals = append(hstore_vals, fmt.Sprint(feature.Properties[name]))
}
newval := fmt.Sprintf(table.HStoreFormatString, hstore_vals...)
newlist = append(newlist, newval)
} else if string(i.Name) == "geometry" {
geomb, err := EncodeGeometryWKB(feature.Geometry)
if err != nil {
return err
}
newlist = append(newlist, geomb)
} else {
val, boolval := feature.Properties[i.Name]
//fmt.Println(i, val, boolval)x
if !boolval {
newlist = append(newlist, nil)
} else {
newlist = append(newlist, fmt.Sprint(val))
}
}
}
table.CurrentInterfaceList = append(table.CurrentInterfaceList, newlist...)
table.CurrentInsertStmt += fmt.Sprintf(table.InsertValue, newlist2...)
table.Count++
//
if table.Count != DefaultIncrement {
} else {
//var oldtable *Table
//*oldtable = *table
//go func(oldtable *pgpush.Table) {
table.CurrentInsertStmt = table.CurrentInsertStmt[0 : len(table.CurrentInsertStmt)-2]
table.Tx.Exec(table.CurrentInsertStmt, table.CurrentInterfaceList...)
table.Count = 0
table.CurrentInsertStmt = table.InsertStmt
table.CurrentInterfaceList = []interface{}{}
}
return nil
}
// commits the given features and refreshes the transaction
func (table *Table) Commit() error {
if table.Count > 0 {
table.CurrentInsertStmt = table.CurrentInsertStmt[0 : len(table.CurrentInsertStmt)-2]
_, err := table.Tx.Exec(table.CurrentInsertStmt, table.CurrentInterfaceList...)
if err != nil {
fmt.Println(err)
}
table.Count = 0
table.CurrentInsertStmt = table.InsertStmt
table.CurrentInterfaceList = []interface{}{}
}
err := table.Tx.Commit()
if err != nil {
return err
}
tx, err := table.Conn.Begin()
table.Tx = tx
return err
}
// reads a given table from schema so features can be added in postgis
func ReadTable(tablename string, config pgx.ConnPoolConfig) *Table {
p, err := pgx.NewConnPool(config)
if err != nil {
return &Table{}
}
tx, err := p.Begin()
if err != nil {
return &Table{}
}
result, err := tx.Query("select column_name, data_type from INFORMATION_SCHEMA.COLUMNS where table_name = 'new';")
if err != nil {
fmt.Println(err)
}
columns := []Column{}
raw := map[string]string{}
for result.Next() {
var key, typeval string
err = result.Scan(&key, &typeval)
if err != nil {
fmt.Println(err)
}
raw[key] = typeval
columns = append(columns, Column{Name: key})
}
insertlist := []string{}
for _, column := range columns {
if column.Name != "geometry" {
insertlist = append(insertlist, "$%d")
} else if column.Name == "geometry" {
insertval := "ST_GeomFromWKB($%d,4326)"
insertlist = append(insertlist, insertval)
}
}
insertval := strings.Join(insertlist, ",")
insertstmt := fmt.Sprintf("INSERT INTO %s VALUES ", tablename)
insertvalupdate := fmt.Sprintf("(%s), ", insertval)
return &Table{
TableName: tablename,
InsertStmt: insertstmt,
Tx: tx,
Columns: columns,
Inserts: 0,
Conn: p,
InsertValue: insertvalupdate,
CurrentInsertStmt: insertstmt,
}
}