PostGIS  3.4.0dev-r@@SVN_REVISION@@
shp2pgsql-cli.c
Go to the documentation of this file.
1 /**********************************************************************
2  *
3  * PostGIS - Spatial Types for PostgreSQL
4  * http://www.postgis.org
5  * Copyright 2008 OpenGeo.org
6  * Copyright 2009 Mark Cave-Ayland <mark.cave-ayland@siriusit.co.uk>
7  *
8  * This is free software; you can redistribute and/or modify it under
9  * the terms of the GNU General Public Licence. See the COPYING file.
10  *
11  * Maintainer: Paul Ramsey <pramsey@opengeo.org>
12  *
13  **********************************************************************/
14 
15 #include "../postgis_config.h"
16 
17 #include "shp2pgsql-core.h"
18 #include "../liblwgeom/liblwgeom.h" /* for SRID_UNKNOWN */
19 
20 #define xstr(s) str(s)
21 #define str(s) #s
22 
23 static void
25 {
26  printf(_( "RELEASE: %s (%s)\n" ),
27  POSTGIS_LIB_VERSION, xstr(POSTGIS_REVISION));
28  printf(_( "USAGE: shp2pgsql [<options>] <shapefile> [[<schema>.]<table>]\n"
29  "OPTIONS:\n" ));
30  printf(_( " -s [<from>:]<srid> Set the SRID field. Defaults to %d.\n"
31  " Optionally reprojects from given SRID.\n"),
32  SRID_UNKNOWN);
33  printf(_( " (-d|a|c|p) These are mutually exclusive options:\n"
34  " -d Drops the table, then recreates it and populates\n"
35  " it with current shape file data.\n"
36  " -a Appends shape file into current table, must be\n"
37  " exactly the same table schema.\n"
38  " -c Creates a new table and populates it, this is the\n"
39  " default if you do not specify any options.\n"
40  " -p Prepare mode, only creates the table.\n" ));
41  printf(_( " -g <geocolumn> Specify the name of the geometry/geography column\n"
42  " (mostly useful in append mode).\n" ));
43  printf(_( " -D Use postgresql dump format (defaults to SQL insert statements).\n" ));
44  printf(_( " -e Execute each statement individually, do not use a transaction.\n"
45  " Not compatible with -D.\n" ));
46  printf(_( " -G Use geography type (requires lon/lat data or -s to reproject).\n" ));
47  printf(_( " -k Keep postgresql identifiers case.\n" ));
48  printf(_( " -i Use int4 type for all integer dbf fields.\n" ));
49  printf(_( " -I Create a spatial index on the geocolumn.\n" ));
50  printf(_(" -m <filename> Specify a file containing a set of mappings of (long) column\n"
51  " names to 10 character DBF column names. The content of the file is one or\n"
52  " more lines of two names separated by white space and no trailing or\n"
53  " leading space. For example:\n"
54  " COLUMNNAME DBFFIELD1\n"
55  " AVERYLONGCOLUMNNAME DBFFIELD2\n" ));
56  printf(_( " -S Generate simple geometries instead of MULTI geometries.\n" ));
57  printf(_( " -t <dimensionality> Force geometry to be one of '2D', '3DZ', '3DM', or '4D'\n" ));
58 
59  printf(_( " -w Output WKT instead of WKB. Note that this can result in\n"
60  " coordinate drift.\n" ));
61  printf(_( " -W <encoding> Specify the character encoding of Shape's\n"
62  " attribute column. (default: \"UTF-8\")\n" ));
63  printf(_( " -N <policy> NULL geometries handling policy (insert*,skip,abort).\n" ));
64  printf(_( " -n Only import DBF file.\n" ));
65  printf(_( " -T <tablespace> Specify the tablespace for the new table.\n"
66  " Note that indexes will still use the default tablespace unless the\n"
67  " -X flag is also used.\n"));
68  printf(_( " -X <tablespace> Specify the tablespace for the table's indexes.\n"
69  " This applies to the primary key, and the spatial index if\n"
70  " the -I flag is used.\n" ));
71  printf(_( " -Z Prevent tables from being analyzed.\n" ));
72  printf(_( " -? Display this help screen.\n" ));
73  printf( "\n" );
74  printf(_( " An argument of `--' disables further option processing.\n" ));
75  printf(_( " (useful for unusual file names starting with '-')\n" ));
76 }
77 
78 
79 int
80 main (int argc, char **argv)
81 {
82  SHPLOADERCONFIG *config;
83  SHPLOADERSTATE *state;
84  char *header, *footer, *record;
85  int c;
86  int ret, i;
87 
88 #ifdef ENABLE_NLS
89 #ifdef PGSQL_LOCALEDIR
90  setlocale (LC_ALL, "");
91  bindtextdomain (PACKAGE, PGSQL_LOCALEDIR);
92  textdomain (PACKAGE);
93 #endif
94 #endif
95 
96  /* If no options are specified, display usage */
97  if (argc == 1)
98  {
99  usage();
100  exit(0);
101  }
102 
103  /* Parse command line options and set configuration */
104  config = malloc(sizeof(SHPLOADERCONFIG));
106 
107  /* Keep the flag list alphabetic so it's easy to see what's left. */
108  while ((c = pgis_getopt(argc, argv, "-acdeg:ikm:nps:t:wDGIN:ST:W:X:Z")) != EOF)
109  {
110  // can not do this inside the switch case
111  if ('-' == c)
112  break;
113 
114  switch (c)
115  {
116  case 'c':
117  case 'd':
118  case 'a':
119  case 'p':
120  config->opt = c;
121  break;
122 
123  case 'D':
124  config->dump_format = 1;
125  break;
126 
127  case 'G':
128  config->geography = 1;
129  break;
130 
131  case 'Z':
132  config->analyze = 0;
133  break;
134 
135  case 'S':
136  config->simple_geometries = 1;
137  break;
138 
139  case 's':
140  if (pgis_optarg)
141  {
142  char *ptr = strchr(pgis_optarg, ':');
143  if (ptr)
144  {
145  *ptr++ = '\0';
146  sscanf(pgis_optarg, "%d", &config->shp_sr_id);
147  sscanf(ptr, "%d", &config->sr_id);
148  }
149  else
150  {
151  /* Only TO_SRID specified */
152  sscanf(pgis_optarg, "%d", &config->sr_id);
153  }
154  }
155  else
156  {
157  /* With -s, user must specify TO_SRID or FROM_SRID:TO_SRID */
158  fprintf(stderr, "The -s parameter must be specified in the form [FROM_SRID:]TO_SRID\n");
159  exit(1);
160  }
161  break;
162  case 'g':
163  config->geo_col = pgis_optarg;
164  break;
165  case 'm':
167  break;
168 
169  case 'k':
170  config->quoteidentifiers = 1;
171  break;
172 
173  case 'i':
174  config->forceint4 = 1;
175  break;
176 
177  case 'I':
178  config->createindex = 1;
179  break;
180 
181  case 'w':
182  config->use_wkt = 1;
183  break;
184 
185  case 'n':
186  config->readshape = 0;
187  break;
188 
189  case 'W':
190  config->encoding = strdup(pgis_optarg);
191  break;
192 
193  case 'N':
194  switch (pgis_optarg[0])
195  {
196  case 'a':
197  config->null_policy = POLICY_NULL_ABORT;
198  break;
199  case 'i':
201  break;
202  case 's':
203  config->null_policy = POLICY_NULL_SKIP;
204  break;
205  default:
206  fprintf(stderr, "Unsupported NULL geometry handling policy.\nValid policies: insert, skip, abort\n");
207  exit(1);
208  }
209  break;
210 
211  case 't':
212  if (strcasecmp(pgis_optarg, "2D") == 0)
213  {
214  config->force_output = FORCE_OUTPUT_2D;
215  }
216  else if (strcasecmp(pgis_optarg, "3DZ") == 0 )
217  {
218  config->force_output = FORCE_OUTPUT_3DZ;
219  }
220  else if (strcasecmp(pgis_optarg, "3DM") == 0 )
221  {
222  config->force_output = FORCE_OUTPUT_3DM;
223  }
224  else if (strcasecmp(pgis_optarg, "4D") == 0 )
225  {
226  config->force_output = FORCE_OUTPUT_4D;
227  }
228  else
229  {
230  fprintf(stderr, "Unsupported output type: %s\nValid output types are 2D, 3DZ, 3DM and 4D\n", pgis_optarg);
231  exit(1);
232  }
233  break;
234 
235  case 'T':
236  config->tablespace = pgis_optarg;
237  break;
238 
239  case 'X':
240  config->idxtablespace = pgis_optarg;
241  break;
242 
243  case 'e':
244  config->usetransaction = 0;
245  break;
246 
247  case '?':
248  usage();
249  exit(0);
250 
251  default:
252  usage();
253  exit(0);
254  }
255  }
256 
257  /* Once we have parsed the arguments, make sure certain combinations are valid */
258  if (config->dump_format && !config->usetransaction)
259  {
260  fprintf(stderr, "Invalid argument combination - cannot use both -D and -e\n");
261  exit(1);
262  }
263 
264  /* Determine the shapefile name from the next argument, if no shape file, exit. */
265  if (pgis_optind < argc)
266  {
267  config->shp_file = argv[pgis_optind];
268  pgis_optind++;
269  }
270  else
271  {
272  usage();
273  exit(0);
274  }
275 
276  /* Determine the table and schema names from the next argument */
277  if (pgis_optind < argc)
278  {
279  char *strptr = argv[pgis_optind];
280  char *chrptr = strchr(strptr, '.');
281 
282  /* OK, this is a schema-qualified table name... */
283  if (chrptr)
284  {
285  if ( chrptr == strptr )
286  {
287  /* ".something" ??? */
288  usage();
289  exit(0);
290  }
291  /* Null terminate at the '.' */
292  *chrptr = '\0';
293  /* Copy in the parts */
294  config->schema = strdup(strptr);
295  config->table = strdup(chrptr+1);
296  }
297  else
298  {
299  config->table = strdup(strptr);
300  }
301  }
302 
303  /* If the table parameter is not provided, use the shape file name as a proxy value.
304  Strip out the .shp and the leading path information first. */
305  if ( config->shp_file && config->table == NULL)
306  {
307  char *shp_file = strdup(config->shp_file);
308  char *ptr;
309 
310  /* Remove the extension, if present */
311  for ( ptr = shp_file + strlen(shp_file); ptr > shp_file; ptr-- )
312  {
313  if ( *ptr == '.' )
314  {
315  *ptr = '\0';
316  break;
317  }
318  }
319 
320  /* The remaining non-path section is the table name */
321  for ( ptr = shp_file + strlen(shp_file); ptr > shp_file; ptr-- )
322  {
323  if ( *ptr == '/' || *ptr == '\\' )
324  {
325  ptr++;
326  break;
327  }
328  }
329  config->table = strdup(ptr);
330  free(shp_file);
331  }
332 
333 
334  /* Transform table name to lower case if no quoting specified */
335  if (!config->quoteidentifiers)
336  {
337  if ( config->table )
338  strtolower(config->table);
339  if ( config->schema )
340  strtolower(config->schema);
341  }
342 
343  /* Create the shapefile state object */
344  state = ShpLoaderCreate(config);
345 
346  /* Open the shapefile */
347  ret = ShpLoaderOpenShape(state);
348  if (ret != SHPLOADEROK)
349  {
350  fprintf(stderr, "%s\n", state->message);
351 
352  if (ret == SHPLOADERERR)
353  exit(1);
354  }
355 
356  /* If reading the whole shapefile, display its type */
357  if (state->config->readshape)
358  {
359  fprintf(stderr, "Shapefile type: %s\n", SHPTypeName(state->shpfiletype));
360  fprintf(stderr, "Postgis type: %s[%d]\n", state->pgtype, state->pgdims);
361  }
362 
363  /* Print the header to stdout */
364  ret = ShpLoaderGetSQLHeader(state, &header);
365  if (ret != SHPLOADEROK)
366  {
367  fprintf(stderr, "%s\n", state->message);
368 
369  if (ret == SHPLOADERERR)
370  exit(1);
371  }
372 
373  printf("%s", header);
374  free(header);
375 
376  /* If we are not in "prepare" mode, go ahead and write out the data. */
377  if ( state->config->opt != 'p' )
378  {
379 
380  /* If in COPY mode, output the COPY statement */
381  if (state->config->dump_format)
382  {
383  ret = ShpLoaderGetSQLCopyStatement(state, &header);
384  if (ret != SHPLOADEROK)
385  {
386  fprintf(stderr, "%s\n", state->message);
387 
388  if (ret == SHPLOADERERR)
389  exit(1);
390  }
391 
392  printf("%s", header);
393  free(header);
394  }
395 
396  /* Main loop: iterate through all of the records and send them to stdout */
397  for (i = 0; i < ShpLoaderGetRecordCount(state); i++)
398  {
399  ret = ShpLoaderGenerateSQLRowStatement(state, i, &record);
400 
401  switch (ret)
402  {
403  case SHPLOADEROK:
404  /* Simply display the geometry */
405  printf("%s\n", record);
406  free(record);
407  break;
408 
409  case SHPLOADERERR:
410  /* Display the error message then stop */
411  fprintf(stderr, "%s\n", state->message);
412  exit(1);
413  break;
414 
415  case SHPLOADERWARN:
416  /* Display the warning, but continue */
417  fprintf(stderr, "%s\n", state->message);
418  printf("%s\n", record);
419  free(record);
420  break;
421 
422  case SHPLOADERRECDELETED:
423  /* Record is marked as deleted - ignore */
424  break;
425 
426  case SHPLOADERRECISNULL:
427  /* Record is NULL and should be ignored according to NULL policy */
428  break;
429  }
430  }
431 
432  /* If in COPY mode, terminate the COPY statement */
433  if (state->config->dump_format)
434  printf("\\.\n");
435 
436  }
437 
438  /* Print the footer to stdout */
439  ret = ShpLoaderGetSQLFooter(state, &footer);
440  if (ret != SHPLOADEROK)
441  {
442  fprintf(stderr, "%s\n", state->message);
443 
444  if (ret == SHPLOADERERR)
445  exit(1);
446  }
447 
448  printf("%s", footer);
449  free(footer);
450 
451 
452  /* Free the state object */
453  ShpLoaderDestroy(state);
454 
455  /* Free configuration variables */
456  if (config->schema)
457  free(config->schema);
458  if (config->table)
459  free(config->table);
460  if (config->encoding)
461  free(config->encoding);
462  free(config);
463 
464  return 0;
465 }
int pgis_optind
Definition: getopt.c:39
int pgis_getopt(int argc, char **argv, char *opts)
Definition: getopt.c:44
char * pgis_optarg
Definition: getopt.c:41
int main(int argc, char *argv[])
#define SRID_UNKNOWN
Unknown SRID value.
Definition: liblwgeom.h:215
void * malloc(YYSIZE_T)
void free(void *)
const char SHPAPI_CALL1 * SHPTypeName(int nSHPType);const char SHPAPI_CALL1(*) SHPPartTypeName(int nPartType
Definition: shpopen.c:2551
static void usage()
Definition: shp2pgsql-cli.c:24
#define xstr(s)
Definition: shp2pgsql-cli.c:20
int ShpLoaderGetRecordCount(SHPLOADERSTATE *state)
void strtolower(char *s)
void ShpLoaderDestroy(SHPLOADERSTATE *state)
int ShpLoaderGetSQLCopyStatement(SHPLOADERSTATE *state, char **strheader)
int ShpLoaderOpenShape(SHPLOADERSTATE *state)
int ShpLoaderGenerateSQLRowStatement(SHPLOADERSTATE *state, int item, char **strrecord)
void set_loader_config_defaults(SHPLOADERCONFIG *config)
int ShpLoaderGetSQLFooter(SHPLOADERSTATE *state, char **strfooter)
SHPLOADERSTATE * ShpLoaderCreate(SHPLOADERCONFIG *config)
int ShpLoaderGetSQLHeader(SHPLOADERSTATE *state, char **strheader)
#define FORCE_OUTPUT_4D
#define POLICY_NULL_ABORT
#define FORCE_OUTPUT_2D
#define SHPLOADERRECISNULL
#define SHPLOADERWARN
#define FORCE_OUTPUT_3DM
#define POLICY_NULL_SKIP
#define POLICY_NULL_INSERT
#define SHPLOADERRECDELETED
#define SHPLOADERERR
#define SHPLOADEROK
#define FORCE_OUTPUT_3DZ
#define _(String)
Definition: shpcommon.h:24
#define POSTGIS_LIB_VERSION
Definition: sqldefines.h:13
char message[SHPLOADERMSGLEN]
SHPLOADERCONFIG * config