PostGIS  3.3.9dev-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  setlocale (LC_ALL, "");
90  bindtextdomain (PACKAGE, PGSQL_LOCALEDIR);
91  textdomain (PACKAGE);
92 #endif
93 
94  /* If no options are specified, display usage */
95  if (argc == 1)
96  {
97  usage();
98  exit(0);
99  }
100 
101  /* Parse command line options and set configuration */
102  config = malloc(sizeof(SHPLOADERCONFIG));
104 
105  /* Keep the flag list alphabetic so it's easy to see what's left. */
106  while ((c = pgis_getopt(argc, argv, "-acdeg:ikm:nps:t:wDGIN:ST:W:X:Z")) != EOF)
107  {
108  // can not do this inside the switch case
109  if ('-' == c)
110  break;
111 
112  switch (c)
113  {
114  case 'c':
115  case 'd':
116  case 'a':
117  case 'p':
118  config->opt = c;
119  break;
120 
121  case 'D':
122  config->dump_format = 1;
123  break;
124 
125  case 'G':
126  config->geography = 1;
127  break;
128 
129  case 'Z':
130  config->analyze = 0;
131  break;
132 
133  case 'S':
134  config->simple_geometries = 1;
135  break;
136 
137  case 's':
138  if (pgis_optarg)
139  {
140  char *ptr = strchr(pgis_optarg, ':');
141  if (ptr)
142  {
143  *ptr++ = '\0';
144  sscanf(pgis_optarg, "%d", &config->shp_sr_id);
145  sscanf(ptr, "%d", &config->sr_id);
146  }
147  else
148  {
149  /* Only TO_SRID specified */
150  sscanf(pgis_optarg, "%d", &config->sr_id);
151  }
152  }
153  else
154  {
155  /* With -s, user must specify TO_SRID or FROM_SRID:TO_SRID */
156  fprintf(stderr, "The -s parameter must be specified in the form [FROM_SRID:]TO_SRID\n");
157  exit(1);
158  }
159  break;
160  case 'g':
161  config->geo_col = pgis_optarg;
162  break;
163  case 'm':
165  break;
166 
167  case 'k':
168  config->quoteidentifiers = 1;
169  break;
170 
171  case 'i':
172  config->forceint4 = 1;
173  break;
174 
175  case 'I':
176  config->createindex = 1;
177  break;
178 
179  case 'w':
180  config->use_wkt = 1;
181  break;
182 
183  case 'n':
184  config->readshape = 0;
185  break;
186 
187  case 'W':
188  config->encoding = strdup(pgis_optarg);
189  break;
190 
191  case 'N':
192  switch (pgis_optarg[0])
193  {
194  case 'a':
195  config->null_policy = POLICY_NULL_ABORT;
196  break;
197  case 'i':
199  break;
200  case 's':
201  config->null_policy = POLICY_NULL_SKIP;
202  break;
203  default:
204  fprintf(stderr, "Unsupported NULL geometry handling policy.\nValid policies: insert, skip, abort\n");
205  exit(1);
206  }
207  break;
208 
209  case 't':
210  if (strcasecmp(pgis_optarg, "2D") == 0)
211  {
212  config->force_output = FORCE_OUTPUT_2D;
213  }
214  else if (strcasecmp(pgis_optarg, "3DZ") == 0 )
215  {
216  config->force_output = FORCE_OUTPUT_3DZ;
217  }
218  else if (strcasecmp(pgis_optarg, "3DM") == 0 )
219  {
220  config->force_output = FORCE_OUTPUT_3DM;
221  }
222  else if (strcasecmp(pgis_optarg, "4D") == 0 )
223  {
224  config->force_output = FORCE_OUTPUT_4D;
225  }
226  else
227  {
228  fprintf(stderr, "Unsupported output type: %s\nValid output types are 2D, 3DZ, 3DM and 4D\n", pgis_optarg);
229  exit(1);
230  }
231  break;
232 
233  case 'T':
234  config->tablespace = pgis_optarg;
235  break;
236 
237  case 'X':
238  config->idxtablespace = pgis_optarg;
239  break;
240 
241  case 'e':
242  config->usetransaction = 0;
243  break;
244 
245  case '?':
246  usage();
247  exit(0);
248 
249  default:
250  usage();
251  exit(0);
252  }
253  }
254 
255  /* Once we have parsed the arguments, make sure certain combinations are valid */
256  if (config->dump_format && !config->usetransaction)
257  {
258  fprintf(stderr, "Invalid argument combination - cannot use both -D and -e\n");
259  exit(1);
260  }
261 
262  /* Determine the shapefile name from the next argument, if no shape file, exit. */
263  if (pgis_optind < argc)
264  {
265  config->shp_file = argv[pgis_optind];
266  pgis_optind++;
267  }
268  else
269  {
270  usage();
271  exit(0);
272  }
273 
274  /* Determine the table and schema names from the next argument */
275  if (pgis_optind < argc)
276  {
277  char *strptr = argv[pgis_optind];
278  char *chrptr = strchr(strptr, '.');
279 
280  /* OK, this is a schema-qualified table name... */
281  if (chrptr)
282  {
283  if ( chrptr == strptr )
284  {
285  /* ".something" ??? */
286  usage();
287  exit(0);
288  }
289  /* Null terminate at the '.' */
290  *chrptr = '\0';
291  /* Copy in the parts */
292  config->schema = strdup(strptr);
293  config->table = strdup(chrptr+1);
294  }
295  else
296  {
297  config->table = strdup(strptr);
298  }
299  }
300 
301  /* If the table parameter is not provided, use the shape file name as a proxy value.
302  Strip out the .shp and the leading path information first. */
303  if ( config->shp_file && config->table == NULL)
304  {
305  char *shp_file = strdup(config->shp_file);
306  char *ptr;
307 
308  /* Remove the extension, if present */
309  for ( ptr = shp_file + strlen(shp_file); ptr > shp_file; ptr-- )
310  {
311  if ( *ptr == '.' )
312  {
313  *ptr = '\0';
314  break;
315  }
316  }
317 
318  /* The remaining non-path section is the table name */
319  for ( ptr = shp_file + strlen(shp_file); ptr > shp_file; ptr-- )
320  {
321  if ( *ptr == '/' || *ptr == '\\' )
322  {
323  ptr++;
324  break;
325  }
326  }
327  config->table = strdup(ptr);
328  free(shp_file);
329  }
330 
331 
332  /* Transform table name to lower case if no quoting specified */
333  if (!config->quoteidentifiers)
334  {
335  if ( config->table )
336  strtolower(config->table);
337  if ( config->schema )
338  strtolower(config->schema);
339  }
340 
341  /* Create the shapefile state object */
342  state = ShpLoaderCreate(config);
343 
344  /* Open the shapefile */
345  ret = ShpLoaderOpenShape(state);
346  if (ret != SHPLOADEROK)
347  {
348  fprintf(stderr, "%s\n", state->message);
349 
350  if (ret == SHPLOADERERR)
351  exit(1);
352  }
353 
354  /* If reading the whole shapefile, display its type */
355  if (state->config->readshape)
356  {
357  fprintf(stderr, "Shapefile type: %s\n", SHPTypeName(state->shpfiletype));
358  fprintf(stderr, "Postgis type: %s[%d]\n", state->pgtype, state->pgdims);
359  }
360 
361  /* Print the header to stdout */
362  ret = ShpLoaderGetSQLHeader(state, &header);
363  if (ret != SHPLOADEROK)
364  {
365  fprintf(stderr, "%s\n", state->message);
366 
367  if (ret == SHPLOADERERR)
368  exit(1);
369  }
370 
371  printf("%s", header);
372  free(header);
373 
374  /* If we are not in "prepare" mode, go ahead and write out the data. */
375  if ( state->config->opt != 'p' )
376  {
377 
378  /* If in COPY mode, output the COPY statement */
379  if (state->config->dump_format)
380  {
381  ret = ShpLoaderGetSQLCopyStatement(state, &header);
382  if (ret != SHPLOADEROK)
383  {
384  fprintf(stderr, "%s\n", state->message);
385 
386  if (ret == SHPLOADERERR)
387  exit(1);
388  }
389 
390  printf("%s", header);
391  free(header);
392  }
393 
394  /* Main loop: iterate through all of the records and send them to stdout */
395  for (i = 0; i < ShpLoaderGetRecordCount(state); i++)
396  {
397  ret = ShpLoaderGenerateSQLRowStatement(state, i, &record);
398 
399  switch (ret)
400  {
401  case SHPLOADEROK:
402  /* Simply display the geometry */
403  printf("%s\n", record);
404  free(record);
405  break;
406 
407  case SHPLOADERERR:
408  /* Display the error message then stop */
409  fprintf(stderr, "%s\n", state->message);
410  exit(1);
411  break;
412 
413  case SHPLOADERWARN:
414  /* Display the warning, but continue */
415  fprintf(stderr, "%s\n", state->message);
416  printf("%s\n", record);
417  free(record);
418  break;
419 
420  case SHPLOADERRECDELETED:
421  /* Record is marked as deleted - ignore */
422  break;
423 
424  case SHPLOADERRECISNULL:
425  /* Record is NULL and should be ignored according to NULL policy */
426  break;
427  }
428  }
429 
430  /* If in COPY mode, terminate the COPY statement */
431  if (state->config->dump_format)
432  printf("\\.\n");
433 
434  }
435 
436  /* Print the footer to stdout */
437  ret = ShpLoaderGetSQLFooter(state, &footer);
438  if (ret != SHPLOADEROK)
439  {
440  fprintf(stderr, "%s\n", state->message);
441 
442  if (ret == SHPLOADERERR)
443  exit(1);
444  }
445 
446  printf("%s", footer);
447  free(footer);
448 
449 
450  /* Free the state object */
451  ShpLoaderDestroy(state);
452 
453  /* Free configuration variables */
454  if (config->schema)
455  free(config->schema);
456  if (config->table)
457  free(config->table);
458  if (config->encoding)
459  free(config->encoding);
460  free(config);
461 
462  return 0;
463 }
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:230
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