1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
|
/**********************************************************************
* $Id: shp2pgsql.c 2764 2008-04-12 16:44:55Z pramsey $
*
* PostGIS - Spatial Types for PostgreSQL
* http://postgis.refractions.net
* Copyright 2001-2003 Refractions Research Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of hte GNU General Public Licence. See the COPYING file.
*
**********************************************************************
* Using shapelib 1.2.8, this program reads in shape files and
* processes it's contents into a Insert statements which can be
* easily piped into a database frontend.
* Specifically designed to insert type 'geometry' (a custom
* written PostgreSQL type) for the shape files and PostgreSQL
* standard types for all attributes of the entity.
*
* Original Author: Jeff Lounsbury, jeffloun@refractions.net
*
* Maintainer: Sandro Santilli, strk@refractions.net
*
**********************************************************************/
#include "../config.h"
#include "shapefil.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include "getopt.h"
#ifdef HAVE_ICONV_H
#include <iconv.h>
#endif
#define POINTTYPE 1
#define LINETYPE 2
#define POLYGONTYPE 3
#define MULTIPOINTTYPE 4
#define MULTILINETYPE 5
#define MULTIPOLYGONTYPE 6
#define COLLECTIONTYPE 7
#define WKBZOFFSET 0x80000000
#define WKBMOFFSET 0x40000000
/*#define DEBUG 1 */
typedef struct {double x, y, z, m;} Point;
typedef struct Ring {
Point *list; /* list of points */
struct Ring *next;
int n; /* number of points in list */
unsigned int linked; /* number of "next" rings */
} Ring;
/* Values for null_policy global */
enum {
insert_null,
skip_null,
abort_on_null
};
/* globals */
int dump_format = 0; /* 0=insert statements, 1 = dump */
int simple_geometries = 0; /* 0 = MULTILINESTRING/MULTIPOLYGON, 1 = LINESTRING/POLYGON */
int quoteidentifiers = 0;
int forceint4 = 0;
int createindex = 0;
int readshape = 1;
char opt = ' ';
char *col_names = NULL;
char *pgtype;
int istypeM = 0;
int pgdims;
unsigned int wkbtype;
char *shp_file = NULL;
int hwgeom = 0; /* old (hwgeom) mode */
#ifdef USE_ICONV
char *encoding=NULL;
#endif
int null_policy = insert_null;
DBFFieldType *types; /* Fields type, width and precision */
SHPHandle hSHPHandle;
DBFHandle hDBFHandle;
int shpfiletype;
SHPObject *obj=NULL;
int *widths;
int *precisions;
char *table=NULL,*schema=NULL,*geom=NULL;
int num_fields,num_records,num_entities;
char **field_names;
int sr_id = 0;
/* Prototypes */
int Insert_attributes(DBFHandle hDBFHandle, int row);
char *make_good_string(char *str);
char *protect_quotes_string(char *str);
int PIP( Point P, Point* V, int n );
void *safe_malloc(size_t size);
void CreateTable(void);
void CreateIndex(void);
void usage(char *me, int exitcode, FILE* out);
void InsertPoint(void);
void InsertPointWKT(void);
void InsertMultiPoint(void);
void InsertPolygon(void);
void InsertPolygonWKT(void);
void InsertLineString(int id);
void InsertLineStringWKT(int id);
int ParseCmdline(int ARGC, char **ARGV);
void SetPgType(void);
char *dump_ring(Ring *ring);
#ifdef USE_ICONV
char *utf8(const char *fromcode, char *inputbuf);
#endif
int FindPolygons(SHPObject *obj, Ring ***Out);
void ReleasePolygons(Ring **polys, int npolys);
void DropTable(char *schema, char *table, char *geom);
void GetFieldsSpec(void);
void LoadData(void);
void OpenShape(void);
void LowerCase(char *s);
void Cleanup(void);
/* WKB */
static char getEndianByte(void);
static void print_wkb_bytes(unsigned char* ptr, unsigned int cnt, size_t size);
static void print_wkb_byte(unsigned char val);
static void print_wkb_int(int val);
static void print_wkb_double(double val);
static char rcsid[] =
"$Id: shp2pgsql.c 2764 2008-04-12 16:44:55Z pramsey $";
void *safe_malloc(size_t size)
{
void *ret = malloc(size);
if ( ! ret ) {
fprintf(stderr, "Out of virtual memory\n");
exit(1);
}
return ret;
}
#define malloc(x) safe_malloc(x)
char *
make_good_string(char *str)
{
/*
* find all the tabs and make them \<tab>s
*
* 1. find # of tabs
* 2. make new string
*
* we dont escape already escaped tabs
*/
char *result;
char *ptr, *optr;
int toescape = 0;
size_t size;
#ifdef USE_ICONV
char *utf8str=NULL;
if ( encoding )
{
utf8str=utf8(encoding, str);
if ( ! utf8str ) exit(1);
str = utf8str;
}
#endif
ptr = str;
while (*ptr) {
if ( *ptr == '\t' || *ptr == '\\' ) toescape++;
ptr++;
}
if (toescape == 0) return str;
size = ptr-str+toescape+1;
result = calloc(1, size);
optr=result;
ptr=str;
while (*ptr) {
if ( *ptr == '\t' || *ptr == '\\' ) *optr++='\\';
*optr++=*ptr++;
}
*optr='\0';
#ifdef USE_ICONV
if ( encoding ) free(str);
#endif
return result;
}
char *
protect_quotes_string(char *str)
{
/*
* find all quotes and make them \quotes
* find all '\' and make them '\\'
*
* 1. find # of characters
* 2. make new string
*/
char *result;
char *ptr, *optr;
int toescape = 0;
size_t size;
#ifdef USE_ICONV
char *utf8str=NULL;
if ( encoding )
{
utf8str=utf8(encoding, str);
if ( ! utf8str ) exit(1);
str = utf8str;
}
#endif
ptr = str;
while (*ptr) {
if ( *ptr == '\'' || *ptr == '\\' ) toescape++;
ptr++;
}
if (toescape == 0) return str;
size = ptr-str+toescape+1;
result = calloc(1, size);
optr=result;
ptr=str;
while (*ptr) {
if ( *ptr == '\\' ) *optr++='\\';
if ( *ptr == '\'') *optr++='\'';
*optr++=*ptr++;
}
*optr='\0';
#ifdef USE_ICONV
if ( encoding ) free(str);
#endif
return result;
}
/*
* PIP(): crossing number test for a point in a polygon
* input: P = a point,
* V[] = vertex points of a polygon V[n+1] with V[n]=V[0]
* returns: 0 = outside, 1 = inside
*/
int
PIP( Point P, Point* V, int n )
{
int cn = 0; /* the crossing number counter */
int i;
/* loop through all edges of the polygon */
for (i=0; i<n-1; i++) { /* edge from V[i] to V[i+1] */
if (((V[i].y <= P.y) && (V[i+1].y > P.y)) /* an upward crossing */
|| ((V[i].y > P.y) && (V[i+1].y <= P.y))) { /* a downward crossing */
double vt = (float)(P.y - V[i].y) / (V[i+1].y - V[i].y);
if (P.x < V[i].x + vt * (V[i+1].x - V[i].x)) /* P.x < intersect */
++cn; /* a valid crossing of y=P.y right of P.x */
}
}
return (cn&1); /* 0 if even (out), and 1 if odd (in) */
}
/*Insert the attributes from the correct row of dbf file */
int
Insert_attributes(DBFHandle hDBFHandle, int row)
{
int i,num_fields;
char val[1024];
char *escval;
num_fields = DBFGetFieldCount( hDBFHandle );
for( i = 0; i < num_fields; i++ )
{
if(DBFIsAttributeNULL( hDBFHandle, row, i))
{
if(dump_format)
{
printf("\\N");
//printf("\t");
}
else
{
printf("NULL");
//printf(",");
}
}
else /* Attribute NOT NULL */
{
switch (types[i])
{
case FTInteger:
case FTDouble:
if ( -1 == snprintf(val, 1024, "%s",
DBFReadStringAttribute(hDBFHandle, row, i)) )
{
fprintf(stderr, "Warning: field %d name truncated\n", i);
val[1023] = '\0';
}
/* pg_atoi() does not do this */
if ( val[0] == '\0' ) { val[0] = '0'; val[1] = '\0'; }
if ( val[strlen(val)-1] == '.' ) val[strlen(val)-1] = '\0';
break;
case FTString:
case FTLogical:
case FTDate:
if ( -1 == snprintf(val, 1024, "%s",
DBFReadStringAttribute(hDBFHandle, row, i)) )
{
fprintf(stderr, "Warning: field %d name truncated\n", i);
val[1023] = '\0';
}
break;
default:
fprintf(stderr,
"Error: field %d has invalid or unknown field type (%d)\n",
i, types[i]);
exit(1);
}
if (dump_format) {
escval = make_good_string(val);
printf("%s", escval);
//printf("\t");
} else {
escval = protect_quotes_string(val);
printf("'%s'", escval);
//printf(",");
}
if ( val != escval ) free(escval);
}
//only put in delimeter if not last field or a shape will follow
if(readshape == 1 || i < (num_fields - 1))
{
if (dump_format){
printf("\t");
}
else {
printf(",");
}
}
}
return 1;
}
/*
* main()
* see description at the top of this file
*/
int
main (int ARGC, char **ARGV)
{
/*
* Parse command line
*/
if ( ! ParseCmdline(ARGC, ARGV) ) usage(ARGV[0], 2, stderr);
/*
* Open shapefile and initialize globals
*/
OpenShape();
if (readshape == 1){
/*
* Compute output geometry type
*/
SetPgType();
fprintf(stderr, "Shapefile type: %s\n", SHPTypeName(shpfiletype));
fprintf(stderr, "Postgis type: %s[%d]\n", pgtype, pgdims);
}
#ifdef USE_ICONV
if ( encoding )
{
printf("SET CLIENT_ENCODING TO UTF8;\n");
}
#endif /* defined USE_ICONV */
/*
* Drop table if requested
*/
if(opt == 'd') DropTable(schema, table, geom);
/*
* Get col names and types for table creation
* and data load.
*/
GetFieldsSpec();
printf("BEGIN;\n");
/*
* If not in 'append' mode create the spatial table
*/
if(opt != 'a') CreateTable();
/*
* Generate INSERT or COPY lines
*/
if(opt != 'p') LoadData();
/*
* Create GiST index if requested
*/
if(createindex) CreateIndex();
printf("END;\n"); /* End the last transaction */
return 0;
}/*end main() */
void
LowerCase(char *s)
{
int j;
for (j=0; j<strlen(s); j++) s[j] = tolower(s[j]);
}
void
Cleanup(void)
{
if ( col_names ) free(col_names);
}
void
OpenShape(void)
{
int j;
SHPObject *obj=NULL;
if (readshape == 1)
{
hSHPHandle = SHPOpen( shp_file, "rb" );
if (hSHPHandle == NULL)
{
fprintf(stderr, "%s: shape (.shp) or index files (.shx) can not be opened, will just import attribute data.\n", shp_file);
readshape = 0;
}
}
hDBFHandle = DBFOpen( shp_file, "rb" );
if ((hSHPHandle == NULL && readshape == 1) || hDBFHandle == NULL){
fprintf(stderr, "%s: dbf file (.dbf) can not be opened.\n",shp_file);
exit(-1);
}
if (readshape == 1)
{
SHPGetInfo(hSHPHandle, &num_entities, &shpfiletype, NULL, NULL);
if ( null_policy == abort_on_null )
{
for (j=0; j<num_entities; j++)
{
obj = SHPReadObject(hSHPHandle,j);
if ( ! obj )
{
fprintf(stderr, "Error reading shape object %d\n", j);
exit(1);
}
if ( obj->nVertices == 0 )
{
fprintf(stderr, "Empty geometries found, aborted.\n");
exit(1);
}
SHPDestroyObject(obj);
}
}
}
else {
num_entities = DBFGetRecordCount(hDBFHandle);
}
}
void
CreateTable(void)
{
int j;
int field_precision, field_width;
DBFFieldType type = -1;
/*
* Create a table for inserting the shapes into with appropriate
* columns and types
*/
if ( schema )
{
printf("CREATE TABLE \"%s\".\"%s\" (gid serial PRIMARY KEY",
schema, table);
}
else
{
printf("CREATE TABLE \"%s\" (gid serial PRIMARY KEY", table);
}
for(j=0;j<num_fields;j++)
{
type = types[j];
field_width = widths[j];
field_precision = precisions[j];
printf(",\n\"%s\" ", field_names[j]);
if(type == FTString)
{
/* use DBF attribute size as maximum width */
printf ("varchar(%d)", field_width);
}
else if (type == FTDate)
{
printf ("date");
}
else if (type == FTInteger)
{
if ( forceint4 )
{
printf ("int4");
}
else if ( field_width < 5 )
{
printf ("int2");
}
else if ( field_width < 10 )
{
printf ("int4");
}
else if ( field_width < 19 )
{
printf ("int8");
}
else
{
printf("numeric(%d,0)",
field_width);
}
}
else if(type == FTDouble)
{
if( field_width > 18 )
{
printf ("numeric");
}
else
{
printf ("float8");
}
}
else if(type == FTLogical)
{
printf ("boolean");
}
else
{
printf ("Invalid type in DBF file");
}
}
printf (");\n");
/* Create the geometry column with an addgeometry call */
if ( schema && readshape == 1 )
{
printf("SELECT AddGeometryColumn('%s','%s','%s','%d',",
schema, table, geom, sr_id);
}
else if (readshape == 1)
{
printf("SELECT AddGeometryColumn('','%s','%s','%d',",
table, geom, sr_id);
}
if (pgtype)
{ //pgtype will only be set if we are loading geometries
printf("'%s',%d);\n", pgtype, pgdims);
}
}
void
CreateIndex(void)
{
/*
* Create gist index
*/
if ( schema )
{
printf("CREATE INDEX \"%s_%s_gist\" ON \"%s\".\"%s\" using gist (\"%s\" gist_geometry_ops);\n", table, geom, schema, table, geom);
}
else
{
printf("CREATE INDEX \"%s_%s_gist\" ON \"%s\" using gist (\"%s\" gist_geometry_ops);\n", table, geom, table, geom);
}
}
void
LoadData(void)
{
int j, trans=0;
if (dump_format){
if ( schema )
{
printf("COPY \"%s\".\"%s\" %s FROM stdin;\n",
schema, table, col_names);
}
else
{
printf("COPY \"%s\" %s FROM stdin;\n",
table, col_names);
}
}
/**************************************************************
*
* MAIN SHAPE OBJECTS SCAN
*
**************************************************************/
for (j=0; j<num_entities; j++)
{
/*wrap a transaction block around each 250 inserts... */
if ( ! dump_format )
{
if (trans == 250) {
trans=0;
printf("END;\n");
printf("BEGIN;\n");
}
}
trans++;
/* transaction stuff done */
/*open the next object */
if (readshape == 1)
{
obj = SHPReadObject(hSHPHandle,j);
if ( ! obj )
{
fprintf(stderr, "Error reading shape object %d\n", j);
exit(1);
}
if ( null_policy == skip_null && obj->nVertices == 0 )
{
SHPDestroyObject(obj);
continue;
}
}
if (!dump_format)
{
if ( schema )
{
printf("INSERT INTO \"%s\".\"%s\" %s VALUES (",
schema, table, col_names);
}
else
{
printf("INSERT INTO \"%s\" %s VALUES (",
table, col_names);
}
}
Insert_attributes(hDBFHandle,j);
if (readshape == 1)
{
/* ---------- NULL SHAPE ----------------- */
if (obj->nVertices == 0)
{
if (dump_format) printf("\\N\n");
else printf("NULL);\n");
SHPDestroyObject(obj);
continue;
}
switch (obj->nSHPType)
{
case SHPT_POLYGON:
case SHPT_POLYGONM:
case SHPT_POLYGONZ:
if ( hwgeom ) InsertPolygonWKT();
else InsertPolygon();
break;
case SHPT_POINT:
case SHPT_POINTM:
case SHPT_POINTZ:
if ( hwgeom ) InsertPointWKT();
else InsertPoint();
break;
case SHPT_MULTIPOINT:
case SHPT_MULTIPOINTM:
case SHPT_MULTIPOINTZ:
if ( hwgeom ) InsertPointWKT();
else InsertMultiPoint();
break;
case SHPT_ARC:
case SHPT_ARCM:
case SHPT_ARCZ:
if ( hwgeom ) InsertLineStringWKT(j);
else InsertLineString(j);
break;
default:
printf ("\n\n**** Type is NOT SUPPORTED, type id = %d ****\n\n",
obj->nSHPType);
break;
}
SHPDestroyObject(obj);
}
else
if (dump_format){ /*close for dbf only dump format */
printf("\n");
}
else { /*close for dbf only sql insert format */
printf(");\n");
}
} /* END of MAIN SHAPE OBJECT LOOP */
if ((dump_format) ) {
printf("\\.\n");
}
}
void
usage(char *me, int exitcode, FILE* out)
{
fprintf(out, "RCSID: %s RELEASE: %s\n", rcsid, POSTGIS_VERSION);
fprintf(out, "USAGE: %s [<options>] <shapefile> [<schema>.]<table>\n", me);
fprintf(out, "OPTIONS:\n");
fprintf(out, " -s <srid> Set the SRID field. If not specified it defaults to -1.\n");
fprintf(out, " (-d|a|c|p) These are mutually exclusive options:\n");
fprintf(out, " -d Drops the table, then recreates it and populates\n");
fprintf(out, " it with current shape file data.\n");
fprintf(out, " -a Appends shape file into current table, must be\n");
fprintf(out, " exactly the same table schema.\n");
fprintf(out, " -c Creates a new table and populates it, this is the\n");
fprintf(out, " default if you do not specify any options.\n");
fprintf(out, " -p Prepare mode, only creates the table.\n");
fprintf(out, " -g <geometry_column> Specify the name of the geometry column\n");
fprintf(out, " (mostly useful in append mode).\n");
fprintf(out, " -D Use postgresql dump format (defaults to sql insert statments.\n");
fprintf(out, " -k Keep postgresql identifiers case.\n");
fprintf(out, " -i Use int4 type for all integer dbf fields.\n");
fprintf(out, " -I Create a GiST index on the geometry column.\n");
fprintf(out, " -S Generate simple geometries instead of MULTI geometries.\n");
fprintf(out, " -w Use wkt format (for postgis-0.x support - drops M - drifts coordinates).\n");
#ifdef USE_ICONV
fprintf(out, " -W <encoding> Specify the character encoding of Shape's\n");
fprintf(out, " attribute column. (default : \"ASCII\")\n");
#endif
fprintf(out, " -N <policy> Specify NULL geometries handling policy (insert,skip,abort)\n");
fprintf(out, " -n Only import DBF file.\n");
fprintf(out, " -? Display this help screen\n");
exit (exitcode);
}
void
InsertLineString(int id)
{
int pi; /* part index */
unsigned int subtype = LINETYPE | (wkbtype&WKBZOFFSET) |
(wkbtype&WKBMOFFSET);
/* Invalid (MULTI)Linestring */
if ( obj->nVertices < 2 )
{
fprintf(stderr,
"MULTILINESTRING %d as %d vertices, set to NULL\n",
id, obj->nVertices);
if (dump_format) printf("\\N\n");
else printf("NULL);\n");
return;
}
if (!dump_format) printf("'");
if ( sr_id > 0 ) printf("SRID=%d;", sr_id);
if (simple_geometries==0) // We write MULTI geometries, so generate Header
{
print_wkb_byte(getEndianByte());
print_wkb_int(wkbtype);
print_wkb_int(obj->nParts); /* npolys */
}
else if ((obj->nParts)!=1) // We write Non-MULTI geometries, but have several parts:
{
fprintf(stderr, "We have a MultiLineString with %d parts, can't use -S switch!\n", obj->nParts);
exit(1);
}
for (pi=0; pi<obj->nParts; pi++)
{
int vi; /* vertex index */
int vs; /* start vertex */
int ve; /* end vertex */
print_wkb_byte(getEndianByte());
print_wkb_int(subtype);
/* Set start and end vertexes */
if ( pi==obj->nParts-1 ) ve = obj->nVertices;
else ve = obj->panPartStart[pi+1];
vs = obj->panPartStart[pi];
print_wkb_int(ve-vs);
for ( vi=vs; vi<ve; vi++)
{
print_wkb_double(obj->padfX[vi]);
print_wkb_double(obj->padfY[vi]);
if ( wkbtype & WKBZOFFSET )
print_wkb_double(obj->padfZ[vi]);
if ( wkbtype & WKBMOFFSET )
print_wkb_double(obj->padfM[vi]);
}
}
if (dump_format) printf("\n");
else printf("');\n");
}
void
InsertLineStringWKT(int id)
{
int pi; /* part index */
/* Invalid (MULTI)Linestring */
if ( obj->nVertices < 2 )
{
fprintf(stderr,
"MULTILINESTRING %d as %d vertices, set to NULL\n",
id, obj->nVertices);
if (dump_format) printf("\\N\n");
else printf("NULL);\n");
return;
}
if (dump_format) printf("SRID=%d;",sr_id );
else printf("GeometryFromText('");
if (simple_geometries==0) // We write MULTI geometries, so generate Header
{
printf("MULTILINESTRING(");
}
else if ((obj->nParts)==1)
{
printf("LINESTRING");
}
else // We write Non-MULTI geometries, but have several parts:
{
fprintf(stderr, "We have a Multilinestring with %d parts, can't use -S switch!\n", obj->nParts);
exit(1);
}
for (pi=0; pi<obj->nParts; pi++)
{
int vi; /* vertex index */
int vs; /* start vertex */
int ve; /* end vertex */
if (pi) printf(",");
printf("(");
/* Set start and end vertexes */
if ( pi==obj->nParts-1 ) ve = obj->nVertices;
else ve = obj->panPartStart[pi+1];
vs = obj->panPartStart[pi];
for ( vi=vs; vi<ve; vi++)
{
if ( vi > vs ) printf(",");
printf("%.15g %.15g",
obj->padfX[vi],
obj->padfY[vi]);
if ( wkbtype & WKBZOFFSET )
printf(" %.15g", obj->padfZ[vi]);
}
printf(")");
}
if (simple_geometries==0) printf(")");
if (dump_format) printf("\n");
else printf("',%d) );\n",sr_id);
}
int
FindPolygons(SHPObject *obj, Ring ***Out)
{
Ring **Outer; /* Pointers to Outer rings */
int out_index=0; /* Count of Outer rings */
Ring **Inner; /* Pointers to Inner rings */
int in_index=0; /* Count of Inner rings */
int pi; /* part index */
#ifdef DEBUG
static int call = -1;
call++;
fprintf(stderr, "FindPolygons[%d]: allocated space for %d rings\n",
call, obj->nParts);
#endif
/* Allocate initial memory */
Outer = (Ring**)malloc(sizeof(Ring*)*obj->nParts);
Inner = (Ring**)malloc(sizeof(Ring*)*obj->nParts);
/* Iterate over rings dividing in Outers and Inners */
for (pi=0; pi<obj->nParts; pi++)
{
int vi; /* vertex index */
int vs; /* start index */
int ve; /* end index */
int nv; /* number of vertex */
double area = 0.0;
Ring *ring;
/* Set start and end vertexes */
if ( pi==obj->nParts-1 ) ve = obj->nVertices;
else ve = obj->panPartStart[pi+1];
vs = obj->panPartStart[pi];
/* Compute number of vertexes */
nv = ve-vs;
/* Allocate memory for a ring */
ring = (Ring*)malloc(sizeof(Ring));
ring->list = (Point*)malloc(sizeof(Point)*nv);
ring->n = nv;
ring->next = NULL;
ring->linked = 0;
/* Iterate over ring vertexes */
for ( vi=vs; vi<ve; vi++)
{
int vn = vi+1; /* next vertex for area */
if ( vn==ve ) vn = vs;
ring->list[vi-vs].x = obj->padfX[vi];
ring->list[vi-vs].y = obj->padfY[vi];
ring->list[vi-vs].z = obj->padfZ[vi];
ring->list[vi-vs].m = obj->padfM[vi];
area += (obj->padfX[vi] * obj->padfY[vn]) -
(obj->padfY[vi] * obj->padfX[vn]);
}
/* Close the ring with first vertex */
/*ring->list[vi].x = obj->padfX[vs]; */
/*ring->list[vi].y = obj->padfY[vs]; */
/*ring->list[vi].z = obj->padfZ[vs]; */
/*ring->list[vi].m = obj->padfM[vs]; */
/* Clockwise (or single-part). It's an Outer Ring ! */
if(area < 0.0 || obj->nParts ==1) {
Outer[out_index] = ring;
out_index++;
}
/* Counterclockwise. It's an Inner Ring ! */
else {
Inner[in_index] = ring;
in_index++;
}
}
#ifdef DEBUG
fprintf(stderr, "FindPolygons[%d]: found %d Outer, %d Inners\n",
call, out_index, in_index);
#endif
/* Put the inner rings into the list of the outer rings */
/* of which they are within */
for(pi=0; pi<in_index; pi++)
{
Point pt,pt2;
int i;
Ring *inner=Inner[pi], *outer=NULL;
pt.x = inner->list[0].x;
pt.y = inner->list[0].y;
pt2.x = inner->list[1].x;
pt2.y = inner->list[1].y;
for(i=0; i<out_index; i++)
{
int in;
in = PIP(pt, Outer[i]->list, Outer[i]->n);
if( in || PIP(pt2, Outer[i]->list, Outer[i]->n) )
{
outer = Outer[i];
break;
}
/*fprintf(stderr, "!PIP %s\nOUTE %s\n", dump_ring(inner), dump_ring(Outer[i])); */
}
if ( outer )
{
outer->linked++;
while(outer->next) outer = outer->next;
outer->next = inner;
}
else
{
/* The ring wasn't within any outer rings, */
/* assume it is a new outer ring. */
#ifdef DEBUG
fprintf(stderr,
"FindPolygons[%d]: hole %d is orphan\n",
call, pi);
#endif
Outer[out_index] = inner;
out_index++;
}
}
*Out = Outer;
free(Inner);
return out_index;
}
void
ReleasePolygons(Ring **polys, int npolys)
{
int pi;
/* Release all memory */
for(pi=0; pi<npolys; pi++)
{
Ring *Poly, *temp;
Poly = polys[pi];
while(Poly != NULL){
temp = Poly;
Poly = Poly->next;
free(temp->list);
free(temp);
}
}
}
/*This function basically deals with the polygon case. */
/*it sorts the polys in order of outer,inner,inner, so that inners */
/*always come after outers they are within */
void
InsertPolygon(void)
{
unsigned int subtype = POLYGONTYPE | (wkbtype&WKBZOFFSET) |
(wkbtype&WKBMOFFSET);
Ring **Outer;
int out_index;
int pi; /* part index */
out_index = FindPolygons(obj, &Outer);
if (!dump_format) printf("'");
if ( sr_id > 0 ) printf("SRID=%d;", sr_id);
if (simple_geometries==0) // We write MULTI geometries, so generate Header
{
print_wkb_byte(getEndianByte());
print_wkb_int(wkbtype);
print_wkb_int(out_index); /* npolys */
}
else if (out_index!=1) // We write Non-MULTI geometries, but have several parts:
{
fprintf(stderr, "We have a Multipolygon with %d parts, can't use -S switch!\n", out_index);
exit(1);
}
/* Write the coordinates */
for(pi=0; pi<out_index; pi++)
{
Ring *poly;
poly = Outer[pi];
print_wkb_byte(getEndianByte());
print_wkb_int(subtype);
print_wkb_int(poly->linked+1); /* nrings */
while(poly)
{
int vi; /* vertex index */
print_wkb_int(poly->n); /* npoints */
for(vi=0; vi<poly->n; vi++)
{
print_wkb_double(poly->list[vi].x);
print_wkb_double(poly->list[vi].y);
if ( wkbtype & WKBZOFFSET )
print_wkb_double(poly->list[vi].z);
if ( wkbtype & WKBMOFFSET )
print_wkb_double(poly->list[vi].m);
}
poly = poly->next;
}
}
if (dump_format) printf("\n");
else printf("');\n");
/* Release all memory */
ReleasePolygons(Outer, out_index);
free(Outer);
}
void
InsertPolygonWKT(void)
{
Ring **Outer; /* Pointers to Outer rings */
int out_index=0; /* Count of Outer rings */
int pi; /* part index */
#ifdef DEBUG
static int call = -1;
call++;
fprintf(stderr, "InsertPolygon[%d]: allocated space for %d rings\n",
call, obj->nParts);
#endif
out_index = FindPolygons(obj, &Outer);
if (dump_format) printf("SRID=%d;",sr_id );
else printf("GeometryFromText('");
if (simple_geometries==0) // We write MULTI geometries, so generate Header
{
printf("MULTIPOLYGON(");
}
else if (out_index==1)
{
printf("POLYGON");
}
else
{ // We write Non-MULTI geometries, but have several parts:
fprintf(stderr, "We have a Multipolygon with %d parts, can't use -S switch!\n", out_index);
exit(1);
}
/* Write the coordinates */
for(pi=0; pi<out_index; pi++)
{
Ring *poly;
poly = Outer[pi];
if ( pi ) printf(",");
printf("(");
while(poly)
{
int vi; /* vertex index */
printf("(");
for(vi=0; vi<poly->n; vi++)
{
if ( vi ) printf(",");
printf("%.15g %.15g",
poly->list[vi].x,
poly->list[vi].y);
if ( wkbtype & WKBZOFFSET )
printf(" %.15g", poly->list[vi].z);
}
printf(")");
poly = poly->next;
if ( poly ) printf(",");
}
printf(")");
}
if (simple_geometries==0) printf(")");
if (dump_format) printf("\n");
else printf("',%d) );\n",sr_id);
/* Release all memory */
ReleasePolygons(Outer, out_index);
free(Outer);
}
void
InsertPoint(void)
{
if (!dump_format) printf("'");
if ( sr_id > 0 ) printf("SRID=%d;", sr_id);
print_wkb_byte(getEndianByte());
print_wkb_int(wkbtype);
print_wkb_double(obj->padfX[0]);
print_wkb_double(obj->padfY[0]);
if ( wkbtype & WKBZOFFSET ) print_wkb_double(obj->padfZ[0]);
if ( wkbtype & WKBMOFFSET ) print_wkb_double(obj->padfM[0]);
if (dump_format) printf("\n");
else printf("');\n");
}
void
InsertPointWKT(void)
{
unsigned int u;
if (dump_format) printf("SRID=%d;%s(", sr_id, pgtype);
else printf("GeometryFromText('%s(", pgtype);
for (u=0;u<obj->nVertices; u++){
if (u>0) printf(",");
printf("%.15g %.15g",obj->padfX[u],obj->padfY[u]);
if ( wkbtype & WKBZOFFSET ) printf(" %.15g", obj->padfZ[u]);
}
if (dump_format) printf(")\n");
else printf(")',%d) );\n",sr_id);
}
void
InsertMultiPoint(void)
{
unsigned int u;
unsigned int subtype = POINTTYPE | (wkbtype&WKBZOFFSET) |
(wkbtype&WKBMOFFSET);
if (!dump_format) printf("'");
if ( sr_id > 0 ) printf("SRID=%d;", sr_id);
print_wkb_byte(getEndianByte());
print_wkb_int(wkbtype);
print_wkb_int(obj->nVertices);
for (u=0;u<obj->nVertices; u++)
{
print_wkb_byte(getEndianByte());
print_wkb_int(subtype);
print_wkb_double(obj->padfX[u]);
print_wkb_double(obj->padfY[u]);
if ( wkbtype & WKBZOFFSET ) print_wkb_double(obj->padfZ[u]);
if ( wkbtype & WKBMOFFSET ) print_wkb_double(obj->padfM[u]);
}
if (dump_format) printf("\n");
else printf("');\n");
}
int
ParseCmdline(int ARGC, char **ARGV)
{
int c;
int curindex=0;
char *ptr;
extern char *optarg;
extern int optind;
if ( ARGC == 1 ) {
usage(ARGV[0], 0, stdout);
}
while ((c = pgis_getopt(ARGC, ARGV, "kcdapDs:Sg:iW:wIN:n")) != EOF){
switch (c) {
case 'c':
if (opt == ' ')
opt ='c';
else
return 0;
break;
case 'd':
if (opt == ' ')
opt ='d';
else
return 0;
break;
case 'a':
if (opt == ' ')
opt ='a';
else
return 0;
break;
case 'p':
if (opt == ' ')
opt ='p';
else
return 0;
break;
case 'D':
dump_format =1;
break;
case 'S':
simple_geometries =1;
break;
case 's':
(void)sscanf(optarg, "%d", &sr_id);
break;
case 'g':
geom = optarg;
break;
case 'k':
quoteidentifiers = 1;
break;
case 'i':
forceint4 = 1;
break;
case 'I':
createindex = 1;
break;
case 'w':
hwgeom = 1;
break;
case 'n':
readshape = 0;
break;
case 'W':
#ifdef USE_ICONV
encoding = optarg;
#else
fprintf(stderr, "WARNING: the -W switch will have no effect. UTF8 disabled at compile time\n");
#endif
break;
case 'N':
switch (optarg[0])
{
case 'a':
null_policy = abort_on_null;
break;
case 'i':
null_policy = insert_null;
break;
case 's':
null_policy = skip_null;
break;
default:
fprintf(stderr, "Unsupported NULL geometry handling policy.\nValid policies: insert, skip, abort\n");
exit(1);
}
break;
case '?':
usage(ARGV[0], 0, stdout);
default:
return 0;
}
}
if ( !sr_id ) sr_id = -1;
if ( !geom ) geom = "the_geom";
if ( opt==' ' ) opt = 'c';
for (; optind < ARGC; optind++){
if(curindex ==0){
shp_file = ARGV[optind];
}else if(curindex == 1){
table = ARGV[optind];
if ( (ptr=strchr(table, '.')) )
{
*ptr = '\0';
schema = table;
table = ptr+1;
}
}
curindex++;
}
/*
* Third argument (if present) is supported for compatibility
* with old shp2pgsql versions taking also database name.
*/
if(curindex < 2 || curindex > 3){
return 0;
}
/*
* Transform table name to lower case unless asked
* to keep original case (we'll quote it later on)
*/
if ( ! quoteidentifiers )
{
LowerCase(table);
if ( schema ) LowerCase(schema);
}
return 1;
}
void
SetPgType(void)
{
switch(shpfiletype)
{
case SHPT_POINT: /* Point */
pgtype = "POINT";
wkbtype = POINTTYPE;
pgdims = 2;
break;
case SHPT_ARC: /* PolyLine */
pgtype = "MULTILINESTRING";
wkbtype = MULTILINETYPE ;
pgdims = 2;
break;
case SHPT_POLYGON: /* Polygon */
pgtype = "MULTIPOLYGON";
wkbtype = MULTIPOLYGONTYPE;
pgdims = 2;
break;
case SHPT_MULTIPOINT: /* MultiPoint */
pgtype = "MULTIPOINT";
wkbtype = MULTIPOINTTYPE;
pgdims = 2;
break;
case SHPT_POINTM: /* PointM */
wkbtype = POINTTYPE | WKBMOFFSET;
if ( ! hwgeom ) {
pgtype = "POINTM";
pgdims = 3;
istypeM = 1;
} else {
pgtype = "POINT";
pgdims = 2;
}
break;
case SHPT_ARCM: /* PolyLineM */
wkbtype = MULTILINETYPE | WKBMOFFSET;
if ( ! hwgeom ) {
pgtype = "MULTILINESTRINGM";
pgdims = 3;
istypeM = 1;
} else {
pgtype = "MULTILINESTRING";
pgdims = 2;
}
break;
case SHPT_POLYGONM: /* PolygonM */
wkbtype = MULTIPOLYGONTYPE | WKBMOFFSET;
if ( ! hwgeom ) {
pgtype = "MULTIPOLYGONM";
pgdims = 3;
istypeM = 1;
} else {
pgtype = "MULTIPOLYGON";
pgdims = 2;
}
break;
case SHPT_MULTIPOINTM: /* MultiPointM */
wkbtype = MULTIPOINTTYPE | WKBMOFFSET;
if ( ! hwgeom ) {
pgtype = "MULTIPOINTM";
pgdims = 3;
istypeM = 1;
} else {
pgtype = "MULTIPOINT";
pgdims = 2;
}
break;
case SHPT_POINTZ: /* PointZ */
wkbtype = POINTTYPE | WKBMOFFSET | WKBZOFFSET;
pgtype = "POINT";
if ( ! hwgeom ) pgdims = 4;
else pgdims = 3;
break;
case SHPT_ARCZ: /* PolyLineZ */
pgtype = "MULTILINESTRING";
wkbtype = MULTILINETYPE | WKBZOFFSET | WKBMOFFSET;
if ( ! hwgeom ) pgdims = 4;
else pgdims = 3;
break;
case SHPT_POLYGONZ: /* MultiPolygonZ */
pgtype = "MULTIPOLYGON";
wkbtype = MULTIPOLYGONTYPE | WKBZOFFSET | WKBMOFFSET;
if ( ! hwgeom ) pgdims = 4;
else pgdims = 3;
break;
case SHPT_MULTIPOINTZ: /* MultiPointZ */
pgtype = "MULTIPOINT";
wkbtype = MULTIPOINTTYPE | WKBZOFFSET | WKBMOFFSET;
if ( ! hwgeom ) pgdims = 4;
else pgdims = 3;
break;
default:
pgtype = "GEOMETRY";
wkbtype = COLLECTIONTYPE | WKBZOFFSET | WKBMOFFSET;
pgdims = 4;
fprintf(stderr, "Unknown geometry type: %d\n",
shpfiletype);
break;
}
if (simple_geometries)
{
// adjust geometry name for CREATE TABLE by skipping MULTI
if ((wkbtype & 0x7) == MULTIPOLYGONTYPE) pgtype += 5;
if ((wkbtype & 0x7) == MULTILINETYPE) pgtype += 5;
}
}
char *
dump_ring(Ring *ring)
{
char *buf = malloc(256*ring->n);
int i;
buf[0] = '\0';
for (i=0; i<ring->n; i++)
{
if (i) strcat(buf, ",");
sprintf(buf+strlen(buf), "%g %g",
ring->list[i].x,
ring->list[i].y);
}
return buf;
}
/*--------------- WKB handling */
static char outchr[]={"0123456789ABCDEF"};
static int endian_check_int = 1; /* dont modify this!!! */
static char
getEndianByte(void)
{
/* 0 = big endian, 1 = little endian */
if ( *((char *) &endian_check_int) ) return 1;
else return 0;
}
static void
print_wkb_double(double val)
{
print_wkb_bytes((unsigned char *)&val, 1, 8);
}
static void
print_wkb_byte(unsigned char val)
{
print_wkb_bytes((unsigned char *)&val, 1, 1);
}
static void
print_wkb_int(int val)
{
print_wkb_bytes((unsigned char *)&val, 1, 4);
}
static void
print_wkb_bytes(unsigned char *ptr, unsigned int cnt, size_t size)
{
unsigned int bc; /* byte count */
static char buf[256];
char *bufp;
if ( size*cnt*2 > 256 )
{
fprintf(stderr,
"You found a bug! wkb_bytes does not allocate enough bytes");
exit(4);
}
bufp = buf;
while(cnt--){
for(bc=0; bc<size; bc++)
{
*bufp++ = outchr[ptr[bc]>>4];
*bufp++ = outchr[ptr[bc]&0x0F];
}
}
*bufp = '\0';
/*fprintf(stderr, "\nwkbbytes:%s\n", buf); */
printf("%s", buf);
}
void
DropTable(char *schema, char *table, char *geom)
{
/*---------------Drop the table--------------------------
* TODO: if the table has more then one geometry column
* the DROP TABLE call will leave spurious records in
* geometry_columns.
*
* If the geometry column in the table being dropped
* does not match 'the_geom' or the name specified with
* -g an error is returned by DropGeometryColumn.
*
* The table to be dropped might not exist.
*
*/
if ( schema )
{
if (readshape == 1){
printf("SELECT DropGeometryColumn('%s','%s','%s');\n",
schema, table, geom);
}
printf("DROP TABLE \"%s\".\"%s\";\n", schema, table);
}
else
{
if (readshape == 1){
printf("SELECT DropGeometryColumn('','%s','%s');\n",
table, geom);
}
printf("DROP TABLE \"%s\";\n", table);
}
}
void
GetFieldsSpec(void)
{
/*
* Shapefile (dbf) field name are at most 10chars + 1 NULL.
* Postgresql field names are at most 63 bytes + 1 NULL.
*/
#define MAXFIELDNAMELEN 64
int field_precision, field_width;
int j, z;
char name[MAXFIELDNAMELEN];
char name2[MAXFIELDNAMELEN];
DBFFieldType type = -1;
#ifdef USE_ICONV
char *utf8str;
#endif
num_fields = DBFGetFieldCount( hDBFHandle );
num_records = DBFGetRecordCount(hDBFHandle);
field_names = malloc(num_fields*sizeof(char*));
types = (DBFFieldType *)malloc(num_fields*sizeof(int));
widths = malloc(num_fields*sizeof(int));
precisions = malloc(num_fields*sizeof(int));
if (readshape == 1)
{
col_names = malloc((num_fields+2) * sizeof(char) * MAXFIELDNAMELEN);
}
{ //for dbf only, we do not need to allocate slot for the_geom
col_names = malloc((num_fields+1) * sizeof(char) * MAXFIELDNAMELEN);
}
strcpy(col_names, "(" );
/*fprintf(stderr, "Number of fields from DBF: %d\n", num_fields); */
for(j=0;j<num_fields;j++)
{
type = DBFGetFieldInfo(hDBFHandle, j, name, &field_width, &field_precision);
/*fprintf(stderr, "Field %d (%s) width/decimals: %d/%d\n", j, name, field_width, field_precision); */
types[j] = type;
widths[j] = field_width;
precisions[j] = field_precision;
#ifdef USE_ICONV
if ( encoding )
{
utf8str = utf8(encoding, name);
if ( ! utf8str ) exit(1);
strcpy(name, utf8str);
free(utf8str);
}
#endif
/*
* Make field names lowercase unless asked to
* keep identifiers case.
*/
if ( ! quoteidentifiers ) LowerCase(name);
/*
* Escape names starting with the
* escape char (_), those named 'gid'
* or after pgsql reserved attribute names
*/
if( name[0]=='_' ||
! strcmp(name,"gid") ||
! strcmp(name, "tableoid") ||
! strcmp(name, "cmax") ||
! strcmp(name, "xmax") ||
! strcmp(name, "cmin") ||
! strcmp(name, "primary") ||
! strcmp(name, "oid") ||
! strcmp(name, "ctid") )
{
strcpy(name2+2, name);
name2[0] = '_';
name2[1] = '_';
strcpy(name, name2);
}
/* Avoid duplicating field names */
for(z=0; z < j ; z++){
if(strcmp(field_names[z],name)==0){
strcat(name,"__");
sprintf(name+strlen(name),"%i",j);
break;
}
}
field_names[j] = malloc (strlen(name)+1);
strcpy(field_names[j], name);
/*sprintf(col_names, "%s\"%s\",", col_names, name);*/
strcat(col_names, "\"");
strcat(col_names, name);
if (readshape == 1 || j < (num_fields - 1)){
//don't include last comma if its the last field and no geometry field will follow
strcat(col_names, "\",");
}
else {
strcat(col_names, "\"");
}
}
/*sprintf(col_names, "%s\"%s\")", col_names, geom);*/
if (readshape == 1){
strcat(col_names, geom);
}
strcat(col_names, ")");
}
#ifdef USE_ICONV
char *
utf8 (const char *fromcode, char *inputbuf)
{
iconv_t cd;
char *outputptr;
char *outputbuf;
size_t outbytesleft;
size_t inbytesleft;
inbytesleft = strlen (inputbuf);
cd = iconv_open ("UTF-8", fromcode);
if (cd == (iconv_t) - 1)
{
fprintf(stderr, "utf8: iconv_open: %s\n", strerror (errno));
return NULL;
}
outbytesleft = inbytesleft*3+1; /* UTF8 string can be 3 times larger */
/* then local string */
outputbuf = (char *) malloc (outbytesleft);
if (!outputbuf)
{
fprintf(stderr, "utf8: malloc: %s\n", strerror (errno));
return NULL;
}
memset (outputbuf, 0, outbytesleft);
outputptr = outputbuf;
if (-1==iconv(cd, &inputbuf, &inbytesleft, &outputptr, &outbytesleft))
{
fprintf(stderr, "utf8: %s", strerror (errno));
return NULL;
}
iconv_close (cd);
return outputbuf;
}
#endif /* defined USE_ICONV */
/**********************************************************************
* $Log$
* Revision 1.109 2008/04/09 14:12:17 robe
* - Added support to load dbf-only files
*
* Revision 1.108 2006/06/16 14:12:17 strk
* - BUGFIX in pgsql2shp successful return code.
* - BUGFIX in shp2pgsql handling of MultiLine WKT.
*
* Revision 1.107 2006/04/18 09:16:26 strk
* Substituted bzero() use with memset()
*
* Revision 1.106 2006/01/16 10:42:58 strk
* Added support for Bool and Date DBF<=>PGIS mapping
*
* Revision 1.105 2006/01/09 16:40:16 strk
* ISO C90 comments, signedness mismatch fixes
*
* Revision 1.104 2005/11/01 09:25:47 strk
* Reworked NULL geometries handling code letting user specify policy (insert,skip,abort). Insert is the default.
*
* Revision 1.103 2005/10/24 15:54:22 strk
* fixed wrong assumption about maximum size of integer attributes (width is maximum size of text representation)
*
* Revision 1.102 2005/10/24 11:30:59 strk
*
* Fixed a bug in string attributes handling truncating values of maximum
* allowed length, curtesy of Lars Roessiger.
* Reworked integer attributes handling to be stricter in dbf->sql mapping
* and to allow for big int8 values in sql->dbf conversion
*
* Revision 1.101 2005/10/21 11:33:55 strk
* Applied patch by Lars Roessiger handling numerical values with a trailing decima
* l dot
*
* Revision 1.100 2005/10/13 13:40:20 strk
* Fixed return code from shp2pgsql
*
* Revision 1.99 2005/10/03 18:08:55 strk
* Stricter string attributes lenght handling. DBF header will be used
* to set varchar maxlenght, (var)char typmod will be used to set DBF header
* len.
*
* Revision 1.98 2005/10/03 07:45:58 strk
* Issued a warning when -W is specified and no UTF8 support has been compiled in.
*
* Revision 1.97 2005/09/30 08:59:29 strk
* Fixed release of stack memory occurring when shp2pgsql is compiled with USE_ICONV defined, an attribute value needs to be escaped and no -W is used
*
* Revision 1.96 2005/08/29 22:36:25 strk
* Removed premature object destruction in InsertLineString{WKT,} causing segfault
*
* Revision 1.95 2005/08/29 11:48:33 strk
* Fixed sprintf() calls to avoid overlapping memory,
* reworked not-null objects existance check to reduce startup costs.
*
* Revision 1.94 2005/07/27 02:47:14 strk
* Support for multibyte field names in loader
*
* Revision 1.93 2005/07/27 02:35:50 strk
* Minor cleanups in loader
*
* Revision 1.92 2005/07/27 02:07:01 strk
* Fixed handling of POINT types as WKT (-w) in loader
*
* Revision 1.91 2005/07/04 09:47:03 strk
* Added conservative iconv detection code
*
* Revision 1.90 2005/06/16 17:55:58 strk
* Added -I switch for GiST index creation in loader
*
* Revision 1.89 2005/04/21 09:08:34 strk
* Applied patch from Ron Mayer fixing a segfault in string escaper funx
*
* Revision 1.88 2005/04/14 12:58:59 strk
* Applied patch by Gino Lucrezi fixing bug in string escaping code.
*
* Revision 1.87 2005/04/06 14:16:43 strk
* Removed manual update of gid field.
*
* Revision 1.86 2005/04/06 14:02:08 mschaber
* added -p option (prepare mode) that spits out the table schema without
* inserting any data.
*
* Revision 1.85 2005/04/06 10:46:10 strk
* Bugfix in -w (hwgeom) handling of ZM shapefiles.
* Big reorganizzation of code to easy maintainance.
*
* Revision 1.84 2005/04/04 20:51:26 strk
* Added -w flag to output old (WKT/HWGEOM) sql.
*
* Revision 1.83 2005/03/15 12:24:40 strk
* hole-in-ring detector made more readable
*
* Revision 1.82 2005/03/14 22:02:31 strk
* Fixed holes handling.
*
* Revision 1.81 2005/03/08 11:06:33 strk
* modernized old-style parameter declarations
*
* Revision 1.80 2005/03/04 14:48:22 strk
* Applied patch from Jonne Savolainen fixing multilines handling
*
* Revision 1.79 2005/01/31 22:15:22 strk
* Added maintainer notice, to reduce Jeff-strk mail bounces
*
* Revision 1.78 2005/01/17 09:21:13 strk
* Added one more bytes for terminating NULL in utf8 encoder
*
* Revision 1.77 2005/01/16 16:50:01 strk
* String escaping algorithm made simpler and more robust.
* Removed escaped strings leaking.
* Fixed UTF8 encoder to allocate enough space for 3bytes chars strings.
*
* Revision 1.76 2005/01/12 17:03:20 strk
* Added optional UTF8 output support as suggested by IIDA Tetsushi
*
* Revision 1.75 2004/11/15 10:51:35 strk
* Fixed a bug in PIP invocation, added some debugging lines.
*
* Revision 1.74 2004/10/17 13:25:44 strk
* removed USE_WKB partially-used define
*
* Revision 1.73 2004/10/17 13:24:44 strk
* HEXWKB polygon
*
* Revision 1.72 2004/10/17 12:59:12 strk
* HEXWKB multiline output
*
* Revision 1.71 2004/10/17 12:26:02 strk
* Point and MultiPoint loaded using HEXWKB.
*
* Revision 1.70 2004/10/15 22:01:35 strk
* Initial WKB functionalities
*
* Revision 1.69 2004/10/07 21:52:28 strk
* Lots of rewriting/cleanup. TypeM/TypeZ supports.
*
* Revision 1.68 2004/10/07 06:54:24 strk
* cleanups
*
* Revision 1.67 2004/10/06 10:11:16 strk
* Other separator fixes
*
* Revision 1.66 2004/10/06 09:40:27 strk
* Handled 0-DBF-attributes corner case.
*
* Revision 1.65 2004/09/20 17:13:31 strk
* changed comments to better show shape type handling
*
* Revision 1.64 2004/08/20 08:14:37 strk
* Whole output wrapped in transaction blocks.
* Drops are out of transaction, and multiple transactions are used
* for INSERT mode.
*
**********************************************************************/
|