[gdal-dev] Inserting into PostGIS table with primary key using ogr2ogr

Even Rouault even.rouault at mines-paris.org
Tue Dec 13 14:03:28 EST 2011


Le mardi 13 décembre 2011 14:47:40, Luca Sigfrido Percich a écrit :
> Even,
> 
> I did again the test with spatialite, and discovered that it behaves
> like Postgres, except it works also if you don't specify -preserve_fid,
> in which case the inserted fids are generated starting from 1. That's
> why I din't realize it was not inserting the values from my shape
> (initially the IDs were 1..5, now I changed to 105..109).
> 
> With the -preserve_fid option, spatialite too starts generating fids
> from 0.
> 
> Is there a way to tell OGR that ID is the FID?

Yes, I've finally found how to do it without changing any line of code. Here 
come the power of the OGR VRT driver...

1) Fetch http://svn.osgeo.org/gdal/trunk/gdal/swig/python/samples/ogr2vrt.py
2) Generate a templatpython ogr2vrt.py test_pk_data.shp test_pk_data.vrt
3) Edit test_pk_data.vrt to add a <FID> element that points to the ID column 
of your shapefile and remove/comment the <Field name="id"> element :

<OGRVRTDataSource>
  <OGRVRTLayer name="test_pk_data">
    <SrcDataSource relativeToVRT="0" 
shared="1">test_pk_data.shp</SrcDataSource>
    <SrcLayer>test_pk_data</SrcLayer>
    <GeometryType>wkbPoint</GeometryType>
    <LayerSRS>PROJCS[&quot;Monte_Mario_Italy_zone_1&quot;,GEOGCS[&quot;GCS_Monte 
Mario&quot;,DATUM[&quot;Monte_Mario&quot;,SPHEROID[&quot;International_1924&quot;,6378388,297]],PRIMEM[&quot;Greenwich&quot;,0],UNIT[&quot;Degree&quot;,0.017453292519943295]],PROJECTION[&quot;Transverse_Mercator&quot;],PARAMETER[&quot;latitude_of_origin&quot;,0],PARAMETER[&quot;central_meridian&quot;,9],PARAMETER[&quot;scale_factor&quot;,0.9996],PARAMETER[&quot;false_easting&quot;,1500000],PARAMETER[&quot;false_northing&quot;,0],UNIT[&quot;Meter&quot;,1]]</LayerSRS>
    <FID>id</FID>
    <!--<Field name="id" type="Integer" src="id" width="10"/>-->
    <Field name="name" type="String" src="name" width="50"/>
  </OGRVRTLayer>
</OGRVRTDataSource>

4) ogr2ogr -update -append pg:dbname=XXXX test_pk_data.vrt -preserve_fid 

Enjoy !

I've also added a short comment about the -preserve_fid option in ogr2ogr 
manual.


Even


More information about the gdal-dev mailing list