forked from OSGeo/grass
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrite_pg.c
More file actions
2962 lines (2436 loc) · 90.7 KB
/
Copy pathwrite_pg.c
File metadata and controls
2962 lines (2436 loc) · 90.7 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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
\file lib/vector/Vlib/write_pg.c
\brief Vector library - write vector feature (PostGIS format)
Higher level functions for reading/writing/manipulating vectors.
Write subroutine inspired by OGR PostgreSQL driver.
\todo PostGIS version of V2__delete_area_cats_from_cidx_nat()
\todo function to delete corresponding entry in fidx
\todo PostGIS version of V2__add_area_cats_to_cidx_nat
(C) 2012-2014 by Martin Landa, and the GRASS Development Team
This program is free software under the GNU General Public License
(>=v2). Read the file COPYING that comes with GRASS for details.
\author Martin Landa <landa.martin gmail.com>
*/
#include <string.h>
#include <grass/vector.h>
#include <grass/glocale.h>
#include "local_proto.h"
#ifdef HAVE_POSTGRES
#include "pg_local_proto.h"
#define WKBSRIDFLAG 0x20000000
#define TOPOGEOM_COLUMN "topo"
/*! Use SQL statements from PostGIS Topology extension (this options
is quite slow. By default are used simple SQL statements (INSERT, UPDATE)
*/
#define USE_TOPO_STMT 0
static int create_table(struct Format_info_pg *);
static int check_schema(const struct Format_info_pg *);
static int create_topo_schema(struct Format_info_pg *, int);
static int create_pg_layer(struct Map_info *, int);
static char *get_sftype(SF_FeatureType);
static off_t write_line_sf(struct Map_info *, int,
const struct line_pnts **, int,
const struct line_cats *);
static off_t write_line_tp(struct Map_info *, int, int,
const struct line_pnts *,
const struct line_cats *);
static char *binary_to_hex(int, const unsigned char *);
static unsigned char *point_to_wkb(int, const struct line_pnts *, int, int *);
static unsigned char *linestring_to_wkb(int, const struct line_pnts *,
int, int *);
static unsigned char *polygon_to_wkb(int, const struct line_pnts **, int,
int, int *);
static char *line_to_wkb(struct Format_info_pg *, const struct line_pnts **,
int, int, int);
static int write_feature(struct Map_info *, int, int,
const struct line_pnts **, int, int);
static char *build_insert_stmt(const struct Format_info_pg *, const char *, int, int);
static int insert_topo_element(struct Map_info *, int, int, const char *);
static int type_to_topogeom(const struct Format_info_pg *);
static int update_next_edge(struct Map_info*, int, int);
static int delete_face(const struct Map_info *, int);
static int update_topo_edge(struct Map_info *, int);
static int update_topo_face(struct Map_info *, int);
static int add_line_to_topo_pg(struct Map_info *, off_t, int, const struct line_pnts *);
static int delete_line_from_topo_pg(struct Map_info *, int, int, const struct line_pnts *);
static int set_constraint_to_deferrable(struct Format_info_pg *, const char *, const char *,
const char *, const char *, const char *);
static dbDriver *open_db(struct Format_info_pg *);
#endif
static struct line_pnts *Points;
/*!
\brief Writes feature on level 1 (PostGIS interface)
Notes for simple feature access:
- centroids are not supported in PostGIS, pseudotopo holds virtual
centroids
- boundaries are not supported in PostGIS, pseudotopo treats polygons
as boundaries
Notes for PostGIS Topology access:
- centroids are stored as isolated nodes
- boundaries are stored as edges
\param Map pointer to Map_info structure
\param type feature type (GV_POINT, GV_LINE, ...)
\param points pointer to line_pnts structure (feature geometry)
\param cats pointer to line_cats structure (feature categories)
\return feature offset into file
\return -1 on error
*/
off_t V1_write_line_pg(struct Map_info *Map, int type,
const struct line_pnts *points,
const struct line_cats *cats)
{
#ifdef HAVE_POSTGRES
struct Format_info_pg *pg_info;
pg_info = &(Map->fInfo.pg);
if (pg_info->feature_type == SF_GEOMETRY) {
/* create PostGIS table if doesn't exist */
if (create_pg_layer(Map, type) < 0)
return -1;
}
if (!points)
return 0;
if (!pg_info->toposchema_name) { /* simple features access */
return write_line_sf(Map, type, &points, 1, cats);
}
/* PostGIS Topology access */
return write_line_tp(Map, type, FALSE, points, cats);
#else
G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
return -1;
#endif
}
/*!
\brief Writes feature on topological level (PostGIS interface)
Calls V2_write_line_sfa() for simple features access.
\param Map pointer to Map_info structure
\param type feature type (GV_POINT, GV_LINE, ...)
\param points pointer to line_pnts structure (feature geometry)
\param cats pointer to line_cats structure (feature categories)
\return feature offset into file
\return -1 on error
*/
off_t V2_write_line_pg(struct Map_info *Map, int type,
const struct line_pnts *points,
const struct line_cats *cats)
{
#ifdef HAVE_POSTGRES
struct Format_info_pg *pg_info;
pg_info = &(Map->fInfo.pg);
if (!pg_info->toposchema_name) { /* pseudo-topology */
return V2_write_line_sfa(Map, type, points, cats);
}
/* PostGIS Topology */
return write_line_tp(Map, type, FALSE, points, cats);
#else
G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
return -1;
#endif
}
/*!
\brief Rewrites feature at the given offset (level 1) (PostGIS interface, internal use only)
Only for simple feature access. PostGIS Topology requires level 2.
\todo Use UPDATE statement ?
\param Map pointer to Map_info structure
\param offset feature offset
\param type feature type (GV_POINT, GV_LINE, ...)
\param points feature geometry
\param cats feature categories
\return feature offset (rewritten feature)
\return -1 on error
*/
off_t V1_rewrite_line_pg(struct Map_info * Map,
off_t offset, int type,
const struct line_pnts * points,
const struct line_cats * cats)
{
G_debug(3, "V1_rewrite_line_pg(): type=%d offset=%" PRI_OFF_T,
type, offset);
#ifdef HAVE_POSTGRES
if (type != V1_read_line_pg(Map, NULL, NULL, offset)) {
G_warning(_("Unable to rewrite feature (incompatible feature types)"));
return -1;
}
/* delete old */
V1_delete_line_pg(Map, offset);
return V1_write_line_pg(Map, type, points, cats);
#else
G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
return -1;
#endif
}
/*!
\brief Rewrites feature at topological level (PostGIS interface, internal use only)
Note: Topology must be built at level >= GV_BUILD_BASE
\todo Handle also categories
\todo Store original geometry in tmp table for restore
\param Map pointer to Map_info structure
\param line feature id
\param type feature type (GV_POINT, GV_LINE, ...)
\param points feature geometry
\param cats feature categories
\return offset where feature was rewritten
\return -1 on error
*/
off_t V2_rewrite_line_pg(struct Map_info *Map, off_t line, int type,
const struct line_pnts *points, const struct line_cats *cats)
{
G_debug(3, "V2_rewrite_line_pg(): line=%d type=%d",
(int)line, type);
#ifdef HAVE_POSTGRES
const char *schema_name, *table_name, *keycolumn;
char *stmt, *geom_data;
struct Format_info_pg *pg_info;
struct P_line *Line;
off_t offset;
geom_data = NULL;
stmt = NULL;
pg_info = &(Map->fInfo.pg);
if (line < 1 || line > Map->plus.n_lines) {
G_warning(_("Attempt to access feature with invalid id (%d)"), (int)line);
return -1;
}
Line = Map->plus.Line[line];
if (Line == NULL) {
G_warning(_("Attempt to access dead feature %d"), (int)line);
return -1;
}
offset = Line->offset;
if (!(Map->plus.update_cidx)) {
Map->plus.cidx_up_to_date = FALSE; /* category index will be outdated */
}
if (!Points)
Points = Vect_new_line_struct();
if (type != V2_read_line_pg(Map, Points, NULL, line)) {
G_warning(_("Unable to rewrite feature (incompatible feature types)"));
return -1;
}
/* remove line from topology */
if (0 != delete_line_from_topo_pg(Map, line, type, Points))
return -1;
if (pg_info->toposchema_name) { /* PostGIS Topology */
schema_name = pg_info->toposchema_name;
if (type & GV_POINTS) {
table_name = keycolumn = "node";
}
else {
table_name = "edge_data";
keycolumn = "edge";
}
}
else { /* simple features access */
schema_name = pg_info->schema_name;
table_name = pg_info->table_name;
keycolumn = pg_info->fid_column;
}
geom_data = line_to_wkb(pg_info, &points, 1, type, Map->head.with_z);
G_asprintf(&stmt, "UPDATE \"%s\".\"%s\" SET geom = '%s'::GEOMETRY WHERE %s_id = %" PRI_OFF_T,
schema_name, table_name, geom_data, keycolumn, line);
G_free(geom_data);
if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
G_warning(_("Unable to rewrite feature %d"), (int)line);
Vect__execute_pg(pg_info->conn, "ROLLBACK");
return -1;
}
/* update topology
note: offset is not changed */
return add_line_to_topo_pg(Map, offset, type, points);
#else
G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
return -1;
#endif
}
/*!
\brief Deletes feature at the given offset (level 1)
Only for simple feature access. PostGIS Topology requires level 2.
\param Map pointer Map_info structure
\param offset feature offset
\return 0 on success
\return -1 on error
*/
int V1_delete_line_pg(struct Map_info *Map, off_t offset)
{
#ifdef HAVE_POSTGRES
long fid;
char stmt[DB_SQL_MAX];
struct Format_info_pg *pg_info;
pg_info = &(Map->fInfo.pg);
if (!pg_info->conn || !pg_info->table_name) {
G_warning(_("No connection defined"));
return -1;
}
if (offset >= pg_info->offset.array_num) {
G_warning(_("Invalid offset (%" PRI_OFF_T ")"), offset);
return -1;
}
fid = pg_info->offset.array[offset];
G_debug(3, "V1_delete_line_pg(): offset = %lu -> fid = %ld",
(unsigned long)offset, fid);
if (!pg_info->inTransaction) {
/* start transaction */
pg_info->inTransaction = TRUE;
if (Vect__execute_pg(pg_info->conn, "BEGIN") == -1)
return -1;
}
sprintf(stmt, "DELETE FROM %s WHERE %s = %ld",
pg_info->table_name, pg_info->fid_column, fid);
G_debug(3, "SQL: %s", stmt);
if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
G_warning(_("Unable to delete feature"));
Vect__execute_pg(pg_info->conn, "ROLLBACK");
return -1;
}
return 0;
#else
G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
return -1;
#endif
}
/*!
\brief Deletes feature on topological level (PostGIS interface)
Note: Topology must be built at level >= GV_BUILD_BASE
Calls V2_delete_line_sfa() for simple feature access.
\param Map pointer to Map_info structure
\param line feature id to be deleted
\return 0 on success
\return -1 on error
*/
int V2_delete_line_pg(struct Map_info *Map, off_t line)
{
#ifdef HAVE_POSTGRES
int ret;
struct Format_info_pg *pg_info;
pg_info = &(Map->fInfo.pg);
if (line < 1 || line > Map->plus.n_lines) {
G_warning(_("Attempt to access feature with invalid id (%d)"), (int)line);
return -1;
}
if (!pg_info->toposchema_name) { /* pseudo-topology */
return V2_delete_line_sfa(Map, line);
}
else { /* PostGIS topology */
int type;
char stmt[DB_SQL_MAX];
const char *table_name, *keycolumn;
struct P_line *Line;
if (line < 1 || line > Map->plus.n_lines) {
G_warning(_("Attempt to access feature with invalid id (%d)"), (int)line);
return -1;
}
Line = Map->plus.Line[line];
if (!Line) {
G_warning(_("Attempt to access dead feature %d"), (int)line);
return -1;
}
if (!(Map->plus.update_cidx)) {
Map->plus.cidx_up_to_date = FALSE; /* category index will be outdated */
}
Vect__execute_pg(pg_info->conn, "BEGIN");
if (Line->type & GV_POINTS) {
table_name = keycolumn = "node";
}
else {
table_name = "edge_data";
keycolumn = "edge";
/* first remove references to this edge */
/* (1) left next edge */
sprintf(stmt, "UPDATE \"%s\".\"%s\" SET abs_next_left_edge = edge_id, "
"next_left_edge = -edge_id WHERE abs_next_left_edge = %d",
pg_info->toposchema_name, table_name, (int)Line->offset);
if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
Vect__execute_pg(pg_info->conn, "ROLLBACK");
return -1;
}
/* (2) right next edge */
sprintf(stmt, "UPDATE \"%s\".\"%s\" SET abs_next_right_edge = edge_id, "
"next_right_edge = edge_id WHERE abs_next_right_edge = %d",
pg_info->toposchema_name, table_name, (int)Line->offset);
if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
Vect__execute_pg(pg_info->conn, "ROLLBACK");
return -1;
}
}
/* read the line */
if (!Points)
Points = Vect_new_line_struct();
type = V2_read_line_pg(Map, Points, NULL, line);
if (type < 0)
return -1;
/* delete record from topology table */
sprintf(stmt, "DELETE FROM \"%s\".\"%s\" WHERE %s_id = %d",
pg_info->toposchema_name, table_name, keycolumn, (int)Line->offset);
if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
G_warning(_("Unable to delete feature (%s) %d"), keycolumn,
(int)line);
Vect__execute_pg(pg_info->conn, "ROLLBACK");
return -1;
}
if (pg_info->cache.ctype == CACHE_MAP) {
/* delete from cache */
Vect_destroy_line_struct(pg_info->cache.lines[line-1]);
pg_info->cache.lines[line-1] = NULL;
pg_info->cache.lines_types[line-1] = 0;
pg_info->cache.lines_cats[line-1] = 0;
}
/* update topology */
ret = delete_line_from_topo_pg(Map, line, type, Points);
if (ret == 0)
Vect__execute_pg(pg_info->conn, "COMMIT");
return ret;
}
#else
G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
return -1;
#endif
}
#ifdef HAVE_POSTGRES
/*!
\brief Writes node on topological level (PostGIS Topology
interface, internal use only)
The vector map must be open on level 2 at least with
GV_BUILD_BASE. PostGIS Topology schema must be defined.
\param Map pointer to Map_info structure
\param node node id (starts at 1)
\param points pointer to line_pnts structure
\return 0 on success
\return -1 on error
*/
off_t V2__write_node_pg(struct Map_info *Map, const struct line_pnts *points)
{
struct Format_info_pg *pg_info;
pg_info = &(Map->fInfo.pg);
if (!pg_info->toposchema_name)
return -1; /* PostGIS Topology required */
return write_line_tp(Map, GV_POINT, TRUE, points, NULL);
}
/*!
\brief Writes area on topological level (PostGIS Simple Features
interface, internal use only)
\param Map pointer to Map_info structure
\param points feature geometry (exterior + interior rings)
\param nparts number of parts including exterior ring
\param cats feature categories
\return feature offset
\return -1 on error
*/
off_t V2__write_area_pg(struct Map_info *Map,
const struct line_pnts **points, int nparts,
const struct line_cats *cats)
{
return write_line_sf(Map, GV_BOUNDARY, points, nparts, cats);
}
/*!
\brief Updates simple features geometry from GRASS-like topo
\param Map pointer to Map_info structure
\param points feature geometry (exterior + interior rings)
\param nparts number of parts including exterior ring
\param cat area category
\return 0 on success
\return -1 on error
*/
int V2__update_area_pg(struct Map_info *Map,
const struct line_pnts **points, int nparts,
int cat)
{
int part, npoints;
char *stmt, *geom_data;
struct Format_info_pg *pg_info;
pg_info = &(Map->fInfo.pg);
for (part = 0; part < nparts; part++) {
npoints = points[part]->n_points - 1;
if (points[part]->x[0] != points[part]->x[npoints] ||
points[part]->y[0] != points[part]->y[npoints] ||
points[part]->z[0] != points[part]->z[npoints]) {
G_warning(_("Boundary is not closed. Skipping."));
return -1;
}
}
geom_data = line_to_wkb(pg_info, points, nparts, GV_AREA, Vect_is_3d(Map));
if (!geom_data)
return -1;
stmt = NULL;
G_asprintf(&stmt, "UPDATE \"%s\".\"%s\" SET %s = '%s'::GEOMETRY WHERE %s = %d",
pg_info->schema_name, pg_info->table_name, pg_info->geom_column,
geom_data, pg_info->fid_column,
cat);
if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
/* rollback transaction */
Vect__execute_pg(pg_info->conn, "ROLLBACK");
G_free(geom_data);
G_free(stmt);
return -1;
}
G_free(geom_data);
G_free(stmt);
return 0;
}
/*!
\brief Create new feature table
\param pg_info pointer to Format_info_pg
\return -1 on error
\return 0 on success
*/
int create_table(struct Format_info_pg *pg_info)
{
int spatial_index, primary_key;
char stmt[DB_SQL_MAX];
char *geom_type, *def_file;
struct field_info *Fi;
PGresult *result;
def_file = getenv("GRASS_VECTOR_PGFILE");
/* by default create spatial index & add primary key */
spatial_index = primary_key = TRUE;
if (G_find_file2("", def_file ? def_file : "PG", G_mapset())) {
FILE *fp;
const char *p;
struct Key_Value *key_val;
fp = G_fopen_old("", def_file ? def_file : "PG", G_mapset());
if (!fp) {
G_warning(_("Unable to open PG file"));
}
else {
key_val = G_fread_key_value(fp);
fclose(fp);
/* disable spatial index ? */
p = G_find_key_value("spatial_index", key_val);
if (p && G_strcasecmp(p, "no") == 0)
spatial_index = FALSE;
/* disable primary key ? */
p = G_find_key_value("primary_key", key_val);
if (p && G_strcasecmp(p, "no") == 0)
primary_key = FALSE;
G_free_key_value(key_val);
}
}
/* create schema if not exists */
if (G_strcasecmp(pg_info->schema_name, "public") != 0) {
if (check_schema(pg_info) != 0)
return -1;
}
/* prepare CREATE TABLE statement */
sprintf(stmt, "CREATE TABLE \"%s\".\"%s\" (%s SERIAL%s, %s INTEGER",
pg_info->schema_name, pg_info->table_name, pg_info->fid_column,
primary_key ? " PRIMARY KEY" : "", GV_KEY_COLUMN);
Fi = pg_info->fi;
if (Fi) {
/* append attributes */
int col, ncols, sqltype, length;
char stmt_col[DB_SQL_MAX];
const char *colname;
dbString dbtable_name;
dbDriver *driver;
dbTable *table;
dbColumn *column;
db_init_string(&dbtable_name);
driver = open_db(pg_info);
if (driver == NULL)
return -1;
/* describe table */
db_set_string(&dbtable_name, Fi->table);
if (db_describe_table(driver, &dbtable_name, &table) != DB_OK) {
G_warning(_("Unable to describe table <%s>"),
Fi->table);
db_close_database_shutdown_driver(driver);
pg_info->dbdriver = NULL;
return -1;
}
ncols = db_get_table_number_of_columns(table);
G_debug(3,
"copying attributes: driver = %s database = %s table = %s cols = %d",
Fi->driver, Fi->database, Fi->table, ncols);
for (col = 0; col < ncols; col++) {
column = db_get_table_column(table, col);
colname = db_get_column_name(column);
sqltype = db_get_column_sqltype(column);
length = db_get_column_length(column);
G_debug(3, "\tcolumn = %d name = %s type = %d length = %d",
col, colname, sqltype, length);
if (G_strcasecmp(pg_info->fid_column, colname) == 0 ||
G_strcasecmp(GV_KEY_COLUMN, colname) == 0) {
/* skip fid column if exists */
G_debug(3, "\t%s skipped", colname);
continue;
}
/* append column */
sprintf(stmt_col, ",\"%s\" %s", colname, db_sqltype_name(sqltype));
strcat(stmt, stmt_col);
if (sqltype == DB_SQL_TYPE_CHARACTER) {
/* length only for string columns */
sprintf(stmt_col, "(%d)", length);
strcat(stmt, stmt_col);
}
}
db_free_string(&dbtable_name);
}
strcat(stmt, ")"); /* close CREATE TABLE statement */
/* begin transaction (create table) */
if (Vect__execute_pg(pg_info->conn, "BEGIN") == -1) {
return -1;
}
/* create table */
if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
Vect__execute_pg(pg_info->conn, "ROLLBACK");
return -1;
}
/* determine geometry type (string) */
switch (pg_info->feature_type) {
case (SF_POINT):
geom_type = "POINT";
break;
case (SF_LINESTRING):
geom_type = "LINESTRING";
break;
case (SF_POLYGON):
geom_type = "POLYGON";
break;
case (SF_POLYGON25D):
geom_type = "POLYGONZ";
break;
case (SF_GEOMETRY):
geom_type = "GEOMETRY";
break;
default:
G_warning(_("Unsupported feature type %d"), pg_info->feature_type);
Vect__execute_pg(pg_info->conn, "ROLLBACK");
return -1;
}
/* add geometry column */
sprintf(stmt, "SELECT AddGeometryColumn('%s', '%s', "
"'%s', %d, '%s', %d)",
pg_info->schema_name, pg_info->table_name,
pg_info->geom_column, pg_info->srid,
geom_type, pg_info->coor_dim);
G_debug(2, "SQL: %s", stmt);
result = PQexec(pg_info->conn, stmt);
if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
G_warning("%s", PQresultErrorMessage(result));
PQclear(result);
Vect__execute_pg(pg_info->conn, "ROLLBACK");
return -1;
}
/* create indices
- GV_KEY_COLUMN
- geometry column
*/
sprintf(stmt,
"CREATE INDEX %s_%s_idx ON \"%s\".\"%s\" (%s)",
pg_info->table_name, GV_KEY_COLUMN,
pg_info->schema_name, pg_info->table_name,
GV_KEY_COLUMN);
if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
Vect__execute_pg(pg_info->conn, "ROLLBACK");
return -1;
}
if (spatial_index) {
G_verbose_message(_("Building spatial index on <%s>..."),
pg_info->geom_column);
sprintf(stmt,
"CREATE INDEX %s_%s_idx ON \"%s\".\"%s\" USING GIST (%s)",
pg_info->table_name, pg_info->geom_column,
pg_info->schema_name, pg_info->table_name,
pg_info->geom_column);
if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
Vect__execute_pg(pg_info->conn, "ROLLBACK");
return -1;
}
}
/* close transaction (create table) */
if (Vect__execute_pg(pg_info->conn, "COMMIT") == -1) {
return -1;
}
return 0;
}
/*!
\brief Creates new schema for feature table if not exists
\param pg_info pointer to Format_info_pg
\return -1 on error
\return 0 on success
*/
int check_schema(const struct Format_info_pg *pg_info)
{
int i, found, nschema;
char stmt[DB_SQL_MAX];
PGresult *result;
if (!pg_info->conn || !pg_info->table_name) {
G_warning(_("No connection defined"));
return -1;
}
/* add geometry column */
sprintf(stmt, "SELECT nspname FROM pg_namespace");
G_debug(2, "SQL: %s", stmt);
result = PQexec(pg_info->conn, stmt);
if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
PQclear(result);
Vect__execute_pg(pg_info->conn, "ROLLBACK");
return -1;
}
found = FALSE;
nschema = PQntuples(result);
for (i = 0; i < nschema && !found; i++) {
if (strcmp(pg_info->schema_name, PQgetvalue(result, i, 0)) == 0)
found = TRUE;
}
PQclear(result);
if (!found) {
sprintf(stmt, "CREATE SCHEMA %s", pg_info->schema_name);
if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
Vect__execute_pg(pg_info->conn, "ROLLBACK");
return -1;
}
G_warning(_("Schema <%s> doesn't exist, created"),
pg_info->schema_name);
}
return 0;
}
/*!
\brief Create new PostGIS topology schema
- create topology schema
- add topology column to the feature table
\todo Add constraints for grass-like tables
\param pg_info pointer to Format_info_pg
\return 0 on success
\return 1 topology disable, nothing to do
\return -1 on failure
*/
int create_topo_schema(struct Format_info_pg *pg_info, int with_z)
{
double tolerance;
char stmt[DB_SQL_MAX];
char *def_file;
def_file = getenv("GRASS_VECTOR_PGFILE");
/* read default values from PG file*/
tolerance = 0.;
if (G_find_file2("", def_file ? def_file : "PG", G_mapset())) {
FILE *fp;
const char *p;
struct Key_Value *key_val;
fp = G_fopen_old("", def_file ? def_file : "PG", G_mapset());
if (!fp) {
G_fatal_error(_("Unable to open PG file"));
}
key_val = G_fread_key_value(fp);
fclose(fp);
/* tolerance */
p = G_find_key_value("topo_tolerance", key_val);
if (p)
tolerance = atof(p);
G_debug(1, "PG: tolerance: %f", tolerance);
/* topogeom column */
p = G_find_key_value("topogeom_name", key_val);
if (p)
pg_info->topogeom_column = G_store(p);
else
pg_info->topogeom_column = G_store(TOPOGEOM_COLUMN);
G_debug(1, "PG: topogeom_column :%s", pg_info->topogeom_column);
/* topo-geo only (default: no) */
p = G_find_key_value("topo_geo_only", key_val);
if (p && G_strcasecmp(p, "yes") == 0)
pg_info->topo_geo_only = TRUE;
G_debug(1, "PG: topo_geo_only :%d", pg_info->topo_geo_only);
/* build simple features from topogeometry data */
p = G_find_key_value("simple_feature", key_val);
if (p && G_strcasecmp(p, "yes") == 0)
pg_info->topo_geo_only = TRUE;
G_debug(1, "PG: topo_geo_only :%d", pg_info->topo_geo_only);
G_free_key_value(key_val);
}
/* begin transaction (create topo schema) */
if (Vect__execute_pg(pg_info->conn, "BEGIN") == -1) {
return -1;
}
/* create topology schema */
G_verbose_message(_("Creating topology schema <%s>..."),
pg_info->toposchema_name);
sprintf(stmt, "SELECT topology.createtopology('%s', "
"find_srid('%s', '%s', '%s'), %f, '%s')",
pg_info->toposchema_name, pg_info->schema_name,
pg_info->table_name, pg_info->geom_column, tolerance,
with_z == WITH_Z ? "t" : "f");
pg_info->toposchema_id = Vect__execute_get_value_pg(pg_info->conn, stmt);
if (pg_info->toposchema_id == -1) {
Vect__execute_pg(pg_info->conn, "ROLLBACK");
return -1;
}
/* add topo column to the feature table */
G_verbose_message(_("Adding new topology column <%s>..."),
pg_info->topogeom_column);
sprintf(stmt, "SELECT topology.AddTopoGeometryColumn('%s', '%s', '%s', "
"'%s', '%s')", pg_info->toposchema_name, pg_info->schema_name,
pg_info->table_name, pg_info->topogeom_column,
get_sftype(pg_info->feature_type));
if (-1 == Vect__execute_get_value_pg(pg_info->conn, stmt)) {
Vect__execute_pg(pg_info->conn, "ROLLBACK");
return -1;
}
/* create index on topo column */
sprintf(stmt, "CREATE INDEX \"%s_%s_%s_idx\" ON \"%s\".\"%s\" (((%s).id))",
pg_info->schema_name, pg_info->table_name, pg_info->topogeom_column,
pg_info->schema_name, pg_info->table_name, pg_info->topogeom_column);
if (-1 == Vect__execute_pg(pg_info->conn, stmt)) {
Vect__execute_pg(pg_info->conn, "ROLLBACK");
return -1;
}
/* change constraints to deferrable initially deferred */
if (!pg_info->topo_geo_only) {
if (-1 == set_constraint_to_deferrable(pg_info, "node", "face_exists",
"containing_face", "face", "face_id") ||
-1 == set_constraint_to_deferrable(pg_info, "edge_data", "end_node_exists",
"end_node", "node", "node_id") ||
-1 == set_constraint_to_deferrable(pg_info, "edge_data", "left_face_exists",
"left_face", "face", "face_id") ||
-1 == set_constraint_to_deferrable(pg_info, "edge_data", "right_face_exists",
"right_face", "face", "face_id") ||
-1 == set_constraint_to_deferrable(pg_info, "edge_data", "start_node_exists",
"start_node", "node", "node_id"))
return -1;
}
/* create additional tables in topological schema to store
GRASS topology in DB */
if (!pg_info->topo_geo_only) {
/* (1) create 'node_grass' (see P_node struct)
todo: add constraints for lines and angles
*/
sprintf(stmt, "CREATE TABLE \"%s\".%s (node_id SERIAL PRIMARY KEY, "
"lines integer[], angles float[])", pg_info->toposchema_name, TOPO_TABLE_NODE);
if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
Vect__execute_pg(pg_info->conn, "ROLLBACK");
return -1;
}
sprintf(stmt, "ALTER TABLE \"%s\".%s ADD CONSTRAINT node_exists "
"FOREIGN KEY (node_id) REFERENCES \"%s\".node (node_id) "
"DEFERRABLE INITIALLY DEFERRED",
pg_info->toposchema_name, TOPO_TABLE_NODE, pg_info->toposchema_name);
if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
Vect__execute_pg(pg_info->conn, "ROLLBACK");
return -1;
}
/* (2) create 'line_grass' (see P_line struct)
*/
sprintf(stmt, "CREATE TABLE \"%s\".%s (line_id SERIAL PRIMARY KEY, "
"left_area integer, right_area integer)",
pg_info->toposchema_name, TOPO_TABLE_LINE);
if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
Vect__execute_pg(pg_info->conn, "ROLLBACK");