PostGIS  3.4.0dev-r@@SVN_REVISION@@
shp2pgsql-core.c
Go to the documentation of this file.
1 /**********************************************************************
2  *
3  * PostGIS - Spatial Types for PostgreSQL
4  * http://postgis.net
5  *
6  * Copyright (C) 2008 OpenGeo.org
7  * Copyright (C) 2009 Mark Cave-Ayland <mark.cave-ayland@siriusit.co.uk>
8  *
9  * This is free software; you can redistribute and/or modify it under
10  * the terms of the GNU General Public Licence. See the COPYING file.
11  *
12  * Maintainer: Paul Ramsey <pramsey@cleverelephant.ca>
13  *
14  **********************************************************************/
15 
16 #include "../postgis_config.h"
17 
18 #include <math.h> /* for isnan */
19 
20 #include "shp2pgsql-core.h"
21 #include "../liblwgeom/liblwgeom.h"
22 #include "../liblwgeom/lwgeom_log.h" /* for LWDEBUG macros */
23 
24 
25 
26 /* Internal ring/point structures */
27 typedef struct struct_point
28 {
29  double x, y, z, m;
31 
32 typedef struct struct_ring
33 {
34  Point *list; /* list of points */
35  struct struct_ring *next;
36  int n; /* number of points in list */
37  unsigned int linked; /* number of "next" rings */
38 } Ring;
39 
40 
41 /*
42  * Internal functions
43  */
44 
45 #define UTF8_GOOD_RESULT 0
46 #define UTF8_BAD_RESULT 1
47 #define UTF8_NO_RESULT 2
48 
49 char *escape_copy_string(char *str);
50 char *escape_insert_string(char *str);
51 
52 int GeneratePointGeometry(SHPLOADERSTATE *state, SHPObject *obj, char **geometry, int force_multi);
53 int GenerateLineStringGeometry(SHPLOADERSTATE *state, SHPObject *obj, char **geometry);
54 int PIP(Point P, Point *V, int n);
55 int FindPolygons(SHPObject *obj, Ring ***Out);
56 void ReleasePolygons(Ring **polys, int npolys);
57 int GeneratePolygonGeometry(SHPLOADERSTATE *state, SHPObject *obj, char **geometry);
58 
59 
60 /* Return allocated string containing UTF8 string converted from encoding fromcode */
61 static int
62 utf8(const char *fromcode, char *inputbuf, char **outputbuf)
63 {
64  iconv_t cd;
65  char *outputptr;
66  size_t outbytesleft;
67  size_t inbytesleft;
68 
69  inbytesleft = strlen(inputbuf);
70 
71  cd = iconv_open("UTF-8", fromcode);
72  if ( cd == ((iconv_t)(-1)) )
73  return UTF8_NO_RESULT;
74 
75  outbytesleft = inbytesleft * 3 + 1; /* UTF8 string can be 3 times larger */
76  /* then local string */
77  *outputbuf = (char *)malloc(outbytesleft);
78  if (!*outputbuf)
79  return UTF8_NO_RESULT;
80 
81  memset(*outputbuf, 0, outbytesleft);
82  outputptr = *outputbuf;
83 
84  /* Does this string convert cleanly? */
85  if ( iconv(cd, &inputbuf, &inbytesleft, &outputptr, &outbytesleft) == (size_t)-1 )
86  {
87 #ifdef HAVE_ICONVCTL
88  int on = 1;
89  /* No. Try to convert it while transliterating. */
90  iconvctl(cd, ICONV_SET_TRANSLITERATE, &on);
91  if ( iconv(cd, &inputbuf, &inbytesleft, &outputptr, &outbytesleft) == -1 )
92  {
93  /* No. Try to convert it while discarding errors. */
94  iconvctl(cd, ICONV_SET_DISCARD_ILSEQ, &on);
95  if ( iconv(cd, &inputbuf, &inbytesleft, &outputptr, &outbytesleft) == -1 )
96  {
97  /* Still no. Throw away the buffer and return. */
98  free(*outputbuf);
99  iconv_close(cd);
100  return UTF8_NO_RESULT;
101  }
102  }
103  iconv_close(cd);
104  return UTF8_BAD_RESULT;
105 #else
106  free(*outputbuf);
107  iconv_close(cd);
108  return UTF8_NO_RESULT;
109 #endif
110  }
111  /* Return a good result, converted string is in buffer. */
112  iconv_close(cd);
113  return UTF8_GOOD_RESULT;
114 }
115 
120 char *
122 {
123  /*
124  * Escape the following characters by adding a preceding backslash
125  * tab, backslash, cr, lf
126  *
127  * 1. find # of escaped characters
128  * 2. make new string
129  *
130  */
131 
132  char *result;
133  char *ptr, *optr;
134  int toescape = 0;
135  size_t size;
136 
137  ptr = str;
138 
139  /* Count how many characters we need to escape so we know the size of the string we need to return */
140  while (*ptr)
141  {
142  if (*ptr == '\t' || *ptr == '\\' || *ptr == '\n' || *ptr == '\r')
143  toescape++;
144 
145  ptr++;
146  }
147 
148  /* If we don't have to escape anything, simply return the input pointer */
149  if (toescape == 0)
150  return str;
151 
152  size = ptr - str + toescape + 1;
153  result = calloc(1, size);
154  optr = result;
155  ptr = str;
156 
157  while (*ptr)
158  {
159  if ( *ptr == '\t' || *ptr == '\\' || *ptr == '\n' || *ptr == '\r' )
160  *optr++ = '\\';
161 
162  *optr++ = *ptr++;
163  }
164 
165  *optr = '\0';
166 
167  return result;
168 }
169 
170 
175 char *
177 {
178  /*
179  * Escape single quotes by adding a preceding single quote
180  *
181  * 1. find # of characters
182  * 2. make new string
183  */
184 
185  char *result;
186  char *ptr, *optr;
187  int toescape = 0;
188  size_t size;
189 
190  ptr = str;
191 
192  /* Count how many characters we need to escape so we know the size of the string we need to return */
193  while (*ptr)
194  {
195  if (*ptr == '\'')
196  toescape++;
197 
198  ptr++;
199  }
200 
201  /* If we don't have to escape anything, simply return the input pointer */
202  if (toescape == 0)
203  return str;
204 
205  size = ptr - str + toescape + 1;
206  result = calloc(1, size);
207  optr = result;
208  ptr = str;
209 
210  while (*ptr)
211  {
212  if (*ptr == '\'')
213  *optr++='\'';
214 
215  *optr++ = *ptr++;
216  }
217 
218  *optr='\0';
219 
220  return result;
221 }
222 
223 
228 int
229 GeneratePointGeometry(SHPLOADERSTATE *state, SHPObject *obj, char **geometry, int force_multi)
230 {
231  LWGEOM **lwmultipoints;
232  LWGEOM *lwgeom = NULL;
233 
234  POINT4D point4d;
235 
236  int dims = 0;
237  int u;
238 
239  char *mem;
240  size_t mem_length;
241 
242  FLAGS_SET_Z(dims, state->has_z);
243  FLAGS_SET_M(dims, state->has_m);
244 
245  /* POINT EMPTY encoded as POINT(NaN NaN) */
246  if (obj->nVertices == 1 && isnan(obj->padfX[0]) && isnan(obj->padfY[0]))
247  {
248  lwgeom = lwpoint_as_lwgeom(lwpoint_construct_empty(state->from_srid, state->has_z, state->has_m));
249  }
250  /* Not empty */
251  else
252  {
253  /* Allocate memory for our array of LWPOINTs and our dynptarrays */
254  lwmultipoints = malloc(sizeof(LWPOINT *) * obj->nVertices);
255 
256  /* We need an array of pointers to each of our sub-geometries */
257  for (u = 0; u < obj->nVertices; u++)
258  {
259  /* Create a ptarray containing a single point */
260  POINTARRAY *pa = ptarray_construct_empty(state->has_z, state->has_m, 1);
261 
262  /* Generate the point */
263  point4d.x = obj->padfX[u];
264  point4d.y = obj->padfY[u];
265 
266  if (state->has_z)
267  point4d.z = obj->padfZ[u];
268  if (state->has_m)
269  point4d.m = obj->padfM[u];
270 
271  /* Add in the point! */
272  ptarray_append_point(pa, &point4d, LW_TRUE);
273 
274  /* Generate the LWPOINT */
275  lwmultipoints[u] = lwpoint_as_lwgeom(lwpoint_construct(state->from_srid, NULL, pa));
276  }
277 
278  /* If we have more than 1 vertex then we are working on a MULTIPOINT and so generate a MULTIPOINT
279  rather than a POINT */
280  if ((obj->nVertices > 1) || force_multi)
281  {
282  lwgeom = lwcollection_as_lwgeom(lwcollection_construct(MULTIPOINTTYPE, state->from_srid, NULL, obj->nVertices, lwmultipoints));
283  }
284  else
285  {
286  lwgeom = lwmultipoints[0];
287  lwfree(lwmultipoints);
288  }
289  }
290 
291  if (state->config->use_wkt)
292  {
293  mem = lwgeom_to_wkt(lwgeom, WKT_EXTENDED, WKT_PRECISION, &mem_length);
294  }
295  else
296  {
297  mem = lwgeom_to_hexwkb_buffer(lwgeom, WKB_EXTENDED);
298  }
299 
300  if ( !mem )
301  {
302  snprintf(state->message, SHPLOADERMSGLEN, "unable to write geometry");
303  return SHPLOADERERR;
304  }
305 
306  /* Free all of the allocated items */
307  lwgeom_free(lwgeom);
308 
309  /* Return the string - everything ok */
310  *geometry = mem;
311 
312  return SHPLOADEROK;
313 }
314 
315 
319 int
321 {
322 
323  LWGEOM **lwmultilinestrings;
324  LWGEOM *lwgeom = NULL;
325  POINT4D point4d;
326  int dims = 0;
327  int u, v, start_vertex, end_vertex;
328  char *mem;
329  size_t mem_length;
330 
331 
332  FLAGS_SET_Z(dims, state->has_z);
333  FLAGS_SET_M(dims, state->has_m);
334 
335  if (state->config->simple_geometries == 1 && obj->nParts > 1)
336  {
337  snprintf(state->message, SHPLOADERMSGLEN, _("We have a Multilinestring with %d parts, can't use -S switch!"), obj->nParts);
338 
339  return SHPLOADERERR;
340  }
341 
342  /* Allocate memory for our array of LWLINEs and our dynptarrays */
343  lwmultilinestrings = malloc(sizeof(LWPOINT *) * obj->nParts);
344 
345  /* We need an array of pointers to each of our sub-geometries */
346  for (u = 0; u < obj->nParts; u++)
347  {
348  /* Create a ptarray containing the line points */
349  POINTARRAY *pa = ptarray_construct_empty(state->has_z, state->has_m, obj->nParts);
350 
351  /* Set the start/end vertices depending upon whether this is
352  a MULTILINESTRING or not */
353  if ( u == obj->nParts-1 )
354  end_vertex = obj->nVertices;
355  else
356  end_vertex = obj->panPartStart[u + 1];
357 
358  start_vertex = obj->panPartStart[u];
359 
360  for (v = start_vertex; v < end_vertex; v++)
361  {
362  /* Generate the point */
363  point4d.x = obj->padfX[v];
364  point4d.y = obj->padfY[v];
365 
366  if (state->has_z)
367  point4d.z = obj->padfZ[v];
368  if (state->has_m)
369  point4d.m = obj->padfM[v];
370 
371  ptarray_append_point(pa, &point4d, LW_FALSE);
372  }
373 
374  /* Generate the LWLINE */
375  lwmultilinestrings[u] = lwline_as_lwgeom(lwline_construct(state->from_srid, NULL, pa));
376  }
377 
378  /* If using MULTILINESTRINGs then generate the serialized collection, otherwise just a single LINESTRING */
379  if (state->config->simple_geometries == 0)
380  {
381  lwgeom = lwcollection_as_lwgeom(lwcollection_construct(MULTILINETYPE, state->from_srid, NULL, obj->nParts, lwmultilinestrings));
382  }
383  else
384  {
385  lwgeom = lwmultilinestrings[0];
386  lwfree(lwmultilinestrings);
387  }
388 
389  if (!state->config->use_wkt)
390  mem = lwgeom_to_hexwkb_buffer(lwgeom, WKB_EXTENDED);
391  else
392  mem = lwgeom_to_wkt(lwgeom, WKT_EXTENDED, WKT_PRECISION, &mem_length);
393 
394  if ( !mem )
395  {
396  snprintf(state->message, SHPLOADERMSGLEN, "unable to write geometry");
397  return SHPLOADERERR;
398  }
399 
400  /* Free all of the allocated items */
401  lwgeom_free(lwgeom);
402 
403  /* Return the string - everything ok */
404  *geometry = mem;
405 
406  return SHPLOADEROK;
407 }
408 
409 
416 int
417 PIP(Point P, Point *V, int n)
418 {
419  int cn = 0; /* the crossing number counter */
420  int i;
421 
422  /* loop through all edges of the polygon */
423  for (i = 0; i < n-1; i++) /* edge from V[i] to V[i+1] */
424  {
425  if (((V[i].y <= P.y) && (V[i + 1].y > P.y)) /* an upward crossing */
426  || ((V[i].y > P.y) && (V[i + 1].y <= P.y))) /* a downward crossing */
427  {
428  double vt = (float)(P.y - V[i].y) / (V[i + 1].y - V[i].y);
429  if (P.x < V[i].x + vt * (V[i + 1].x - V[i].x)) /* P.x < intersect */
430  ++cn; /* a valid crossing of y=P.y right of P.x */
431  }
432  }
433 
434  return (cn&1); /* 0 if even (out), and 1 if odd (in) */
435 }
436 
437 
438 int
440 {
441  Ring **Outer; /* Pointers to Outer rings */
442  int out_index=0; /* Count of Outer rings */
443  Ring **Inner; /* Pointers to Inner rings */
444  int in_index=0; /* Count of Inner rings */
445  int pi; /* part index */
446 
447 #if POSTGIS_DEBUG_LEVEL > 0
448  static int call = -1;
449  call++;
450 #endif
451 
452  LWDEBUGF(4, "FindPolygons[%d]: allocated space for %d rings\n", call, obj->nParts);
453 
454  /* Allocate initial memory */
455  Outer = (Ring **)malloc(sizeof(Ring *) * obj->nParts);
456  Inner = (Ring **)malloc(sizeof(Ring *) * obj->nParts);
457 
458  /* Iterate over rings dividing in Outers and Inners */
459  for (pi=0; pi < obj->nParts; pi++)
460  {
461  int vi; /* vertex index */
462  int vs; /* start index */
463  int ve; /* end index */
464  int nv; /* number of vertex */
465  double area = 0.0;
466  Ring *ring;
467 
468  /* Set start and end vertexes */
469  if (pi == obj->nParts - 1)
470  ve = obj->nVertices;
471  else
472  ve = obj->panPartStart[pi + 1];
473 
474  vs = obj->panPartStart[pi];
475 
476  /* Compute number of vertexes */
477  nv = ve - vs;
478 
479  /* Allocate memory for a ring */
480  ring = (Ring *)malloc(sizeof(Ring));
481  ring->list = (Point *)malloc(sizeof(Point) * nv);
482  ring->n = nv;
483  ring->next = NULL;
484  ring->linked = 0;
485 
486  /* Iterate over ring vertexes */
487  for (vi = vs; vi < ve; vi++)
488  {
489  int vn = vi+1; /* next vertex for area */
490  if (vn == ve)
491  vn = vs;
492 
493  ring->list[vi - vs].x = obj->padfX[vi];
494  ring->list[vi - vs].y = obj->padfY[vi];
495  ring->list[vi - vs].z = obj->padfZ[vi];
496  ring->list[vi - vs].m = obj->padfM[vi];
497 
498  area += (obj->padfX[vi] * obj->padfY[vn]) -
499  (obj->padfY[vi] * obj->padfX[vn]);
500  }
501 
502  /* Close the ring with first vertex */
503  /*ring->list[vi].x = obj->padfX[vs]; */
504  /*ring->list[vi].y = obj->padfY[vs]; */
505  /*ring->list[vi].z = obj->padfZ[vs]; */
506  /*ring->list[vi].m = obj->padfM[vs]; */
507 
508  /* Clockwise (or single-part). It's an Outer Ring ! */
509  if (area < 0.0 || obj->nParts == 1)
510  {
511  Outer[out_index] = ring;
512  out_index++;
513  }
514  else
515  {
516  /* Counterclockwise. It's an Inner Ring ! */
517  Inner[in_index] = ring;
518  in_index++;
519  }
520  }
521 
522  LWDEBUGF(4, "FindPolygons[%d]: found %d Outer, %d Inners\n", call, out_index, in_index);
523 
524  /* Put the inner rings into the list of the outer rings */
525  /* of which they are within */
526  for (pi = 0; pi < in_index; pi++)
527  {
528  Point pt, pt2;
529  int i;
530  Ring *inner = Inner[pi], *outer = NULL;
531 
532  pt.x = inner->list[0].x;
533  pt.y = inner->list[0].y;
534 
535  pt2.x = inner->list[1].x;
536  pt2.y = inner->list[1].y;
537 
538  /*
539  * If we assume that the case of the "big polygon w/o hole
540  * containing little polygon w/ hold" is ordered so that the
541  * big polygon comes first, then checking the list in reverse
542  * will assign the little polygon's hole to the little polygon
543  * w/o a lot of extra fancy containment logic here
544  */
545  for (i = out_index - 1; i >= 0; i--)
546  {
547  int in;
548 
549  in = PIP(pt, Outer[i]->list, Outer[i]->n);
550  if ( in || PIP(pt2, Outer[i]->list, Outer[i]->n) )
551  {
552  outer = Outer[i];
553  break;
554  }
555  }
556 
557  if (outer)
558  {
559  outer->linked++;
560  while (outer->next)
561  outer = outer->next;
562 
563  outer->next = inner;
564  }
565  else
566  {
567  /* The ring wasn't within any outer rings, */
568  /* assume it is a new outer ring. */
569  LWDEBUGF(4, "FindPolygons[%d]: hole %d is orphan\n", call, pi);
570 
571  Outer[out_index] = inner;
572  out_index++;
573  }
574  }
575 
576  *Out = Outer;
577  /*
578  * Only free the containing Inner array, not the ring elements, because
579  * the rings are now owned by the linked lists in the Outer array elements.
580  */
581  free(Inner);
582 
583  return out_index;
584 }
585 
586 
587 void
588 ReleasePolygons(Ring **polys, int npolys)
589 {
590  int pi;
591 
592  /* Release all memory */
593  for (pi = 0; pi < npolys; pi++)
594  {
595  Ring *Poly, *temp;
596  Poly = polys[pi];
597  while (Poly != NULL)
598  {
599  temp = Poly;
600  Poly = Poly->next;
601  free(temp->list);
602  free(temp);
603  }
604  }
605 
606  free(polys);
607 }
608 
609 
617 int
618 GeneratePolygonGeometry(SHPLOADERSTATE *state, SHPObject *obj, char **geometry)
619 {
620  Ring **Outer;
621  int polygon_total, ring_total;
622  int pi, vi; /* part index and vertex index */
623 
624  LWGEOM **lwpolygons;
625  LWGEOM *lwgeom;
626 
627  POINT4D point4d;
628 
629  int dims = 0;
630 
631  char *mem;
632  size_t mem_length;
633 
634  FLAGS_SET_Z(dims, state->has_z);
635  FLAGS_SET_M(dims, state->has_m);
636 
637  polygon_total = FindPolygons(obj, &Outer);
638 
639  if (state->config->simple_geometries == 1 && polygon_total != 1) /* We write Non-MULTI geometries, but have several parts: */
640  {
641  snprintf(state->message, SHPLOADERMSGLEN, _("We have a Multipolygon with %d parts, can't use -S switch!"), polygon_total);
642 
643  return SHPLOADERERR;
644  }
645 
646  /* Allocate memory for our array of LWPOLYs */
647  lwpolygons = malloc(sizeof(LWPOLY *) * polygon_total);
648 
649  /* Cycle through each individual polygon */
650  for (pi = 0; pi < polygon_total; pi++)
651  {
652  LWPOLY *lwpoly = lwpoly_construct_empty(state->from_srid, state->has_z, state->has_m);
653 
654  Ring *polyring;
655  int ring_index = 0;
656 
657  /* Firstly count through the total number of rings in this polygon */
658  ring_total = 0;
659  polyring = Outer[pi];
660  while (polyring)
661  {
662  ring_total = ring_total + 1;
663  polyring = polyring->next;
664  }
665 
666  /* Cycle through each ring within the polygon, starting with the outer */
667  polyring = Outer[pi];
668 
669  while (polyring)
670  {
671  /* Create a POINTARRAY containing the points making up the ring */
672  POINTARRAY *pa = ptarray_construct_empty(state->has_z, state->has_m, polyring->n);
673 
674  for (vi = 0; vi < polyring->n; vi++)
675  {
676  /* Build up a point array of all the points in this ring */
677  point4d.x = polyring->list[vi].x;
678  point4d.y = polyring->list[vi].y;
679 
680  if (state->has_z)
681  point4d.z = polyring->list[vi].z;
682  if (state->has_m)
683  point4d.m = polyring->list[vi].m;
684 
685  ptarray_append_point(pa, &point4d, LW_TRUE);
686  }
687 
688  /* Copy the POINTARRAY pointer so we can use the LWPOLY constructor */
689  lwpoly_add_ring(lwpoly, pa);
690 
691  polyring = polyring->next;
692  ring_index = ring_index + 1;
693  }
694 
695  /* Generate the LWGEOM */
696  lwpolygons[pi] = lwpoly_as_lwgeom(lwpoly);
697  }
698 
699  /* If using MULTIPOLYGONS then generate the serialized collection, otherwise just a single POLYGON */
700  if (state->config->simple_geometries == 0)
701  {
702  lwgeom = lwcollection_as_lwgeom(lwcollection_construct(MULTIPOLYGONTYPE, state->from_srid, NULL, polygon_total, lwpolygons));
703  }
704  else
705  {
706  lwgeom = lwpolygons[0];
707  lwfree(lwpolygons);
708  }
709 
710  if (!state->config->use_wkt)
711  mem = lwgeom_to_hexwkb_buffer(lwgeom, WKB_EXTENDED);
712  else
713  mem = lwgeom_to_wkt(lwgeom, WKT_EXTENDED, WKT_PRECISION, &mem_length);
714 
715  if ( !mem )
716  {
717  /* Free the linked list of rings */
718  ReleasePolygons(Outer, polygon_total);
719 
720  snprintf(state->message, SHPLOADERMSGLEN, "unable to write geometry");
721  return SHPLOADERERR;
722  }
723 
724  /* Free all of the allocated items */
725  lwgeom_free(lwgeom);
726 
727  /* Free the linked list of rings */
728  ReleasePolygons(Outer, polygon_total);
729 
730  /* Return the string - everything ok */
731  *geometry = mem;
732 
733  return SHPLOADEROK;
734 }
735 
736 
737 /*
738  * External functions (defined in shp2pgsql-core.h)
739  */
740 
741 
742 /* Convert the string to lower case */
743 void
744 strtolower(char *s)
745 {
746  size_t j;
747 
748  for (j = 0; j < strlen(s); j++)
749  s[j] = tolower(s[j]);
750 }
751 
752 
753 /* Default configuration settings */
754 void
756 {
757  config->opt = 'c';
758  config->table = NULL;
759  config->schema = NULL;
760  config->geo_col = NULL;
761  config->shp_file = NULL;
762  config->dump_format = 0;
763  config->simple_geometries = 0;
764  config->geography = 0;
765  config->quoteidentifiers = 0;
766  config->forceint4 = 0;
767  config->createindex = 0;
768  config->analyze = 1;
769  config->readshape = 1;
771  config->encoding = strdup(ENCODING_DEFAULT);
773  config->sr_id = SRID_UNKNOWN;
774  config->shp_sr_id = SRID_UNKNOWN;
775  config->use_wkt = 0;
776  config->tablespace = NULL;
777  config->idxtablespace = NULL;
778  config->usetransaction = 1;
779  config->column_map_filename = NULL;
780 }
781 
782 /* Create a new shapefile state object */
785 {
786  SHPLOADERSTATE *state;
787 
788  /* Create a new state object and assign the config to it */
789  state = malloc(sizeof(SHPLOADERSTATE));
790  state->config = config;
791 
792  /* Set any state defaults */
793  state->hSHPHandle = NULL;
794  state->hDBFHandle = NULL;
795  state->has_z = 0;
796  state->has_m = 0;
797  state->types = NULL;
798  state->widths = NULL;
799  state->precisions = NULL;
800  state->col_names = NULL;
801  state->field_names = NULL;
802  state->num_fields = 0;
803  state->pgfieldtypes = NULL;
804 
805  state->from_srid = config->shp_sr_id;
806  state->to_srid = config->sr_id;
807 
808  /* If only one has a valid SRID, use it for both. */
809  if (state->to_srid == SRID_UNKNOWN)
810  {
811  if (config->geography)
812  {
813  state->to_srid = 4326;
814  }
815  else
816  {
817  state->to_srid = state->from_srid;
818  }
819  }
820 
821  if (state->from_srid == SRID_UNKNOWN)
822  {
823  state->from_srid = state->to_srid;
824  }
825 
826  /* If the geo col name is not set, use one of the defaults. */
827  state->geo_col = config->geo_col;
828 
829  if (!state->geo_col)
830  {
832  }
833 
834  colmap_init(&state->column_map);
835 
836  return state;
837 }
838 
839 
840 /* Open the shapefile and extract the relevant field information */
841 int
843 {
844  SHPObject *obj = NULL;
845  int ret = SHPLOADEROK;
846  char name[MAXFIELDNAMELEN];
848  char *utf8str;
849 
850  /* If we are reading the entire shapefile, open it */
851  if (state->config->readshape == 1)
852  {
853  state->hSHPHandle = SHPOpen(state->config->shp_file, "rb");
854 
855  if (state->hSHPHandle == NULL)
856  {
857  snprintf(state->message, SHPLOADERMSGLEN, _("%s: shape (.shp) or index files (.shx) can not be opened, will just import attribute data."), state->config->shp_file);
858  state->config->readshape = 0;
859 
860  ret = SHPLOADERWARN;
861  }
862  }
863 
864  /* Open the DBF (attributes) file */
865  state->hDBFHandle = DBFOpen(state->config->shp_file, "rb");
866  if ((state->hSHPHandle == NULL && state->config->readshape == 1) || state->hDBFHandle == NULL)
867  {
868  snprintf(state->message, SHPLOADERMSGLEN, _("%s: dbf file (.dbf) can not be opened."), state->config->shp_file);
869 
870  return SHPLOADERERR;
871  }
872 
873 
874  /* Open the column map if one was specified */
875  if (state->config->column_map_filename)
876  {
877  ret = colmap_read(state->config->column_map_filename,
878  &state->column_map, state->message, SHPLOADERMSGLEN);
879  if (!ret) return SHPLOADERERR;
880  }
881 
882  /* User hasn't altered the default encoding preference... */
883  if ( strcmp(state->config->encoding, ENCODING_DEFAULT) == 0 )
884  {
885  /* But the file has a code page entry... */
886  if ( state->hDBFHandle->pszCodePage )
887  {
888  /* And we figured out what iconv encoding it maps to, so use it! */
889  char *newencoding = NULL;
890  if ( (newencoding = codepage2encoding(state->hDBFHandle->pszCodePage)) )
891  {
892  lwfree(state->config->encoding);
893  state->config->encoding = newencoding;
894  }
895  }
896  }
897 
898  /* If reading the whole shapefile (not just attributes)... */
899  if (state->config->readshape == 1)
900  {
901  SHPGetInfo(state->hSHPHandle, &state->num_entities, &state->shpfiletype, NULL, NULL);
902 
903  /* If null_policy is set to abort, check for NULLs */
904  if (state->config->null_policy == POLICY_NULL_ABORT)
905  {
906  /* If we abort on null items, scan the entire file for NULLs */
907  for (int j = 0; j < state->num_entities; j++)
908  {
909  obj = SHPReadObject(state->hSHPHandle, j);
910 
911  if (!obj)
912  {
913  snprintf(state->message, SHPLOADERMSGLEN, _("Error reading shape object %d"), j);
914  return SHPLOADERERR;
915  }
916 
917  if (obj->nVertices == 0)
918  {
919  snprintf(state->message, SHPLOADERMSGLEN, _("Empty geometries found, aborted.)"));
920  return SHPLOADERERR;
921  }
922 
923  SHPDestroyObject(obj);
924  }
925  }
926 
927  /* Check the shapefile type */
928  int geomtype = 0;
929  switch (state->shpfiletype)
930  {
931  case SHPT_POINT:
932  /* Point */
933  state->pgtype = "POINT";
934  geomtype = POINTTYPE;
935  state->pgdims = 2;
936  break;
937 
938  case SHPT_ARC:
939  /* PolyLine */
940  state->pgtype = "MULTILINESTRING";
941  geomtype = MULTILINETYPE ;
942  state->pgdims = 2;
943  break;
944 
945  case SHPT_POLYGON:
946  /* Polygon */
947  state->pgtype = "MULTIPOLYGON";
948  geomtype = MULTIPOLYGONTYPE;
949  state->pgdims = 2;
950  break;
951 
952  case SHPT_MULTIPOINT:
953  /* MultiPoint */
954  state->pgtype = "MULTIPOINT";
955  geomtype = MULTIPOINTTYPE;
956  state->pgdims = 2;
957  break;
958 
959  case SHPT_POINTM:
960  /* PointM */
961  geomtype = POINTTYPE;
962  state->has_m = 1;
963  state->pgtype = "POINTM";
964  state->pgdims = 3;
965  break;
966 
967  case SHPT_ARCM:
968  /* PolyLineM */
969  geomtype = MULTILINETYPE;
970  state->has_m = 1;
971  state->pgtype = "MULTILINESTRINGM";
972  state->pgdims = 3;
973  break;
974 
975  case SHPT_POLYGONM:
976  /* PolygonM */
977  geomtype = MULTIPOLYGONTYPE;
978  state->has_m = 1;
979  state->pgtype = "MULTIPOLYGONM";
980  state->pgdims = 3;
981  break;
982 
983  case SHPT_MULTIPOINTM:
984  /* MultiPointM */
985  geomtype = MULTIPOINTTYPE;
986  state->has_m = 1;
987  state->pgtype = "MULTIPOINTM";
988  state->pgdims = 3;
989  break;
990 
991  case SHPT_POINTZ:
992  /* PointZ */
993  geomtype = POINTTYPE;
994  state->has_m = 1;
995  state->has_z = 1;
996  state->pgtype = "POINT";
997  state->pgdims = 4;
998  break;
999 
1000  case SHPT_ARCZ:
1001  /* PolyLineZ */
1002  state->pgtype = "MULTILINESTRING";
1003  geomtype = MULTILINETYPE;
1004  state->has_z = 1;
1005  state->has_m = 1;
1006  state->pgdims = 4;
1007  break;
1008 
1009  case SHPT_POLYGONZ:
1010  /* MultiPolygonZ */
1011  state->pgtype = "MULTIPOLYGON";
1012  geomtype = MULTIPOLYGONTYPE;
1013  state->has_z = 1;
1014  state->has_m = 1;
1015  state->pgdims = 4;
1016  break;
1017 
1018  case SHPT_MULTIPOINTZ:
1019  /* MultiPointZ */
1020  state->pgtype = "MULTIPOINT";
1021  geomtype = MULTIPOINTTYPE;
1022  state->has_z = 1;
1023  state->has_m = 1;
1024  state->pgdims = 4;
1025  break;
1026 
1027  default:
1028  state->pgtype = "GEOMETRY";
1029  geomtype = COLLECTIONTYPE;
1030  state->has_z = 1;
1031  state->has_m = 1;
1032  state->pgdims = 4;
1033 
1034  snprintf(state->message, SHPLOADERMSGLEN, _("Unknown geometry type: %d\n"), state->shpfiletype);
1035  return SHPLOADERERR;
1036 
1037  break;
1038  }
1039 
1040  /* Force Z/M-handling if configured to do so */
1041  switch(state->config->force_output)
1042  {
1043  case FORCE_OUTPUT_2D:
1044  state->has_z = 0;
1045  state->has_m = 0;
1046  state->pgdims = 2;
1047  break;
1048 
1049  case FORCE_OUTPUT_3DZ:
1050  state->has_z = 1;
1051  state->has_m = 0;
1052  state->pgdims = 3;
1053  break;
1054 
1055  case FORCE_OUTPUT_3DM:
1056  state->has_z = 0;
1057  state->has_m = 1;
1058  state->pgdims = 3;
1059  break;
1060 
1061  case FORCE_OUTPUT_4D:
1062  state->has_z = 1;
1063  state->has_m = 1;
1064  state->pgdims = 4;
1065  break;
1066  default:
1067  /* Simply use the auto-detected values above */
1068  break;
1069  }
1070 
1071  /* If in simple geometry mode, alter names for CREATE TABLE by skipping MULTI */
1072  if (state->config->simple_geometries)
1073  {
1074  if ((geomtype == MULTIPOLYGONTYPE) || (geomtype == MULTILINETYPE) || (geomtype == MULTIPOINTTYPE))
1075  {
1076  /* Chop off the "MULTI" from the string. */
1077  state->pgtype += 5;
1078  }
1079  }
1080 
1081  }
1082  else
1083  {
1084  /* Otherwise just count the number of records in the DBF */
1085  state->num_entities = DBFGetRecordCount(state->hDBFHandle);
1086  }
1087 
1088 
1089  /* Get the field information from the DBF */
1090  state->num_fields = DBFGetFieldCount(state->hDBFHandle);
1091 
1092  state->num_records = DBFGetRecordCount(state->hDBFHandle);
1093 
1094  /* Allocate storage for field information */
1095  state->field_names = malloc(state->num_fields * sizeof(char*));
1096  state->types = (DBFFieldType *)malloc(state->num_fields * sizeof(int));
1097  state->widths = malloc(state->num_fields * sizeof(int));
1098  state->precisions = malloc(state->num_fields * sizeof(int));
1099  state->pgfieldtypes = malloc(state->num_fields * sizeof(char *));
1100  state->col_names = malloc((state->num_fields + 2) * sizeof(char) * MAXFIELDNAMELEN);
1101 
1102  strcpy(state->col_names, "" );
1103  /* Generate a string of comma separated column names of the form "col1, col2 ... colN" for the SQL
1104  insertion string */
1105 
1106  for (int j = 0; j < state->num_fields; j++)
1107  {
1108  int field_precision = 0, field_width = 0;
1109  type = DBFGetFieldInfo(state->hDBFHandle, j, name, &field_width, &field_precision);
1110 
1111  state->types[j] = type;
1112  state->widths[j] = field_width;
1113  state->precisions[j] = field_precision;
1114 /* fprintf(stderr, "XXX %s width:%d prec:%d\n", name, field_width, field_precision); */
1115 
1116  if (state->config->encoding)
1117  {
1118  char *encoding_msg = _("Try \"LATIN1\" (Western European), or one of the values described at http://www.gnu.org/software/libiconv/.");
1119 
1120  int rv = utf8(state->config->encoding, name, &utf8str);
1121 
1122  if (rv != UTF8_GOOD_RESULT)
1123  {
1124  if ( rv == UTF8_BAD_RESULT )
1125  snprintf(state->message, SHPLOADERMSGLEN, _("Unable to convert field name \"%s\" to UTF-8 (iconv reports \"%s\"). Current encoding is \"%s\". %s"), utf8str, strerror(errno), state->config->encoding, encoding_msg);
1126  else if ( rv == UTF8_NO_RESULT )
1127  snprintf(state->message, SHPLOADERMSGLEN, _("Unable to convert field name to UTF-8 (iconv reports \"%s\"). Current encoding is \"%s\". %s"), strerror(errno), state->config->encoding, encoding_msg);
1128  else
1129  snprintf(state->message, SHPLOADERMSGLEN, _("Unexpected return value from utf8()"));
1130 
1131  if ( rv == UTF8_BAD_RESULT )
1132  free(utf8str);
1133 
1134  return SHPLOADERERR;
1135  }
1136 
1137  strncpy(name, utf8str, MAXFIELDNAMELEN);
1138  name[MAXFIELDNAMELEN-1] = '\0';
1139  free(utf8str);
1140  }
1141 
1142  /* If a column map file has been passed in, use this to create the postgresql field name from
1143  the dbf column name */
1144  {
1145  const char *mapped = colmap_pg_by_dbf(&state->column_map, name);
1146  if (mapped)
1147  {
1148  strncpy(name, mapped, MAXFIELDNAMELEN);
1149  name[MAXFIELDNAMELEN-1] = '\0';
1150  }
1151  }
1152 
1153  /*
1154  * Make field names lowercase unless asked to
1155  * keep identifiers case.
1156  */
1157  if (!state->config->quoteidentifiers)
1158  strtolower(name);
1159 
1160  /*
1161  * Escape names starting with the
1162  * escape char (_), those named 'gid'
1163  * or after pgsql reserved attribute names
1164  */
1165  if (name[0] == '_' ||
1166  ! strcmp(name, "gid") ||
1167  ! strcmp(name, "tableoid") ||
1168  ! strcmp(name, "cmin") ||
1169  ! strcmp(name, "cmax") ||
1170  ! strcmp(name, "xmin") ||
1171  ! strcmp(name, "xmax") ||
1172  ! strcmp(name, "primary") ||
1173  ! strcmp(name, "oid") ||
1174  ! strcmp(name, "ctid"))
1175  {
1176  char tmp[MAXFIELDNAMELEN] = "__";
1177  memcpy(tmp+2, name, MAXFIELDNAMELEN-2);
1178  tmp[MAXFIELDNAMELEN-1] = '\0';
1179  }
1180 
1181  /* Avoid duplicating field names */
1182  for (int z = 0; z < j; z++)
1183  {
1184  if (strcmp(state->field_names[z], name) == 0)
1185  {
1186  strncat(name, "__", MAXFIELDNAMELEN - 1);
1187  snprintf(name + strlen(name),
1188  MAXFIELDNAMELEN - 1 - strlen(name),
1189  "%i",
1190  j);
1191  break;
1192  }
1193  }
1194 
1195  state->field_names[j] = strdup(name);
1196 
1197  /* Now generate the PostgreSQL type name string and width based upon the shapefile type */
1198  switch (state->types[j])
1199  {
1200  case FTString:
1201  state->pgfieldtypes[j] = strdup("varchar");
1202  break;
1203 
1204  case FTDate:
1205  state->pgfieldtypes[j] = strdup("date");
1206  break;
1207 
1208  case FTInteger:
1209  /* Determine exact type based upon field width */
1210  if (state->config->forceint4 || (state->widths[j] >=5 && state->widths[j] < 10))
1211  {
1212  state->pgfieldtypes[j] = strdup("int4");
1213  }
1214  else if (state->widths[j] >=10 && state->widths[j] < 19)
1215  {
1216  state->pgfieldtypes[j] = strdup("int8");
1217  }
1218  else if (state->widths[j] < 5)
1219  {
1220  state->pgfieldtypes[j] = strdup("int2");
1221  }
1222  else
1223  {
1224  state->pgfieldtypes[j] = strdup("numeric");
1225  }
1226  break;
1227 
1228  case FTDouble:
1229  /* Determine exact type based upon field width */
1230  fprintf(stderr, "Field %s is an FTDouble with width %d and precision %d\n",
1231  state->field_names[j], state->widths[j], state->precisions[j]);
1232  if (state->widths[j] > 18)
1233  {
1234  state->pgfieldtypes[j] = strdup("numeric");
1235  }
1236  else
1237  {
1238  state->pgfieldtypes[j] = strdup("float8");
1239  }
1240  break;
1241 
1242  case FTLogical:
1243  state->pgfieldtypes[j] = strdup("boolean");
1244  break;
1245 
1246  default:
1247  snprintf(state->message, SHPLOADERMSGLEN, _("Invalid type %x in DBF file"), state->types[j]);
1248  return SHPLOADERERR;
1249  }
1250 
1251  strcat(state->col_names, "\"");
1252  strcat(state->col_names, name);
1253 
1254  if (state->config->readshape == 1 || j < (state->num_fields - 1))
1255  {
1256  /* Don't include last comma if its the last field and no geometry field will follow */
1257  strcat(state->col_names, "\",");
1258  }
1259  else
1260  {
1261  strcat(state->col_names, "\"");
1262  }
1263  }
1264 
1265  /* Append the geometry column if required */
1266  if (state->config->readshape == 1)
1267  strcat(state->col_names, state->geo_col);
1268 
1269  /* Return status */
1270  return ret;
1271 }
1272 
1273 /* Return a pointer to an allocated string containing the header for the specified loader state */
1274 int
1275 ShpLoaderGetSQLHeader(SHPLOADERSTATE *state, char **strheader)
1276 {
1277  stringbuffer_t *sb;
1278  char *ret;
1279  int j;
1280 
1281  /* Create the stringbuffer containing the header; we use this API as it's easier
1282  for handling string resizing during append */
1283  sb = stringbuffer_create();
1284  stringbuffer_clear(sb);
1285 
1286  /* Set the client encoding if required */
1287  if (state->config->encoding)
1288  {
1289  stringbuffer_aprintf(sb, "SET CLIENT_ENCODING TO UTF8;\n");
1290  }
1291 
1292  /* Use SQL-standard string escaping rather than PostgreSQL standard */
1293  stringbuffer_aprintf(sb, "SET STANDARD_CONFORMING_STRINGS TO ON;\n");
1294 
1295  /* Drop table if requested */
1296  if (state->config->opt == 'd')
1297  {
1309  if (state->config->schema)
1310  {
1311  if (state->config->readshape == 1 && (! state->config->geography) )
1312  {
1313  stringbuffer_aprintf(sb, "SELECT DropGeometryColumn('%s','%s','%s');\n",
1314  state->config->schema, state->config->table, state->geo_col);
1315  }
1316 
1317  stringbuffer_aprintf(sb, "DROP TABLE IF EXISTS \"%s\".\"%s\";\n", state->config->schema,
1318  state->config->table);
1319  }
1320  else
1321  {
1322  if (state->config->readshape == 1 && (! state->config->geography) )
1323  {
1324  stringbuffer_aprintf(sb, "SELECT DropGeometryColumn('','%s','%s');\n",
1325  state->config->table, state->geo_col);
1326  }
1327 
1328  stringbuffer_aprintf(sb, "DROP TABLE IF EXISTS \"%s\";\n", state->config->table);
1329  }
1330  }
1331 
1332  /* Start of transaction if we are using one */
1333  if (state->config->usetransaction)
1334  {
1335  stringbuffer_aprintf(sb, "BEGIN;\n");
1336  }
1337 
1338  /* If not in 'append' mode create the spatial table */
1339  if (state->config->opt != 'a')
1340  {
1341  /*
1342  * Create a table for inserting the shapes into with appropriate
1343  * columns and types
1344  */
1345  if (state->config->schema)
1346  {
1347  stringbuffer_aprintf(sb, "CREATE TABLE \"%s\".\"%s\" (gid serial",
1348  state->config->schema, state->config->table);
1349  }
1350  else
1351  {
1352  stringbuffer_aprintf(sb, "CREATE TABLE \"%s\" (gid serial", state->config->table);
1353  }
1354 
1355  /* Generate the field types based upon the shapefile information */
1356  for (j = 0; j < state->num_fields; j++)
1357  {
1358  stringbuffer_aprintf(sb, ",\n\"%s\" ", state->field_names[j]);
1359 
1360  /* First output the raw field type string */
1361  stringbuffer_aprintf(sb, "%s", state->pgfieldtypes[j]);
1362 
1363  /* Some types do have typmods */
1364  /* Apply width typmod for varchar if there is positive width **/
1365  if (!strcmp("varchar", state->pgfieldtypes[j]) && state->widths[j] > 0)
1366  stringbuffer_aprintf(sb, "(%d)", state->widths[j]);
1367 
1368  if (!strcmp("numeric", state->pgfieldtypes[j]))
1369  {
1370  /* Doubles we just allow PostgreSQL to auto-detect the size */
1371  if (state->types[j] != FTDouble)
1372  stringbuffer_aprintf(sb, "(%d,0)", state->widths[j]);
1373  }
1374  }
1375 
1376  /* Add the geography column directly to the table definition, we don't
1377  need to do an AddGeometryColumn() call. */
1378  if (state->config->readshape == 1 && state->config->geography)
1379  {
1380  char *dimschar;
1381 
1382  if (state->pgdims == 4)
1383  dimschar = "ZM";
1384  else
1385  dimschar = "";
1386 
1387  if (state->to_srid == SRID_UNKNOWN ){
1388  state->to_srid = 4326;
1389  }
1390 
1391  stringbuffer_aprintf(sb, ",\n\"%s\" geography(%s%s,%d)", state->geo_col, state->pgtype, dimschar, state->to_srid);
1392  }
1393  stringbuffer_aprintf(sb, ")");
1394 
1395  /* Tablespace is optional. */
1396  if (state->config->tablespace != NULL)
1397  {
1398  stringbuffer_aprintf(sb, " TABLESPACE \"%s\"", state->config->tablespace);
1399  }
1400  stringbuffer_aprintf(sb, ";\n");
1401 
1402  /* Create the primary key. This is done separately because the index for the PK needs
1403  * to be in the correct tablespace. */
1404 
1405  /* TODO: Currently PostgreSQL does not allow specifying an index to use for a PK (so you get
1406  * a default one called table_pkey) and it does not provide a way to create a PK index
1407  * in a specific tablespace. So as a hacky solution we create the PK, then move the
1408  * index to the correct tablespace. Eventually this should be:
1409  * CREATE INDEX table_pkey on table(gid) TABLESPACE tblspc;
1410  * ALTER TABLE table ADD PRIMARY KEY (gid) USING INDEX table_pkey;
1411  * A patch has apparently been submitted to PostgreSQL to enable this syntax, see this thread:
1412  * http://archives.postgresql.org/pgsql-hackers/2011-01/msg01405.php */
1413  stringbuffer_aprintf(sb, "ALTER TABLE ");
1414 
1415  /* Schema is optional, include if present. */
1416  if (state->config->schema)
1417  {
1418  stringbuffer_aprintf(sb, "\"%s\".",state->config->schema);
1419  }
1420  stringbuffer_aprintf(sb, "\"%s\" ADD PRIMARY KEY (gid);\n", state->config->table);
1421 
1422  /* Tablespace is optional for the index. */
1423  if (state->config->idxtablespace != NULL)
1424  {
1425  stringbuffer_aprintf(sb, "ALTER INDEX ");
1426  if (state->config->schema)
1427  {
1428  stringbuffer_aprintf(sb, "\"%s\".",state->config->schema);
1429  }
1430 
1431  /* WARNING: We're assuming the default "table_pkey" name for the primary
1432  * key index. PostgreSQL may use "table_pkey1" or similar in the
1433  * case of a name conflict, so you may need to edit the produced
1434  * SQL in this rare case. */
1435  stringbuffer_aprintf(sb, "\"%s_pkey\" SET TABLESPACE \"%s\";\n",
1436  state->config->table, state->config->idxtablespace);
1437  }
1438 
1439  /* Create the geometry column with an addgeometry call */
1440  if (state->config->readshape == 1 && (!state->config->geography))
1441  {
1442  /* If they didn't specify a target SRID, see if they specified a source SRID. */
1443  int32_t srid = state->to_srid;
1444  if (state->config->schema)
1445  {
1446  stringbuffer_aprintf(sb, "SELECT AddGeometryColumn('%s','%s','%s','%d',",
1447  state->config->schema, state->config->table, state->geo_col, srid);
1448  }
1449  else
1450  {
1451  stringbuffer_aprintf(sb, "SELECT AddGeometryColumn('','%s','%s','%d',",
1452  state->config->table, state->geo_col, srid);
1453  }
1454 
1455  stringbuffer_aprintf(sb, "'%s',%d);\n", state->pgtype, state->pgdims);
1456  }
1457  }
1458 
1462  if (state->config->dump_format && state->to_srid != state->from_srid){
1464  stringbuffer_aprintf(sb, "CREATE TEMP TABLE \"pgis_tmp_%s\" AS SELECT * FROM ", state->config->table);
1465  /* Schema is optional, include if present. */
1466  if (state->config->schema)
1467  {
1468  stringbuffer_aprintf(sb, "\"%s\".",state->config->schema);
1469  }
1470  stringbuffer_aprintf(sb, "\"%s\" WHERE false;\n", state->config->table, state->geo_col);
1472  stringbuffer_aprintf(sb, "ALTER TABLE \"pgis_tmp_%s\" ALTER COLUMN \"%s\" TYPE geometry USING ( (\"%s\"::geometry) ); \n", state->config->table, state->geo_col, state->geo_col);
1473  }
1474 
1475  /* Copy the string buffer into a new string, destroying the string buffer */
1476  ret = (char *)malloc(strlen((char *)stringbuffer_getstring(sb)) + 1);
1477  strcpy(ret, (char *)stringbuffer_getstring(sb));
1479 
1480  *strheader = ret;
1481 
1482  return SHPLOADEROK;
1483 }
1484 
1485 
1486 /* Return an allocated string containing the copy statement for this state */
1487 int
1489 {
1490  //char *copystr;
1491  stringbuffer_t *sb;
1492  char *ret;
1493  sb = stringbuffer_create();
1494  stringbuffer_clear(sb);
1495 
1496 
1497  /* Allocate the string for the COPY statement */
1498  if (state->config->dump_format)
1499  {
1500  stringbuffer_aprintf(sb, "COPY ");
1501 
1502  if (state->to_srid != state->from_srid){
1504  stringbuffer_aprintf(sb, " \"pgis_tmp_%s\" (%s) FROM stdin;\n", state->config->table, state->col_names);
1505  }
1506  else {
1507  if (state->config->schema)
1508  {
1509  stringbuffer_aprintf(sb, " \"%s\".", state->config->schema);
1510  }
1511 
1512  stringbuffer_aprintf(sb, "\"%s\" (%s) FROM stdin;\n", state->config->table, state->col_names);
1513  }
1514 
1515  /* Copy the string buffer into a new string, destroying the string buffer */
1516  ret = (char *)malloc(strlen((char *)stringbuffer_getstring(sb)) + 1);
1517  strcpy(ret, (char *)stringbuffer_getstring(sb));
1519 
1520  *strheader = ret;
1521  return SHPLOADEROK;
1522  }
1523  else
1524  {
1525  /* Flag an error as something has gone horribly wrong */
1526  snprintf(state->message, SHPLOADERMSGLEN, _("Internal error: attempt to generate a COPY statement for data that hasn't been requested in COPY format"));
1527 
1528  return SHPLOADERERR;
1529  }
1530 }
1531 
1532 
1533 /* Return a count of the number of entities in this shapefile */
1534 int
1536 {
1537  return state->num_entities;
1538 }
1539 
1540 
1541 /* Return an allocated string representation of a specified record item */
1542 int
1543 ShpLoaderGenerateSQLRowStatement(SHPLOADERSTATE *state, int item, char **strrecord)
1544 {
1545  SHPObject *obj = NULL;
1546  stringbuffer_t *sb;
1547  stringbuffer_t *sbwarn;
1548  char val[MAXVALUELEN];
1549  char *escval;
1550  char *geometry=NULL, *ret;
1551  char *utf8str;
1552  int res, i;
1553  int rv;
1554 
1555  /* Clear the stringbuffers */
1556  sbwarn = stringbuffer_create();
1557  stringbuffer_clear(sbwarn);
1558  sb = stringbuffer_create();
1559  stringbuffer_clear(sb);
1560 
1561  /* Skip deleted records */
1562  if (state->hDBFHandle && DBFIsRecordDeleted(state->hDBFHandle, item))
1563  {
1564  *strrecord = NULL;
1565  return SHPLOADERRECDELETED;
1566  }
1567 
1568  /* If we are reading the shapefile, open the specified record */
1569  if (state->config->readshape == 1)
1570  {
1571  obj = SHPReadObject(state->hSHPHandle, item);
1572  if (!obj)
1573  {
1574  snprintf(state->message, SHPLOADERMSGLEN, _("Error reading shape object %d"), item);
1575  return SHPLOADERERR;
1576  }
1577 
1578  /* If we are set to skip NULLs, return a NULL record status */
1579  if (state->config->null_policy == POLICY_NULL_SKIP && obj->nVertices == 0 )
1580  {
1581  SHPDestroyObject(obj);
1582 
1583  *strrecord = NULL;
1584  return SHPLOADERRECISNULL;
1585  }
1586  }
1587 
1588  /* If not in dump format, generate the INSERT string */
1589  if (!state->config->dump_format)
1590  {
1591  if (state->config->schema)
1592  {
1593  stringbuffer_aprintf(sb, "INSERT INTO \"%s\".\"%s\" (%s) VALUES (", state->config->schema,
1594  state->config->table, state->col_names);
1595  }
1596  else
1597  {
1598  stringbuffer_aprintf(sb, "INSERT INTO \"%s\" (%s) VALUES (", state->config->table,
1599  state->col_names);
1600  }
1601  }
1602 
1603 
1604  /* Read all of the attributes from the DBF file for this item */
1605  for (i = 0; i < DBFGetFieldCount(state->hDBFHandle); i++)
1606  {
1607  /* Special case for NULL attributes */
1608  if (DBFIsAttributeNULL(state->hDBFHandle, item, i))
1609  {
1610  if (state->config->dump_format)
1611  stringbuffer_aprintf(sb, "\\N");
1612  else
1613  stringbuffer_aprintf(sb, "NULL");
1614  }
1615  else
1616  {
1617  /* Attribute NOT NULL */
1618  switch (state->types[i])
1619  {
1620  case FTInteger:
1621  case FTDouble:
1622  rv = snprintf(val, MAXVALUELEN, "%s", DBFReadStringAttribute(state->hDBFHandle, item, i));
1623  if (rv >= MAXVALUELEN || rv == -1)
1624  {
1625  stringbuffer_aprintf(sbwarn, "Warning: field %d name truncated\n", i);
1626  val[MAXVALUELEN - 1] = '\0';
1627  }
1628 
1629  /* If the value is an empty string, change to 0 */
1630  if (val[0] == '\0')
1631  {
1632  val[0] = '0';
1633  val[1] = '\0';
1634  }
1635 
1636  /* If the value ends with just ".", remove the dot */
1637  if (val[strlen(val) - 1] == '.')
1638  val[strlen(val) - 1] = '\0';
1639  break;
1640 
1641  case FTString:
1642  case FTLogical:
1643  rv = snprintf(val, MAXVALUELEN, "%s", DBFReadStringAttribute(state->hDBFHandle, item, i));
1644  if (rv >= MAXVALUELEN || rv == -1)
1645  {
1646  stringbuffer_aprintf(sbwarn, "Warning: field %d name truncated\n", i);
1647  val[MAXVALUELEN - 1] = '\0';
1648  }
1649  break;
1650 
1651  case FTDate:
1652  rv = snprintf(val, MAXVALUELEN, "%s", DBFReadStringAttribute(state->hDBFHandle, item, i));
1653  if (rv >= MAXVALUELEN || rv == -1)
1654  {
1655  stringbuffer_aprintf(sbwarn, "Warning: field %d name truncated\n", i);
1656  val[MAXVALUELEN - 1] = '\0';
1657  }
1658  if (strlen(val) == 0)
1659  {
1660  if (state->config->dump_format)
1661  stringbuffer_aprintf(sb, "\\N");
1662  else
1663  stringbuffer_aprintf(sb, "NULL");
1664  goto done_cell;
1665  }
1666  break;
1667 
1668  default:
1669  snprintf(state->message, SHPLOADERMSGLEN, _("Error: field %d has invalid or unknown field type (%d)"), i, state->types[i]);
1670 
1671  /* clean up and return err */
1672  SHPDestroyObject(obj);
1673  stringbuffer_destroy(sbwarn);
1675  return SHPLOADERERR;
1676  }
1677 
1678  if (state->config->encoding)
1679  {
1680  char *encoding_msg = _("Try \"LATIN1\" (Western European), or one of the values described at http://www.postgresql.org/docs/current/static/multibyte.html.");
1681 
1682  rv = utf8(state->config->encoding, val, &utf8str);
1683 
1684  if (rv != UTF8_GOOD_RESULT)
1685  {
1686  if ( rv == UTF8_BAD_RESULT )
1687  snprintf(state->message, SHPLOADERMSGLEN, _("Unable to convert data value \"%s\" to UTF-8 (iconv reports \"%s\"). Current encoding is \"%s\". %s"), utf8str, strerror(errno), state->config->encoding, encoding_msg);
1688  else if ( rv == UTF8_NO_RESULT )
1689  snprintf(state->message, SHPLOADERMSGLEN, _("Unable to convert data value to UTF-8 (iconv reports \"%s\"). Current encoding is \"%s\". %s"), strerror(errno), state->config->encoding, encoding_msg);
1690  else
1691  snprintf(state->message, SHPLOADERMSGLEN, _("Unexpected return value from utf8()"));
1692 
1693  if ( rv == UTF8_BAD_RESULT )
1694  free(utf8str);
1695 
1696  /* clean up and return err */
1697  SHPDestroyObject(obj);
1698  stringbuffer_destroy(sbwarn);
1700  return SHPLOADERERR;
1701  }
1702  strncpy(val, utf8str, MAXVALUELEN);
1703  val[MAXVALUELEN-1] = '\0';
1704  free(utf8str);
1705 
1706  }
1707 
1708  /* Escape attribute correctly according to dump format */
1709  if (state->config->dump_format)
1710  {
1711  escval = escape_copy_string(val);
1712  stringbuffer_aprintf(sb, "%s", escval);
1713  }
1714  else
1715  {
1716  escval = escape_insert_string(val);
1717  stringbuffer_aprintf(sb, "'%s'", escval);
1718  }
1719 
1720  /* Free the escaped version if required */
1721  if (val != escval)
1722  free(escval);
1723  }
1724 
1725 done_cell:
1726 
1727  /* Only put in delimeter if not last field or a shape will follow */
1728  if (state->config->readshape == 1 || i < DBFGetFieldCount(state->hDBFHandle) - 1)
1729  {
1730  if (state->config->dump_format)
1731  stringbuffer_aprintf(sb, "\t");
1732  else
1733  stringbuffer_aprintf(sb, ",");
1734  }
1735 
1736  /* End of DBF attribute loop */
1737  }
1738 
1739 
1740  /* Add the shape attribute if we are reading it */
1741  if (state->config->readshape == 1)
1742  {
1743  /* Force the locale to C */
1744  char *oldlocale = setlocale(LC_NUMERIC, "C");
1745 
1746  /* Handle the case of a NULL shape */
1747  if (obj->nVertices == 0)
1748  {
1749  if (state->config->dump_format)
1750  stringbuffer_aprintf(sb, "\\N");
1751  else
1752  stringbuffer_aprintf(sb, "NULL");
1753  }
1754  else
1755  {
1756  /* Handle all other shape attributes */
1757  switch (obj->nSHPType)
1758  {
1759  case SHPT_POLYGON:
1760  case SHPT_POLYGONM:
1761  case SHPT_POLYGONZ:
1762  res = GeneratePolygonGeometry(state, obj, &geometry);
1763  break;
1764 
1765  case SHPT_POINT:
1766  case SHPT_POINTM:
1767  case SHPT_POINTZ:
1768  res = GeneratePointGeometry(state, obj, &geometry, 0);
1769  break;
1770 
1771  case SHPT_MULTIPOINT:
1772  case SHPT_MULTIPOINTM:
1773  case SHPT_MULTIPOINTZ:
1774  /* Force it to multi unless using -S */
1775  res = GeneratePointGeometry(state, obj, &geometry,
1776  state->config->simple_geometries ? 0 : 1);
1777  break;
1778 
1779  case SHPT_ARC:
1780  case SHPT_ARCM:
1781  case SHPT_ARCZ:
1782  res = GenerateLineStringGeometry(state, obj, &geometry);
1783  break;
1784 
1785  default:
1786  snprintf(state->message, SHPLOADERMSGLEN, _("Shape type is not supported, type id = %d"), obj->nSHPType);
1787  SHPDestroyObject(obj);
1788  stringbuffer_destroy(sbwarn);
1790 
1791  return SHPLOADERERR;
1792  }
1793  /* The default returns out of the function, so res will always have been set. */
1794  if (res != SHPLOADEROK)
1795  {
1796  /* Error message has already been set */
1797  SHPDestroyObject(obj);
1798  stringbuffer_destroy(sbwarn);
1800 
1801  return SHPLOADERERR;
1802  }
1803 
1804  /* Now generate the geometry string according to the current configuration */
1805  if (!state->config->dump_format)
1806  {
1807  if (state->to_srid != state->from_srid)
1808  {
1809  stringbuffer_aprintf(sb, "ST_Transform(");
1810  }
1811  stringbuffer_aprintf(sb, "'");
1812  }
1813 
1814  stringbuffer_aprintf(sb, "%s", geometry);
1815 
1816  if (!state->config->dump_format)
1817  {
1818  stringbuffer_aprintf(sb, "'");
1819 
1820  /* Close the ST_Transform if reprojecting. */
1821  if (state->to_srid != state->from_srid)
1822  {
1823  /* We need to add an explicit cast to geography/geometry to ensure that
1824  PostgreSQL doesn't get confused with the ST_Transform() raster
1825  function. */
1826  if (state->config->geography)
1827  stringbuffer_aprintf(sb, "::geometry, %d)::geography", state->to_srid);
1828  else
1829  stringbuffer_aprintf(sb, "::geometry, %d)", state->to_srid);
1830  }
1831  }
1832 
1833  // free(geometry);
1834  }
1835 
1836  /* Tidy up everything */
1837  SHPDestroyObject(obj);
1838 
1839  setlocale(LC_NUMERIC, oldlocale);
1840  }
1841 
1842  /* Close the line correctly for dump/insert format */
1843  if (!state->config->dump_format)
1844  stringbuffer_aprintf(sb, ");");
1845 
1846 
1847  /* Copy the string buffer into a new string, destroying the string buffer */
1848  ret = (char *)malloc(strlen((char *)stringbuffer_getstring(sb)) + 1);
1849  strcpy(ret, (char *)stringbuffer_getstring(sb));
1851 
1852  *strrecord = ret;
1853 
1854  /* If any warnings occurred, set the returned message string and warning status */
1855  if (strlen((char *)stringbuffer_getstring(sbwarn)) > 0)
1856  {
1857  snprintf(state->message, SHPLOADERMSGLEN, "%s", stringbuffer_getstring(sbwarn));
1858  stringbuffer_destroy(sbwarn);
1859 
1860  return SHPLOADERWARN;
1861  }
1862  else
1863  {
1864  /* Everything went okay */
1865  stringbuffer_destroy(sbwarn);
1866 
1867  return SHPLOADEROK;
1868  }
1869 }
1870 
1871 
1872 /* Return a pointer to an allocated string containing the header for the specified loader state */
1873 int
1874 ShpLoaderGetSQLFooter(SHPLOADERSTATE *state, char **strfooter)
1875 {
1876  stringbuffer_t *sb;
1877  char *ret;
1878 
1879  /* Create the stringbuffer containing the header; we use this API as it's easier
1880  for handling string resizing during append */
1881  sb = stringbuffer_create();
1882  stringbuffer_clear(sb);
1883 
1884  if ( state->config->dump_format && state->to_srid != state->from_srid){
1886  stringbuffer_aprintf(sb, "ALTER TABLE \"pgis_tmp_%s\" ALTER COLUMN \"%s\" TYPE ", state->config->table, state->geo_col);
1887  if (state->config->geography){
1888  stringbuffer_aprintf(sb, "geography USING (ST_Transform(\"%s\", %d)::geography );\n", state->geo_col, state->to_srid);
1889  }
1890  else {
1891  stringbuffer_aprintf(sb, "geometry USING (ST_Transform(\"%s\", %d)::geometry );\n", state->geo_col, state->to_srid);
1892  }
1893  stringbuffer_aprintf(sb, "INSERT INTO ");
1894  // /* Schema is optional, include if present. */
1895  if (state->config->schema)
1896  {
1897  stringbuffer_aprintf(sb, "\"%s\".", state->config->schema);
1898  }
1899  stringbuffer_aprintf(sb, "\"%s\" (%s) ", state->config->table, state->col_names);
1900  stringbuffer_aprintf(sb, "SELECT %s FROM \"pgis_tmp_%s\";\n", state->col_names, state->config->table);
1901  }
1902 
1903  /* Create gist index if specified and not in "prepare" mode */
1904  if (state->config->readshape && state->config->createindex)
1905  {
1906  stringbuffer_aprintf(sb, "CREATE INDEX ON ");
1907  /* Schema is optional, include if present. */
1908  if (state->config->schema)
1909  {
1910  stringbuffer_aprintf(sb, "\"%s\".",state->config->schema);
1911  }
1912  stringbuffer_aprintf(sb, "\"%s\" USING GIST (\"%s\")", state->config->table, state->geo_col);
1913  /* Tablespace is also optional. */
1914  if (state->config->idxtablespace != NULL)
1915  {
1916  stringbuffer_aprintf(sb, " TABLESPACE \"%s\"", state->config->idxtablespace);
1917  }
1918  stringbuffer_aprintf(sb, ";\n");
1919  }
1920 
1921  /* End the transaction if there is one. */
1922  if (state->config->usetransaction)
1923  {
1924  stringbuffer_aprintf(sb, "COMMIT;\n");
1925  }
1926 
1927 
1928  if(state->config->analyze)
1929  {
1930  /* Always ANALYZE the resulting table, for better stats */
1931  stringbuffer_aprintf(sb, "ANALYZE ");
1932  if (state->config->schema)
1933  {
1934  stringbuffer_aprintf(sb, "\"%s\".", state->config->schema);
1935  }
1936  stringbuffer_aprintf(sb, "\"%s\";\n", state->config->table);
1937  }
1938 
1939  /* Copy the string buffer into a new string, destroying the string buffer */
1940  ret = (char *)malloc(strlen((char *)stringbuffer_getstring(sb)) + 1);
1941  strcpy(ret, (char *)stringbuffer_getstring(sb));
1943 
1944  *strfooter = ret;
1945 
1946  return SHPLOADEROK;
1947 }
1948 
1949 
1950 void
1952 {
1953  /* Destroy a state object created with ShpLoaderOpenShape */
1954  int i;
1955  if (state != NULL)
1956  {
1957  if (state->hSHPHandle)
1958  SHPClose(state->hSHPHandle);
1959  if (state->hDBFHandle)
1960  DBFClose(state->hDBFHandle);
1961  if (state->field_names)
1962  {
1963  for (i = 0; i < state->num_fields; i++)
1964  free(state->field_names[i]);
1965 
1966  free(state->field_names);
1967  }
1968  if (state->pgfieldtypes)
1969  {
1970  for (i = 0; i < state->num_fields; i++)
1971  free(state->pgfieldtypes[i]);
1972 
1973  free(state->pgfieldtypes);
1974  }
1975  if (state->types)
1976  free(state->types);
1977  if (state->widths)
1978  free(state->widths);
1979  if (state->precisions)
1980  free(state->precisions);
1981  if (state->col_names)
1982  free(state->col_names);
1983 
1984  /* Free any column map fieldnames if specified */
1985  colmap_clean(&state->column_map);
1986 
1987  /* Free the state itself */
1988  free(state);
1989  }
1990 }
char * s
Definition: cu_in_wkt.c:23
char result[OUT_DOUBLE_BUFFER_SIZE]
Definition: cu_print.c:262
int SHPAPI_CALL DBFGetFieldCount(DBFHandle psDBF)
Definition: dbfopen.c:1237
DBFHandle SHPAPI_CALL DBFOpen(const char *pszFilename, const char *pszAccess)
Definition: dbfopen.c:351
int SHPAPI_CALL DBFGetRecordCount(DBFHandle psDBF)
Definition: dbfopen.c:1250
void SHPAPI_CALL DBFClose(DBFHandle psDBF)
Definition: dbfopen.c:599
int SHPAPI_CALL DBFIsAttributeNULL(DBFHandle psDBF, int iRecord, int iField)
Definition: dbfopen.c:1217
int SHPAPI_CALL DBFIsRecordDeleted(DBFHandle psDBF, int iShape)
Definition: dbfopen.c:1741
const char SHPAPI_CALL1 * DBFReadStringAttribute(DBFHandle psDBF, int iRecord, int iField){ return STATIC_CAST(const char *, DBFReadAttribute(psDBF, iRecord, iField, 'C')
DBFFieldType SHPAPI_CALL DBFGetFieldInfo(DBFHandle psDBF, int iField, char *pszFieldName, int *pnWidth, int *pnDecimals)
Definition: dbfopen.c:1265
LWPOINT * lwpoint_construct_empty(int32_t srid, char hasz, char hasm)
Definition: lwpoint.c:151
LWGEOM * lwline_as_lwgeom(const LWLINE *obj)
Definition: lwgeom.c:339
#define LW_FALSE
Definition: liblwgeom.h:94
LWGEOM * lwcollection_as_lwgeom(const LWCOLLECTION *obj)
Definition: lwgeom.c:309
#define COLLECTIONTYPE
Definition: liblwgeom.h:108
void lwgeom_free(LWGEOM *geom)
Definition: lwgeom.c:1155
#define MULTILINETYPE
Definition: liblwgeom.h:106
#define WKT_EXTENDED
Definition: liblwgeom.h:2186
LWGEOM * lwpoly_as_lwgeom(const LWPOLY *obj)
Definition: lwgeom.c:329
#define MULTIPOINTTYPE
Definition: liblwgeom.h:105
char * lwgeom_to_hexwkb_buffer(const LWGEOM *geom, uint8_t variant)
Definition: lwout_wkb.c:845
int lwpoly_add_ring(LWPOLY *poly, POINTARRAY *pa)
Add a ring, allocating extra space if necessary.
Definition: lwpoly.c:247
#define POINTTYPE
LWTYPE numbers, used internally by PostGIS.
Definition: liblwgeom.h:102
LWLINE * lwline_construct(int32_t srid, GBOX *bbox, POINTARRAY *points)
Definition: lwline.c:42
#define MULTIPOLYGONTYPE
Definition: liblwgeom.h:107
void lwfree(void *mem)
Definition: lwutil.c:242
LWGEOM * lwpoint_as_lwgeom(const LWPOINT *obj)
Definition: lwgeom.c:344
LWPOINT * lwpoint_construct(int32_t srid, GBOX *bbox, POINTARRAY *point)
Definition: lwpoint.c:129
#define WKB_EXTENDED
Definition: liblwgeom.h:2177
POINTARRAY * ptarray_construct_empty(char hasz, char hasm, uint32_t maxpoints)
Create a new POINTARRAY with no points.
Definition: ptarray.c:59
char * lwgeom_to_wkt(const LWGEOM *geom, uint8_t variant, int precision, size_t *size_out)
WKT emitter function.
Definition: lwout_wkt.c:708
int ptarray_append_point(POINTARRAY *pa, const POINT4D *pt, int allow_duplicates)
Append a point to the end of an existing POINTARRAY If allow_duplicate is LW_FALSE,...
Definition: ptarray.c:147
LWCOLLECTION * lwcollection_construct(uint8_t type, int32_t srid, GBOX *bbox, uint32_t ngeoms, LWGEOM **geoms)
Definition: lwcollection.c:42
#define LW_TRUE
Return types for functions with status returns.
Definition: liblwgeom.h:93
#define FLAGS_SET_M(flags, value)
Definition: liblwgeom.h:173
#define SRID_UNKNOWN
Unknown SRID value.
Definition: liblwgeom.h:215
#define FLAGS_SET_Z(flags, value)
Definition: liblwgeom.h:172
LWPOLY * lwpoly_construct_empty(int32_t srid, char hasz, char hasm)
Definition: lwpoly.c:161
#define str(s)
#define LWDEBUGF(level, msg,...)
Definition: lwgeom_log.h:88
void * malloc(YYSIZE_T)
void free(void *)
type
Definition: ovdump.py:42
tuple res
Definition: window.py:79
#define SHPT_ARCZ
Definition: shapefil.h:354
DBFFieldType
Definition: shapefil.h:638
@ FTDouble
Definition: shapefil.h:641
@ FTString
Definition: shapefil.h:639
@ FTInvalid
Definition: shapefil.h:644
@ FTLogical
Definition: shapefil.h:642
@ FTDate
Definition: shapefil.h:643
@ FTInteger
Definition: shapefil.h:640
SHPObject SHPAPI_CALL1 * SHPReadObject(SHPHandle hSHP, int iShape);int SHPAPI_CALL SHPWriteObject(SHPHandle hSHP, int iShape, SHPObject *psObject
Definition: shpopen.c:1831
#define SHPT_ARCM
Definition: shapefil.h:358
#define SHPT_POLYGONM
Definition: shapefil.h:359
#define SHPT_ARC
Definition: shapefil.h:350
void SHPAPI_CALL SHPClose(SHPHandle hSHP)
Definition: shpopen.c:879
#define SHPT_POLYGON
Definition: shapefil.h:351
void SHPAPI_CALL SHPDestroyObject(SHPObject *psObject)
Definition: shpopen.c:2641
SHPHandle SHPAPI_CALL SHPOpen(const char *pszShapeFile, const char *pszAccess)
Definition: shpopen.c:291
#define SHPT_MULTIPOINT
Definition: shapefil.h:352
void SHPAPI_CALL SHPGetInfo(SHPHandle hSHP, int *pnEntities, int *pnShapeType, double *padfMinBound, double *padfMaxBound)
Definition: shpopen.c:947
#define SHPT_POINTZ
Definition: shapefil.h:353
#define SHPT_MULTIPOINTZ
Definition: shapefil.h:356
#define SHPT_MULTIPOINTM
Definition: shapefil.h:360
#define SHPT_POINTM
Definition: shapefil.h:357
#define SHPT_POINT
Definition: shapefil.h:349
#define SHPT_POLYGONZ
Definition: shapefil.h:355
static int utf8(const char *fromcode, char *inputbuf, char **outputbuf)
int GeneratePointGeometry(SHPLOADERSTATE *state, SHPObject *obj, char **geometry, int force_multi)
Generate an allocated geometry string for shapefile object obj using the state parameters if "force_m...
struct struct_ring Ring
int ShpLoaderGetRecordCount(SHPLOADERSTATE *state)
int PIP(Point P, Point *V, int n)
PIP(): crossing number test for a point in a polygon input: P = a point, V[] = vertex points of a pol...
char * escape_insert_string(char *str)
Escape input string suitable for INSERT.
#define UTF8_GOOD_RESULT
#define UTF8_BAD_RESULT
int GeneratePolygonGeometry(SHPLOADERSTATE *state, SHPObject *obj, char **geometry)
Generate an allocated geometry string for shapefile object obj using the state parameters.
int FindPolygons(SHPObject *obj, Ring ***Out)
void strtolower(char *s)
void ShpLoaderDestroy(SHPLOADERSTATE *state)
char * escape_copy_string(char *str)
Escape input string suitable for COPY.
int ShpLoaderGetSQLCopyStatement(SHPLOADERSTATE *state, char **strheader)
int ShpLoaderOpenShape(SHPLOADERSTATE *state)
void ReleasePolygons(Ring **polys, int npolys)
int ShpLoaderGenerateSQLRowStatement(SHPLOADERSTATE *state, int item, char **strrecord)
#define UTF8_NO_RESULT
void set_loader_config_defaults(SHPLOADERCONFIG *config)
int ShpLoaderGetSQLFooter(SHPLOADERSTATE *state, char **strfooter)
struct struct_point Point
SHPLOADERSTATE * ShpLoaderCreate(SHPLOADERCONFIG *config)
int GenerateLineStringGeometry(SHPLOADERSTATE *state, SHPObject *obj, char **geometry)
Generate an allocated geometry string for shapefile object obj using the state parameters.
int ShpLoaderGetSQLHeader(SHPLOADERSTATE *state, char **strheader)
#define FORCE_OUTPUT_4D
#define WKT_PRECISION
#define POLICY_NULL_ABORT
#define GEOGRAPHY_DEFAULT
#define FORCE_OUTPUT_2D
#define SHPLOADERRECISNULL
#define SHPLOADERWARN
#define FORCE_OUTPUT_3DM
#define POLICY_NULL_SKIP
#define POLICY_NULL_INSERT
#define ENCODING_DEFAULT
#define FORCE_OUTPUT_DISABLE
#define SHPLOADERMSGLEN
#define GEOMETRY_DEFAULT
#define SHPLOADERRECDELETED
#define MAXVALUELEN
#define SHPLOADERERR
#define MAXFIELDNAMELEN
#define SHPLOADEROK
#define FORCE_OUTPUT_3DZ
int colmap_read(const char *filename, colmap *map, char *errbuf, size_t errbuflen)
Read the content of filename into a symbol map.
Definition: shpcommon.c:217
void colmap_init(colmap *map)
Definition: shpcommon.c:163
const char * colmap_pg_by_dbf(colmap *map, const char *dbfname)
Definition: shpcommon.c:203
void colmap_clean(colmap *map)
Definition: shpcommon.c:171
char * codepage2encoding(const char *cpg)
Definition: shpcommon.c:292
#define _(String)
Definition: shpcommon.h:24
void stringbuffer_clear(stringbuffer_t *s)
Reset the stringbuffer_t.
Definition: stringbuffer.c:97
int stringbuffer_aprintf(stringbuffer_t *s, const char *fmt,...)
Appends a formatted string to the current string buffer, using the format and argument list provided.
Definition: stringbuffer.c:247
stringbuffer_t * stringbuffer_create(void)
Allocate a new stringbuffer_t.
Definition: stringbuffer.c:33
void stringbuffer_destroy(stringbuffer_t *s)
Free the stringbuffer_t and all memory managed within it.
Definition: stringbuffer.c:85
const char * stringbuffer_getstring(stringbuffer_t *s)
Returns a reference to the internal string being managed by the stringbuffer.
Definition: stringbuffer.c:122
char * pszCodePage
Definition: shapefil.h:625
double m
Definition: liblwgeom.h:414
double x
Definition: liblwgeom.h:414
double z
Definition: liblwgeom.h:414
double y
Definition: liblwgeom.h:414
char message[SHPLOADERMSGLEN]
DBFFieldType * types
SHPHandle hSHPHandle
DBFHandle hDBFHandle
SHPLOADERCONFIG * config
Point * list
unsigned int linked
struct struct_ring * next
double * padfX
Definition: shapefil.h:390
int nVertices
Definition: shapefil.h:389
double * padfY
Definition: shapefil.h:391
int nSHPType
Definition: shapefil.h:381
double * padfZ
Definition: shapefil.h:392
int * panPartStart
Definition: shapefil.h:386
double * padfM
Definition: shapefil.h:393