Skip to content
Prev 23633 / 29559 Next

Adding spatial tables to existing SpatiaLite DBs

On 11/03/2015 04:24 AM, Barry Rowlingson wrote:
Ogr2ogr can add layers to any driver that supports multiple layers using 
the -update switch:

     ogr2ogr -update destination source [layers]

If layers are not specified for a multi-layer source, *all* of them will 
be transferred.

Although writeOGR does expose the -update switch, it does successfully 
add layers to existing PostGIS database.

As Roger pointed out, gdalUtils exposes full functionality of ogr2ogr. 
So the following takes a couple of extra lines of code but works:

```
library(rgdal)
library(gdalUtils)

pts = data.frame(x=runif(10),y=runif(10),z=1:10)
coordinates(pts)=~x+y
writeOGR(pts, "final.sqlite", "pts", driver="SQLite", dataset_options = 
"SPATIALITE=YES")
writeOGR(pts, "tmp.sqlite", "pts2", driver="SQLite", dataset_options = 
"SPATIALITE=YES")

ogr2ogr("tmp.sqlite", "final.sqlite", "pts2", update=TRUE)
file.remove("tmp.sqlite")

```

Some other notes:

Without the -update switch, ogr2ogr will silently overwrite the 
destination.

Note that what writeOGR calls dataset_options are dataset *creation* 
options, so "SPATIALITE=YES" is not needed when adding layers to 
existing SpatiaLite DB. (For that matter, neither is the layer creation 
option "FORMAT=SPATIALITE".)

Best,
--Lee