forked from postgis/postgis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpgsql2shp-core.c
2226 lines (1861 loc) · 57.1 KB
/
pgsql2shp-core.c
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
/**********************************************************************
*
* PostGIS - Spatial Types for PostgreSQL
* http://www.postgis.org
*
* Copyright (C) 2001-2003 Refractions Research Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU General Public Licence. See the COPYING file.
*
**********************************************************************
*
* PostGIS to Shapefile converter
*
* Original Author: Jeff Lounsbury <jeffloun@refractions.net>
* Contributions by: Sandro Santilli <strk@keybit.bet>
* Enhanced by: Mark Cave-Ayland <mark.cave-ayland@siriusit.co.uk>
*
**********************************************************************/
#include "../postgis_config.h"
#include "pgsql2shp-core.h"
/* Solaris9 does not provide stdint.h */
/* #include <stdint.h> */
#include <inttypes.h>
#ifdef HAVE_UNISTD_H /* for getpid() and getopt */
#include <unistd.h>
#endif
#ifdef __CYGWIN__
#include <sys/param.h>
#endif
#include "../liblwgeom/liblwgeom.h" /* for LWGEOM struct and funx */
#include "../liblwgeom/lwgeom_log.h" /* for LWDEBUG macros */
/* Maximum DBF field width (according to ARCGIS) */
#define MAX_DBF_FIELD_SIZE 254
/* Prototypes */
static int reverse_points(int num_points, double *x, double *y, double *z, double *m);
static int is_clockwise(int num_points,double *x,double *y,double *z);
static int is_bigendian(void);
static SHPObject *create_point(SHPDUMPERSTATE *state, LWPOINT *lwpoint);
static SHPObject *create_multipoint(SHPDUMPERSTATE *state, LWMPOINT *lwmultipoint);
static SHPObject *create_polygon(SHPDUMPERSTATE *state, LWPOLY *lwpolygon);
static SHPObject *create_multipolygon(SHPDUMPERSTATE *state, LWMPOLY *lwmultipolygon);
static SHPObject *create_linestring(SHPDUMPERSTATE *state, LWLINE *lwlinestring);
static SHPObject *create_multilinestring(SHPDUMPERSTATE *state, LWMLINE *lwmultilinestring);
static char *nullDBFValue(char fieldType);
static int getMaxFieldSize(PGconn *conn, char *schema, char *table, char *fname);
static int getTableInfo(SHPDUMPERSTATE *state);
static int projFileCreate(SHPDUMPERSTATE *state);
/**
* @brief Make appropriate formatting of a DBF value based on type.
* Might return untouched input or pointer to static private
* buffer: use return value right away.
*/
static char * goodDBFValue(char *in, char fieldType);
/** @brief Binary to hexewkb conversion function */
char *convert_bytes_to_hex(uint8_t *ewkb, size_t size);
static SHPObject *
create_point(SHPDUMPERSTATE *state, LWPOINT *lwpoint)
{
SHPObject *obj;
POINT4D p4d;
double *xpts, *ypts, *zpts, *mpts;
/* Allocate storage for points */
xpts = malloc(sizeof(double));
ypts = malloc(sizeof(double));
zpts = malloc(sizeof(double));
mpts = malloc(sizeof(double));
/* Grab the point: note getPoint4d will correctly handle
the case where the POINTs don't contain Z or M coordinates */
p4d = getPoint4d(lwpoint->point, 0);
xpts[0] = p4d.x;
ypts[0] = p4d.y;
zpts[0] = p4d.z;
mpts[0] = p4d.m;
LWDEBUGF(4, "Point: %g %g %g %g", xpts[0], ypts[0], zpts[0], mpts[0]);
obj = SHPCreateObject(state->outshptype, -1, 0, NULL, NULL, 1, xpts, ypts, zpts, mpts);
free(xpts);
free(ypts);
free(zpts);
free(mpts);
return obj;
}
static SHPObject *
create_multipoint(SHPDUMPERSTATE *state, LWMPOINT *lwmultipoint)
{
SHPObject *obj;
POINT4D p4d;
int i;
double *xpts, *ypts, *zpts, *mpts;
/* Allocate storage for points */
xpts = malloc(sizeof(double) * lwmultipoint->ngeoms);
ypts = malloc(sizeof(double) * lwmultipoint->ngeoms);
zpts = malloc(sizeof(double) * lwmultipoint->ngeoms);
mpts = malloc(sizeof(double) * lwmultipoint->ngeoms);
/* Grab the points: note getPoint4d will correctly handle
the case where the POINTs don't contain Z or M coordinates */
for (i = 0; i < lwmultipoint->ngeoms; i++)
{
p4d = getPoint4d(lwmultipoint->geoms[i]->point, 0);
xpts[i] = p4d.x;
ypts[i] = p4d.y;
zpts[i] = p4d.z;
mpts[i] = p4d.m;
LWDEBUGF(4, "MultiPoint %d - Point: %g %g %g %g", i, xpts[i], ypts[i], zpts[i], mpts[i]);
}
obj = SHPCreateObject(state->outshptype, -1, 0, NULL, NULL, lwmultipoint->ngeoms, xpts, ypts, zpts, mpts);
free(xpts);
free(ypts);
free(zpts);
free(mpts);
return obj;
}
static SHPObject *
create_polygon(SHPDUMPERSTATE *state, LWPOLY *lwpolygon)
{
SHPObject *obj;
POINT4D p4d;
int i, j;
double *xpts, *ypts, *zpts, *mpts;
int *shpparts, shppointtotal = 0, shppoint = 0;
/* Allocate storage for ring pointers */
shpparts = malloc(sizeof(int) * lwpolygon->nrings);
/* First count through all the points in each ring so we now how much memory is required */
for (i = 0; i < lwpolygon->nrings; i++)
shppointtotal += lwpolygon->rings[i]->npoints;
/* Allocate storage for points */
xpts = malloc(sizeof(double) * shppointtotal);
ypts = malloc(sizeof(double) * shppointtotal);
zpts = malloc(sizeof(double) * shppointtotal);
mpts = malloc(sizeof(double) * shppointtotal);
LWDEBUGF(4, "Total number of points: %d", shppointtotal);
/* Iterate through each ring setting up shpparts to point to the beginning of each ring */
for (i = 0; i < lwpolygon->nrings; i++)
{
/* For each ring, store the integer coordinate offset for the start of each ring */
shpparts[i] = shppoint;
for (j = 0; j < lwpolygon->rings[i]->npoints; j++)
{
p4d = getPoint4d(lwpolygon->rings[i], j);
xpts[shppoint] = p4d.x;
ypts[shppoint] = p4d.y;
zpts[shppoint] = p4d.z;
mpts[shppoint] = p4d.m;
LWDEBUGF(4, "Polygon Ring %d - Point: %g %g %g %g", i, xpts[shppoint], ypts[shppoint], zpts[shppoint], mpts[shppoint]);
/* Increment the point counter */
shppoint++;
}
/*
* First ring should be clockwise,
* other rings should be counter-clockwise
*/
if ( i == 0 )
{
if ( ! is_clockwise(lwpolygon->rings[i]->npoints,
&xpts[shpparts[i]], &ypts[shpparts[i]], NULL) )
{
LWDEBUG(4, "Outer ring not clockwise, forcing clockwise\n");
reverse_points(lwpolygon->rings[i]->npoints,
&xpts[shpparts[i]], &ypts[shpparts[i]],
&zpts[shpparts[i]], &mpts[shpparts[i]]);
}
}
else
{
if ( is_clockwise(lwpolygon->rings[i]->npoints,
&xpts[shpparts[i]], &ypts[shpparts[i]], NULL) )
{
LWDEBUGF(4, "Inner ring %d not counter-clockwise, forcing counter-clockwise\n", i);
reverse_points(lwpolygon->rings[i]->npoints,
&xpts[shpparts[i]], &ypts[shpparts[i]],
&zpts[shpparts[i]], &mpts[shpparts[i]]);
}
}
}
obj = SHPCreateObject(state->outshptype, -1, lwpolygon->nrings, shpparts, NULL, shppointtotal, xpts, ypts, zpts, mpts);
free(xpts);
free(ypts);
free(zpts);
free(mpts);
free(shpparts);
return obj;
}
static SHPObject *
create_multipolygon(SHPDUMPERSTATE *state, LWMPOLY *lwmultipolygon)
{
SHPObject *obj;
POINT4D p4d;
int i, j, k;
double *xpts, *ypts, *zpts, *mpts;
int *shpparts, shppointtotal = 0, shppoint = 0, shpringtotal = 0, shpring = 0;
/* NOTE: Multipolygons are stored in shapefiles as Polygon* shapes with multiple outer rings */
/* First count through each ring of each polygon so we now know much memory is required */
for (i = 0; i < lwmultipolygon->ngeoms; i++)
{
for (j = 0; j < lwmultipolygon->geoms[i]->nrings; j++)
{
shpringtotal++;
shppointtotal += lwmultipolygon->geoms[i]->rings[j]->npoints;
}
}
/* Allocate storage for ring pointers */
shpparts = malloc(sizeof(int) * shpringtotal);
/* Allocate storage for points */
xpts = malloc(sizeof(double) * shppointtotal);
ypts = malloc(sizeof(double) * shppointtotal);
zpts = malloc(sizeof(double) * shppointtotal);
mpts = malloc(sizeof(double) * shppointtotal);
LWDEBUGF(4, "Total number of rings: %d Total number of points: %d", shpringtotal, shppointtotal);
/* Iterate through each ring of each polygon in turn */
for (i = 0; i < lwmultipolygon->ngeoms; i++)
{
for (j = 0; j < lwmultipolygon->geoms[i]->nrings; j++)
{
/* For each ring, store the integer coordinate offset for the start of each ring */
shpparts[shpring] = shppoint;
LWDEBUGF(4, "Ring offset: %d", shpring);
for (k = 0; k < lwmultipolygon->geoms[i]->rings[j]->npoints; k++)
{
p4d = getPoint4d(lwmultipolygon->geoms[i]->rings[j], k);
xpts[shppoint] = p4d.x;
ypts[shppoint] = p4d.y;
zpts[shppoint] = p4d.z;
mpts[shppoint] = p4d.m;
LWDEBUGF(4, "MultiPolygon %d Polygon Ring %d - Point: %g %g %g %g", i, j, xpts[shppoint], ypts[shppoint], zpts[shppoint], mpts[shppoint]);
/* Increment the point counter */
shppoint++;
}
/*
* First ring should be clockwise,
* other rings should be counter-clockwise
*/
if ( j == 0 )
{
if ( ! is_clockwise(lwmultipolygon->geoms[i]->rings[j]->npoints,
&xpts[shpparts[shpring]], &ypts[shpparts[shpring]], NULL) )
{
LWDEBUG(4, "Outer ring not clockwise, forcing clockwise\n");
reverse_points(lwmultipolygon->geoms[i]->rings[j]->npoints,
&xpts[shpparts[shpring]], &ypts[shpparts[shpring]],
&zpts[shpparts[shpring]], &mpts[shpparts[shpring]]);
}
}
else
{
if ( is_clockwise(lwmultipolygon->geoms[i]->rings[j]->npoints,
&xpts[shpparts[shpring]], &ypts[shpparts[shpring]], NULL) )
{
LWDEBUGF(4, "Inner ring %d not counter-clockwise, forcing counter-clockwise\n", i);
reverse_points(lwmultipolygon->geoms[i]->rings[j]->npoints,
&xpts[shpparts[shpring]], &ypts[shpparts[shpring]],
&zpts[shpparts[shpring]], &mpts[shpparts[shpring]]);
}
}
/* Increment the ring counter */
shpring++;
}
}
obj = SHPCreateObject(state->outshptype, -1, shpringtotal, shpparts, NULL, shppointtotal, xpts, ypts, zpts, mpts);
free(xpts);
free(ypts);
free(zpts);
free(mpts);
free(shpparts);
return obj;
}
static SHPObject *
create_linestring(SHPDUMPERSTATE *state, LWLINE *lwlinestring)
{
SHPObject *obj;
POINT4D p4d;
int i;
double *xpts, *ypts, *zpts, *mpts;
/* Allocate storage for points */
xpts = malloc(sizeof(double) * lwlinestring->points->npoints);
ypts = malloc(sizeof(double) * lwlinestring->points->npoints);
zpts = malloc(sizeof(double) * lwlinestring->points->npoints);
mpts = malloc(sizeof(double) * lwlinestring->points->npoints);
/* Grab the points: note getPoint4d will correctly handle
the case where the POINTs don't contain Z or M coordinates */
for (i = 0; i < lwlinestring->points->npoints; i++)
{
p4d = getPoint4d(lwlinestring->points, i);
xpts[i] = p4d.x;
ypts[i] = p4d.y;
zpts[i] = p4d.z;
mpts[i] = p4d.m;
LWDEBUGF(4, "Linestring - Point: %g %g %g %g", i, xpts[i], ypts[i], zpts[i], mpts[i]);
}
obj = SHPCreateObject(state->outshptype, -1, 0, NULL, NULL, lwlinestring->points->npoints, xpts, ypts, zpts, mpts);
free(xpts);
free(ypts);
free(zpts);
free(mpts);
return obj;
}
static SHPObject *
create_multilinestring(SHPDUMPERSTATE *state, LWMLINE *lwmultilinestring)
{
SHPObject *obj;
POINT4D p4d;
int i, j;
double *xpts, *ypts, *zpts, *mpts;
int *shpparts, shppointtotal = 0, shppoint = 0;
/* Allocate storage for ring pointers */
shpparts = malloc(sizeof(int) * lwmultilinestring->ngeoms);
/* First count through all the points in each linestring so we now how much memory is required */
for (i = 0; i < lwmultilinestring->ngeoms; i++)
shppointtotal += lwmultilinestring->geoms[i]->points->npoints;
LWDEBUGF(3, "Total number of points: %d", shppointtotal);
/* Allocate storage for points */
xpts = malloc(sizeof(double) * shppointtotal);
ypts = malloc(sizeof(double) * shppointtotal);
zpts = malloc(sizeof(double) * shppointtotal);
mpts = malloc(sizeof(double) * shppointtotal);
/* Iterate through each linestring setting up shpparts to point to the beginning of each line */
for (i = 0; i < lwmultilinestring->ngeoms; i++)
{
/* For each linestring, store the integer coordinate offset for the start of each line */
shpparts[i] = shppoint;
for (j = 0; j < lwmultilinestring->geoms[i]->points->npoints; j++)
{
p4d = getPoint4d(lwmultilinestring->geoms[i]->points, j);
xpts[shppoint] = p4d.x;
ypts[shppoint] = p4d.y;
zpts[shppoint] = p4d.z;
mpts[shppoint] = p4d.m;
LWDEBUGF(4, "Linestring %d - Point: %g %g %g %g", i, xpts[shppoint], ypts[shppoint], zpts[shppoint], mpts[shppoint]);
/* Increment the point counter */
shppoint++;
}
}
obj = SHPCreateObject(state->outshptype, -1, lwmultilinestring->ngeoms, shpparts, NULL, shppoint, xpts, ypts, zpts, mpts);
free(xpts);
free(ypts);
free(zpts);
free(mpts);
return obj;
}
/*Reverse the clockwise-ness of the point list... */
static int
reverse_points(int num_points, double *x, double *y, double *z, double *m)
{
int i,j;
double temp;
j = num_points -1;
for (i=0; i <num_points; i++)
{
if (j <= i)
{
break;
}
temp = x[j];
x[j] = x[i];
x[i] = temp;
temp = y[j];
y[j] = y[i];
y[i] = temp;
if ( z )
{
temp = z[j];
z[j] = z[i];
z[i] = temp;
}
if ( m )
{
temp = m[j];
m[j] = m[i];
m[i] = temp;
}
j--;
}
return 1;
}
/* Return 1 if the points are in clockwise order */
static int
is_clockwise(int num_points, double *x, double *y, double *z)
{
int i;
double x_change,y_change,area;
double *x_new, *y_new; /* the points, translated to the origin
* for safer accuracy */
x_new = (double *)malloc(sizeof(double) * num_points);
y_new = (double *)malloc(sizeof(double) * num_points);
area=0.0;
x_change = x[0];
y_change = y[0];
for (i=0; i < num_points ; i++)
{
x_new[i] = x[i] - x_change;
y_new[i] = y[i] - y_change;
}
for (i=0; i < num_points - 1; i++)
{
/* calculate the area */
area += (x[i] * y[i+1]) - (y[i] * x[i+1]);
}
if (area > 0 )
{
free(x_new);
free(y_new);
return 0; /*counter-clockwise */
}
else
{
free(x_new);
free(y_new);
return 1; /*clockwise */
}
}
/*
* Return the maximum octet_length from given table.
* Return -1 on error.
*/
static int
getMaxFieldSize(PGconn *conn, char *schema, char *table, char *fname)
{
int size;
char *query;
PGresult *res;
/*( this is ugly: don't forget counting the length */
/* when changing the fixed query strings ) */
if ( schema )
{
query = (char *)malloc(strlen(fname)+strlen(table)+
strlen(schema)+46);
sprintf(query,
"select max(octet_length(\"%s\"::text)) from \"%s\".\"%s\"",
fname, schema, table);
}
else
{
query = (char *)malloc(strlen(fname)+strlen(table)+46);
sprintf(query,
"select max(octet_length(\"%s\"::text)) from \"%s\"",
fname, table);
}
LWDEBUGF(4, "maxFieldLenQuery: %s\n", query);
res = PQexec(conn, query);
free(query);
if ( ! res || PQresultStatus(res) != PGRES_TUPLES_OK )
{
printf( _("Querying for maximum field length: %s"),
PQerrorMessage(conn));
return -1;
}
if (PQntuples(res) <= 0 )
{
PQclear(res);
return -1;
}
size = atoi(PQgetvalue(res, 0, 0));
PQclear(res);
return size;
}
static int
is_bigendian(void)
{
int test = 1;
if ( (((char *)(&test))[0]) == 1)
{
return 0; /*NDR (little_endian) */
}
else
{
return 1; /*XDR (big_endian) */
}
}
char *
shapetypename(int num)
{
switch (num)
{
case SHPT_NULL:
return "Null Shape";
case SHPT_POINT:
return "Point";
case SHPT_ARC:
return "PolyLine";
case SHPT_POLYGON:
return "Polygon";
case SHPT_MULTIPOINT:
return "MultiPoint";
case SHPT_POINTZ:
return "PointZ";
case SHPT_ARCZ:
return "PolyLineZ";
case SHPT_POLYGONZ:
return "PolygonZ";
case SHPT_MULTIPOINTZ:
return "MultiPointZ";
case SHPT_POINTM:
return "PointM";
case SHPT_ARCM:
return "PolyLineM";
case SHPT_POLYGONM:
return "PolygonM";
case SHPT_MULTIPOINTM:
return "MultiPointM";
case SHPT_MULTIPATCH:
return "MultiPatch";
default:
return "Unknown";
}
}
/* This is taken and adapted from dbfopen.c of shapelib */
static char *
nullDBFValue(char fieldType)
{
switch (fieldType)
{
case FTInteger:
case FTDouble:
/* NULL numeric fields have value "****************" */
return "****************";
case FTDate:
/* NULL date fields have value "00000000" */
return " ";
case FTLogical:
/* NULL boolean fields have value "?" */
return "?";
default:
/* empty string fields are considered NULL */
return "";
}
}
/**
* @brief Make appropriate formatting of a DBF value based on type.
* Might return untouched input or pointer to static private
* buffer: use return value right away.
*/
static char *
goodDBFValue(char *in, char fieldType)
{
/*
* We only work on FTLogical and FTDate.
* FTLogical is 1 byte, FTDate is 8 byte (YYYYMMDD)
* We allocate space for 9 bytes to take
* terminating null into account
*/
static char buf[9];
switch (fieldType)
{
case FTLogical:
buf[0] = toupper(in[0]);
buf[1]='\0';
return buf;
case FTDate:
buf[0]=in[0]; /* Y */
buf[1]=in[1]; /* Y */
buf[2]=in[2]; /* Y */
buf[3]=in[3]; /* Y */
buf[4]=in[5]; /* M */
buf[5]=in[6]; /* M */
buf[6]=in[8]; /* D */
buf[7]=in[9]; /* D */
buf[8]='\0';
return buf;
default:
return in;
}
}
char *convert_bytes_to_hex(uint8_t *ewkb, size_t size)
{
int i;
char *hexewkb;
/* Convert the byte stream to a hex string using liblwgeom's deparse_hex function */
hexewkb = malloc(size * 2 + 1);
for (i=0; i<size; ++i) deparse_hex(ewkb[i], &hexewkb[i * 2]);
hexewkb[size * 2] = '\0';
return hexewkb;
}
/**
* @brief Creates ESRI .prj file for this shp output
* It looks in the spatial_ref_sys table and outputs the srtext field for this data
* If data is a table will use geometry_columns, if a query or view will read SRID from query output.
* @warning Will give warning and not output a .prj file if SRID is -1, Unknown, mixed SRIDS or not found in spatial_ref_sys. The dbf and shp will still be output.
*/
static int
projFileCreate(SHPDUMPERSTATE *state)
{
FILE *fp;
char *pszFullname, *pszBasename;
int i;
char *pszFilename = state->shp_file;
char *schema = state->schema;
char *table = state->table;
char *geo_col_name = state->geo_col_name;
char *srtext;
char *query;
char *esc_schema;
char *esc_table;
char *esc_geo_col_name;
int error, result;
PGresult *res;
int size;
/***********
*** I'm multiplying by 2 instead of 3 because I am too lazy to figure out how many characters to add
*** after escaping if any **/
size = 1000;
if ( schema )
{
size += 3 * strlen(schema);
}
size += 1000;
esc_table = (char *) malloc(3 * strlen(table) + 1);
esc_geo_col_name = (char *) malloc(3 * strlen(geo_col_name) + 1);
PQescapeStringConn(state->conn, esc_table, table, strlen(table), &error);
PQescapeStringConn(state->conn, esc_geo_col_name, geo_col_name, strlen(geo_col_name), &error);
/** make our address space large enough to hold query with table/schema **/
query = (char *) malloc(size);
if ( ! query ) return 0; /* out of virtual memory */
/**************************************************
* Get what kind of spatial ref is the selected geometry field
* We first check the geometry_columns table for a match and then if no match do a distinct against the table
* NOTE: COALESCE does a short-circuit check returning the faster query result and skipping the second if first returns something
* Escaping quotes in the schema and table in query may not be necessary except to prevent malicious attacks
* or should someone be crazy enough to have quotes or other weird character in their table, column or schema names
**************************************************/
if ( schema )
{
esc_schema = (char *) malloc(2 * strlen(schema) + 1);
PQescapeStringConn(state->conn, esc_schema, schema, strlen(schema), &error);
sprintf(query, "SELECT COALESCE((SELECT sr.srtext "
" FROM geometry_columns As gc INNER JOIN spatial_ref_sys sr ON sr.srid = gc.srid "
" WHERE gc.f_table_schema = '%s' AND gc.f_table_name = '%s' AND gc.f_geometry_column = '%s' LIMIT 1), "
" (SELECT CASE WHEN COUNT(DISTINCT sr.srid) > 1 THEN 'm' ELSE MAX(sr.srtext) END As srtext "
" FROM \"%s\".\"%s\" As g INNER JOIN spatial_ref_sys sr ON sr.srid = ST_SRID((g.\"%s\")::geometry)) , ' ') As srtext ",
esc_schema, esc_table,esc_geo_col_name, schema, table, geo_col_name);
free(esc_schema);
}
else
{
sprintf(query, "SELECT COALESCE((SELECT sr.srtext "
" FROM geometry_columns As gc INNER JOIN spatial_ref_sys sr ON sr.srid = gc.srid "
" WHERE gc.f_table_name = '%s' AND gc.f_geometry_column = '%s' AND pg_table_is_visible((gc.f_table_schema || '.' || gc.f_table_name)::regclass) LIMIT 1), "
" (SELECT CASE WHEN COUNT(DISTINCT sr.srid) > 1 THEN 'm' ELSE MAX(sr.srtext) END as srtext "
" FROM \"%s\" As g INNER JOIN spatial_ref_sys sr ON sr.srid = ST_SRID((g.\"%s\")::geometry)), ' ') As srtext ",
esc_table, esc_geo_col_name, table, geo_col_name);
}
LWDEBUGF(3,"%s\n",query);
free(esc_table);
free(esc_geo_col_name);
res = PQexec(state->conn, query);
if ( ! res || PQresultStatus(res) != PGRES_TUPLES_OK )
{
snprintf(state->message, SHPDUMPERMSGLEN, _("WARNING: Could not execute prj query: %s"), PQresultErrorMessage(res));
PQclear(res);
free(query);
return SHPDUMPERWARN;
}
for (i=0; i < PQntuples(res); i++)
{
srtext = PQgetvalue(res, i, 0);
if (strcmp(srtext,"m") == 0)
{
snprintf(state->message, SHPDUMPERMSGLEN, _("WARNING: Mixed set of spatial references. No prj file will be generated"));
PQclear(res);
free(query);
return SHPDUMPERWARN;
}
else
{
if (srtext[0] == ' ')
{
snprintf(state->message, SHPDUMPERMSGLEN, _("WARNING: Cannot determine spatial reference (empty table or unknown spatial ref). No prj file will be generated."));
PQclear(res);
free(query);
return SHPDUMPERWARN;
}
else
{
/* -------------------------------------------------------------------- */
/* Compute the base (layer) name. If there is any extension */
/* on the passed in filename we will strip it off. */
/* -------------------------------------------------------------------- */
pszBasename = (char *) malloc(strlen(pszFilename)+5);
strcpy( pszBasename, pszFilename );
for ( i = strlen(pszBasename)-1;
i > 0 && pszBasename[i] != '.' && pszBasename[i] != '/'
&& pszBasename[i] != '\\';
i-- ) {}
if ( pszBasename[i] == '.' )
pszBasename[i] = '\0';
pszFullname = (char *) malloc(strlen(pszBasename) + 5);
sprintf( pszFullname, "%s.prj", pszBasename );
free( pszBasename );
/* -------------------------------------------------------------------- */
/* Create the file. */
/* -------------------------------------------------------------------- */
fp = fopen( pszFullname, "wb" );
if ( fp == NULL )
{
return 0;
}
{
result = fputs (srtext,fp);
LWDEBUGF(3, "\n result %d proj SRText is %s .\n", result, srtext);
if (result == EOF)
{
fclose( fp );
free( pszFullname );
PQclear(res);
free(query);
return 0;
}
}
fclose( fp );
free( pszFullname );
}
}
}
PQclear(res);
free(query);
return SHPDUMPEROK;
}
static int
getTableInfo(SHPDUMPERSTATE *state)
{
/* Get some more information from the table:
- count = total number of geometries/geographies in the table
and if we have found a suitable geometry column:
- max = maximum number of dimensions within the geometry/geography column
- geometrytype = string representing the geometry/geography type, e.g. POINT
Since max/geometrytype already require a sequential scan of the table, we may as
well get the row count too.
*/
PGresult *res;
char *query;
int tmpint;
if (state->geo_col_name)
{
/* Include geometry information */
if (state->schema)
{
query = malloc(150 + 4 * strlen(state->geo_col_name) + strlen(state->schema) + strlen(state->table));
sprintf(query, "SELECT count(\"%s\"), max(ST_zmflag(\"%s\"::geometry)), geometrytype(\"%s\"::geometry) FROM \"%s\".\"%s\" GROUP BY geometrytype(\"%s\"::geometry)",
state->geo_col_name, state->geo_col_name, state->geo_col_name, state->schema, state->table, state->geo_col_name);
}
else
{
query = malloc(150 + 4 * strlen(state->geo_col_name) + strlen(state->table));
sprintf(query, "SELECT count(\"%s\"), max(ST_zmflag(\"%s\"::geometry)), geometrytype(\"%s\"::geometry) FROM \"%s\" GROUP BY geometrytype(\"%s\"::geometry)",
state->geo_col_name, state->geo_col_name, state->geo_col_name, state->table, state->geo_col_name);
}
}
else
{
/* Otherwise... just a row count will do */
if (state->schema)
{
query = malloc(40 + strlen(state->schema) + strlen(state->table));
sprintf(query, "SELECT count(1) FROM \"%s\".\"%s\"", state->schema, state->table);
}
else
{
query = malloc(40 + strlen(state->table));
sprintf(query, "SELECT count(1) FROM \"%s\"", state->table);
}
}
LWDEBUGF(3, "Table metadata query: %s\n", query);
res = PQexec(state->conn, query);
free(query);
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
snprintf(state->message, SHPDUMPERMSGLEN, _("ERROR: Could not execute table metadata query: %s"), PQresultErrorMessage(res));
PQclear(res);
return SHPDUMPERERR;
}
/* Make sure we error if the table is empty */
if (PQntuples(res) == 0)
{
snprintf(state->message, SHPDUMPERMSGLEN, _("ERROR: Could not determine table metadata (empty table)"));
PQclear(res);
return SHPDUMPERERR;
}
/* If we have a geo* column, get the dimension, type and count information */
if (state->geo_col_name)
{
/* If a table has a geometry column containing mixed types then
the metadata query will return multiple rows. We need to cycle
through all rows to determine if the type combinations are valid.
Note that if we find a combination of a MULTI and non-MULTI geometry
of the same type, we always choose MULTI to ensure that everything
gets output correctly. The create_* conversion functions are clever
enough to up-convert the non-MULTI geometry to a MULTI in this case. */
int dummy, i;
uint8_t type = 0;
int typefound = 0, typemismatch = 0;
state->rowcount = 0;
for (i = 0; i < PQntuples(res); i++)
{
geometry_type_from_string(PQgetvalue(res, i, 2), &type, &dummy, &dummy);
if (!type) continue; /* skip null geometries */
/* We can always set typefound to that of the first column found */
if (!typefound)
typefound = type;
switch (type)
{
case MULTIPOINTTYPE:
if (typefound != MULTIPOINTTYPE && typefound != POINTTYPE)
typemismatch = 1;
else
typefound = MULTIPOINTTYPE;
break;
case MULTILINETYPE:
if (typefound != MULTILINETYPE && typefound != LINETYPE)
typemismatch = 1;
else
typefound = MULTILINETYPE;
break;
case MULTIPOLYGONTYPE:
if (typefound != MULTIPOLYGONTYPE && typefound != POLYGONTYPE)
typemismatch = 1;
else
typefound = MULTIPOLYGONTYPE;
break;
case POINTTYPE:
if (typefound != POINTTYPE && typefound != MULTIPOINTTYPE)
typemismatch = 1;
else if (!lwtype_is_collection(type))
typefound = POINTTYPE;
break;
case LINETYPE:
if (typefound != LINETYPE && typefound != MULTILINETYPE)
typemismatch = 1;
else if (!lwtype_is_collection(type))
typefound = LINETYPE;
break;
case POLYGONTYPE:
if (typefound != POLYGONTYPE && typefound != MULTIPOLYGONTYPE)