Author: Federico Gianoli
License: GNU GPLv3
Version: 2.0
QGIS version: ≥ 3.20 — compatible with QGIS 3.x and 4.x (Qt5 & Qt6)
PG2GPKG is a QGIS plugin that moves data both ways between PostgreSQL/PostGIS and GeoPackage:
- Export — dump entire PostgreSQL/PostGIS databases (or selected tables) to GeoPackage files, with three layout modes and automatic rewriting of QGIS projects stored in the database.
- Import — load one or more layers from a
.gpkgfile into PostgreSQL/PostGIS, with per-layer destination control, field mapping, and reprojection.
-
Three export modes:
- One GeoPackage per schema (
output/schema.gpkg) - Everything in a single GeoPackage (
output/database.gpkg) - One GeoPackage per table (
output/schema/table.gpkg)
- One GeoPackage per schema (
-
Selective export: Tree widget with checkboxes allows selecting individual schemas and tables. Quick-select buttons for "all", "none", or "spatial only".
-
QGIS project export: Detects QGIS projects stored in the database (
qgis_projectstable), exports them as.qgsfiles, and rewrites all PostgreSQL datasource paths to point to the corresponding GeoPackage files. -
Handles edge cases:
fidfields of typedouble/real(GeoPackage requires integer FID)- SSL mode normalization (Qt enum → psycopg2 strings)
- Compressed project formats (zlib, ZIP/.qgz)
- System tables are automatically filtered out
-
Multi-layer batch import: Choose a
.gpkgfile and pick which of its layers to import; each row in the layer table has its own destination schema, table name, and mode. -
Three modes:
- create — fail if the destination table already exists
- append — add features to an existing table
- replace — drop and recreate the destination table, then load
-
Interactive field mapping: Per-layer sub-dialog to include/exclude columns and rename them (with quick
snake_caseconversion). Mappings are persisted as presets per GeoPackage + layer and restored automatically the next time you analyze the same file. -
Layer preview: "View..." opens a read-only preview of the first 50 rows of any layer before importing.
-
Batch helpers: Apply a destination schema, mode, or source SRID to all selected layers at once. "New schema..." creates a schema directly from the dialog (requires
CREATEprivilege). -
Reprojection: Optionally reproject all layers to a target EPSG before loading.
-
Source SRID assignment: Layers that declare no CRS get an editable EPSG field so you can assign one before import (this is not a reprojection — layers that already have a CRS are untouched).
-
Fast loading: Uses GDAL's PostgreSQL driver with
PG_USE_COPY=YES, so inserts go through PostgreSQLCOPYinstead of singleINSERTstatements — typically 5–10× faster than row-by-row imports. -
Pre-import safety checks: Validates destination identifiers, warns on append-mode column mismatches and duplicate destinations, and confirms
replace(DROP CASCADE). A health check detectspg_is_in_recovery()and flags the known 3D/Measured + COPY combination. -
Resilience: Auto-retries on transient PostgreSQL errors (recovery mode, "server closed unexpectedly", "too many connections", …) with 2/5/10 s backoff. A "Retry failed (N)" button re-runs only the layers that failed in the last run.
-
Advanced options (for fragile PostgreSQL servers): disable COPY (fall back to
INSERT), skip the post-load spatial index, force 2D (drop Z/M), and pause N ms between layers. -
Bilingual: Full Italian and English interface (auto-detected from QGIS locale).
- Download or create the
pg2gpkg.zipfile - In QGIS: Plugins → Manage and Install Plugins → Install from ZIP
- Select the ZIP file and click Install Plugin
- Copy the
pg2gpkgfolder to your QGIS plugins directory:- Windows:
%APPDATA%\QGIS\QGIS3\profiles\default\python\plugins\ - Linux:
~/.local/share/QGIS/QGIS3/profiles/default/python/plugins/ - macOS:
~/Library/Application Support/QGIS/QGIS3/profiles/default/python/plugins/
- Windows:
- Restart QGIS
- Enable the plugin in Plugins → Manage and Install Plugins
The plugin requires psycopg2. Install it if not already present:
pip install psycopg2-binaryOn Windows with OSGeo4W:
python -m pip install psycopg2-binary-
Open the plugin from Database → PG2GPKG → Export PostgreSQL to GeoPackage or from the toolbar icon.
-
Select a connection: Choose a registered PostgreSQL connection from the dropdown, or enter parameters manually.
-
Click "Connect and load schemas/tables" to populate the tree widget.
-
Select tables: Use checkboxes to select/deselect individual tables or entire schemas. Use the quick buttons:
- Select all — check everything
- Deselect all — uncheck everything
- Spatial only — check only tables with geometry columns
-
Choose export mode:
- One GeoPackage per schema — creates
schema.gpkgin the output folder, each containing all selected tables from that schema - Single GeoPackage — creates one file with all tables; if multiple schemas are selected, layer names are prefixed with
schema__ - One GeoPackage per table — creates a subfolder per schema with individual
.gpkgfiles
- One GeoPackage per schema — creates
-
Options:
- Export QGIS projects — finds projects in the
qgis_projectstable and exports them with rewritten datasource paths
- Export QGIS projects — finds projects in the
-
Select output folder and click Export.
-
Check the QGIS Log Messages panel (tab "PG2GPKG") for detailed progress and diagnostic information.
-
Open the plugin from Database → PG2GPKG → Import GeoPackage to PostgreSQL or from the toolbar icon.
-
Browse and analyze a
.gpkgfile. The layer table is populated with one row per layer (rows, geometry, SRID). -
Connect to PostgreSQL (same connection picker as the export dialog). After connecting, the destination schema combo on each row is populated with schemas where the current user has
CREATEprivilege. -
Configure each layer in the table:
- Tick / untick to include it in the batch
- Set the destination schema and table name
- Pick a mode (
create/append/replace) - Click Edit... in the Mapping column to rename or exclude individual columns (the mapping is remembered as a preset)
- Click View... in the Preview column to inspect the first rows
- For layers without a CRS, set an EPSG code in the SRID column
Use Apply to all selected layers to set schema / mode / source SRID in bulk, or New schema... to create a schema on the fly.
-
Options:
- Reproject all layers to a target SRID — runs a coordinate transform before insert
-
Advanced options (for fragile PostgreSQL servers) — optional:
- Use COPY — uncheck to fall back to slower but lighter
INSERTstatements - Create spatial index after load — uncheck if the server crashes at the end of large imports
- Force 2D — strips Z/M from 3D/Measured geometries
- Pause between layers — wait N ms between layers to let the server recover
- Use COPY — uncheck to fall back to slower but lighter
-
Click Import. A pre-import check and a server health check may ask for confirmation. If some layers fail (e.g. the database was momentarily in recovery), use Retry failed (N) to re-run just those layers.
If you modify the .ts translation files, compile them to .qm:
cd pg2gpkg/i18n
lrelease pg2gpkg_it.tsOr use the provided script:
python pg2gpkg/i18n/compile_translations.pyAutore: Federico Gianoli
Licenza: GNU GPLv3
Versione: 2.0
Versione QGIS: ≥ 3.20 — compatibile con QGIS 3.x e 4.x (Qt5 e Qt6)
PG2GPKG è un plugin QGIS che sposta i dati nei due sensi tra PostgreSQL/PostGIS e GeoPackage:
- Esportazione — riversa interi database PostgreSQL/PostGIS (o tabelle selezionate) in file GeoPackage, con tre modalità di layout e riscrittura automatica dei progetti QGIS memorizzati nel database.
- Importazione — carica uno o più layer da un file
.gpkgin PostgreSQL/PostGIS, con controllo per-layer della destinazione, mappatura campi e riproiezione.
-
Tre modalità di esportazione:
- Un GeoPackage per schema (
output/schema.gpkg) - Tutto in un unico GeoPackage (
output/database.gpkg) - Un GeoPackage per tabella (
output/schema/tabella.gpkg)
- Un GeoPackage per schema (
-
Esportazione selettiva: Widget ad albero con checkbox per selezionare singoli schemi e tabelle. Pulsanti rapidi per "tutto", "niente" o "solo spaziali".
-
Esportazione progetti QGIS: Rileva i progetti salvati nel database (tabella
qgis_projects), li esporta come file.qgse riscrive tutti i percorsi delle sorgenti dati PostgreSQL per puntare ai file GeoPackage corrispondenti. -
Gestione casi particolari:
- Campi
fiddi tipodouble/real(GeoPackage richiede FID intero) - Normalizzazione modalità SSL (enum Qt → stringhe psycopg2)
- Formati progetto compressi (zlib, ZIP/.qgz)
- Tabelle di sistema filtrate automaticamente
- Campi
-
Import batch multi-layer: scegli un file
.gpkg, seleziona quali layer importare; ogni riga della tabella ha schema, nome tabella e modalità di destinazione indipendenti. -
Tre modalità:
- create — fallisce se la tabella di destinazione esiste già
- append — aggiunge i record a una tabella esistente
- replace — elimina e ricrea la tabella di destinazione prima del caricamento
-
Mappatura campi interattiva: sub-dialog per ogni layer per includere/escludere colonne e rinominarle (con conversione rapida in
snake_case). Le mappature sono salvate come preset per GeoPackage + layer e ripristinate automaticamente alla successiva analisi dello stesso file. -
Anteprima layer: "Visualizza..." apre un'anteprima in sola lettura delle prime 50 righe di un layer prima dell'import.
-
Helper batch: applica schema, modalità o SRID sorgente a tutti i layer selezionati in un colpo solo. "Nuovo schema..." crea uno schema direttamente dal dialog (richiede privilegio
CREATE). -
Riproiezione: opzionalmente riproietta tutti i layer in un EPSG di destinazione prima dell'inserimento.
-
Assegnazione SRID sorgente: ai layer privi di CRS viene offerto un campo EPSG modificabile per assegnarne uno prima dell'import (non è una riproiezione — i layer che hanno già un CRS non vengono toccati).
-
Caricamento veloce: usa il driver PostgreSQL di GDAL con
PG_USE_COPY=YES, sfruttandoCOPYinvece dei singoliINSERT— tipicamente 5–10× più veloce dell'import riga-per-riga. -
Controlli di sicurezza pre-import: valida gli identificatori di destinazione, avvisa su mismatch di colonne in modalità append e su destinazioni duplicate, e chiede conferma per
replace(DROP CASCADE). Un health check rilevapg_is_in_recovery()e segnala la combinazione critica 3D/Measured + COPY. -
Resilienza: ritenta automaticamente sugli errori PostgreSQL transitori (recovery mode, "server closed unexpectedly", "too many connections", …) con backoff 2/5/10 s. Il pulsante "Riprova falliti (N)" riesegue solo i layer falliti nell'ultima esecuzione.
-
Opzioni avanzate (per server PostgreSQL fragili): disabilita COPY (fallback a
INSERT), salta l'indice spaziale post-caricamento, forza 2D (rimuove Z/M), e pausa di N ms tra un layer e l'altro. -
Bilingue: Interfaccia completa in italiano e inglese (rilevamento automatico dalla lingua di QGIS).
- Scarica o crea il file
pg2gpkg.zip - In QGIS: Plugin → Gestisci e installa plugin → Installa da ZIP
- Seleziona il file ZIP e clicca Installa plugin
- Copia la cartella
pg2gpkgnella directory dei plugin QGIS:- Windows:
%APPDATA%\QGIS\QGIS3\profiles\default\python\plugins\ - Linux:
~/.local/share/QGIS/QGIS3/profiles/default/python/plugins/ - macOS:
~/Library/Application Support/QGIS/QGIS3/profiles/default/python/plugins/
- Windows:
- Riavvia QGIS
- Abilita il plugin in Plugin → Gestisci e installa plugin
Il plugin richiede psycopg2. Installalo se non già presente:
pip install psycopg2-binary-
Apri il plugin da Database → PG2GPKG → Esporta PostgreSQL in GeoPackage o dall'icona nella toolbar.
-
Seleziona una connessione: scegli una connessione PostgreSQL registrata o inserisci i parametri manualmente.
-
Clicca "Connetti e carica schemi/tabelle" per popolare l'albero.
-
Seleziona le tabelle con le checkbox. Usa i pulsanti rapidi:
- Seleziona tutto
- Deseleziona tutto
- Solo spaziali — seleziona solo le tabelle con colonne geometria
-
Scegli la modalità di esportazione.
-
Seleziona la cartella di output e clicca Esporta.
-
Controlla il pannello Messaggi di log di QGIS (tab "PG2GPKG") per informazioni dettagliate.
-
Apri il plugin da Database → PG2GPKG → Importa GeoPackage in PostgreSQL o dall'icona nella toolbar.
-
Sfoglia e analizza un file
.gpkg. La tabella dei layer viene popolata con una riga per layer (righe, geometria, SRID). -
Connettiti a PostgreSQL (stesso selettore di connessione del dialog di esportazione). Dopo la connessione, il combo schema di destinazione su ogni riga viene popolato con gli schemi su cui l'utente corrente ha il privilegio
CREATE. -
Configura ogni layer nella tabella:
- Spunta/desconta per includerlo nel batch
- Imposta schema e nome tabella di destinazione
- Scegli una modalità (
create/append/replace) - Clicca Modifica... nella colonna Mappatura per rinominare o escludere singole colonne (la mappatura viene memorizzata come preset)
- Clicca Visualizza... nella colonna Anteprima per ispezionare le prime righe
- Per i layer privi di CRS, imposta un codice EPSG nella colonna SRID
Usa Applica a tutti i layer selezionati per impostare schema / modalità / SRID sorgente in blocco, oppure Nuovo schema... per creare uno schema al volo.
-
Opzioni:
- Riproietta tutti i layer in un SRID di destinazione — esegue una trasformazione di coordinate prima dell'inserimento
-
Opzioni avanzate (per server PostgreSQL fragili) — facoltative:
- Usa COPY — deseleziona per usare gli
INSERT, più lenti ma più leggeri - Crea indice spaziale dopo il caricamento — deseleziona se il server va in crash a fine import
- Forza 2D — rimuove Z/M dalle geometrie 3D/Measured
- Pausa tra i layer — attende N ms tra un layer e l'altro per dare respiro al server
- Usa COPY — deseleziona per usare gli
-
Clicca Importa. Un controllo pre-import e un health check del server potrebbero chiedere conferma. Se alcuni layer falliscono (es. il database era momentaneamente in recovery), usa Riprova falliti (N) per rieseguire solo quei layer.