Skip to content

Commit

Permalink
add import
Browse files Browse the repository at this point in the history
  • Loading branch information
tsamsonov committed Sep 24, 2023
1 parent 99e7763 commit fcc3138
Show file tree
Hide file tree
Showing 13 changed files with 220 additions and 4 deletions.
4 changes: 2 additions & 2 deletions _freeze/adv_05_PostGIS/execute-results/html.json

Large diffs are not rendered by default.

93 changes: 93 additions & 0 deletions adv_05_PostGIS.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -239,4 +239,97 @@ UPDATE postgis.geo_points
:::
:::

## Импорт из шейп-файла

Вместе с **PostGIS** устанавливаются утилиты [**`shp2pgsql`**](https://postgis.net/docs/using_postgis_dbmanagement.html#shp2pgsql_usage) и [**`pgsql2shp`**](https://postgis.net/docs/using_postgis_dbmanagement.html#pgsql2shp-usage) , позволяющие импортировать из и экспортировать данные в формат [Shapefile](https://www.esri.com/content/dam/esrisites/sitecore-archive/Files/Pdfs/library/whitepapers/pdfs/shapefile.pdf).

``` bash
Last login: Fri Sep 22 14:36:05 on console
(base) tsamsonov@Butterfly ~ % shp2pgsql
RELEASE: 3.3.4 (3.3.4)
USAGE: shp2pgsql [<options>] <shapefile> [[<schema>.]<table>]
OPTIONS:
-s [<from>:]<srid> Set the SRID field. Defaults to 0.
Optionally reprojects from given SRID.
(-d|a|c|p) These are mutually exclusive options:
-d Drops the table, then recreates it and populates
it with current shape file data.
-a Appends shape file into current table, must be
exactly the same table schema.
-c Creates a new table and populates it, this is the
default if you do not specify any options.
-p Prepare mode, only creates the table.
```
## shp2pgsql на Windows
При установке путь к утилите не прописывается в переменные среды:
![](images/shp2pgsql_win.png)
## shp2pgsql на Windows
На *Windows* утилита по умолчанию находится в папке `C:\Program Files\PostgreSQL\<version>\bin`
![](images/shp2pgsql.png)
## shp2pgsql на Windows
Чтобы не вводить каждый раз полный путь к программе, необходимо прописать его в переменные окружения:
``` bash
setx path "%PATH%;C:\Program Files\PostgreSQL\15\bin"
```
После этого перезапустите командную строку, и утилита будет запускаться:
![](images/shp2pgsql2.png)
## Импорт из шейп-файла
Если запустить без параметров, то будет только диагностика без импорта:
``` bash
tsamsonov@Butterfly satino_base % shp2pgsql border.shp postgis.border
Field fid is an FTDouble with width 20 and precision 0
Shapefile type: Polygon
Postgis type: MULTIPOLYGON[2]
SET CLIENT_ENCODING TO UTF8;
SET STANDARD_CONFORMING_STRINGS TO ON;
BEGIN;
CREATE TABLE "postgis"."border" (gid serial,
"fid" numeric,
"name" varchar(60));
ALTER TABLE "postgis"."border" ADD PRIMARY KEY (gid);
SELECT AddGeometryColumn('postgis','border','geom','0','MULTIPOLYGON',2);
INSERT INTO "postgis"."border" ("fid","name",geom) VALUES ('1',NULL,'0106000000010000000103000000010000000500000030FF21BDE4231441BAFC8774DB575741503789C1D8231441C05B2081C35B5741F04A59C6FA711441C442AD71C45B5741F0DBD7C106721441BCE31465DC57574130FF21BDE4231441BAFC8774DB575741');
COMMIT;
ANALYZE "postgis"."border";
tsamsonov@Butterfly satino_base %
```
## Импорт из шейп-файла
По факту утилита создает SQL-запрос, который можно направить в файл через `>`:
``` bash
shp2pgsql -g geom border.shp postgis.border > border.sql
```
::: columns
::: {.column width="30%"}
Полученный файл можно открыть средствами СУБД и запустить.
::: callout-tip
## Большие файлы
При импорте больших файлов рекомендуется использовать параметр `-D`, при котором будет создаваться не SQL-запрос, а бинарный файл *дампа* базы данных.
:::
:::
::: {.column width="70%"}
![](images/importsql.png)
:::
:::
## Библиография
81 changes: 81 additions & 0 deletions docs/adv_05_PostGIS.html
Original file line number Diff line number Diff line change
Expand Up @@ -637,6 +637,87 @@ <h2>Активация пространственных точек</h2>
</div>
</div>
</section>
<section id="импорт-из-шейп-файла" class="slide level2">
<h2>Импорт из шейп-файла</h2>
<p>Вместе с <strong>PostGIS</strong> устанавливаются утилиты <a href="https://postgis.net/docs/using_postgis_dbmanagement.html#shp2pgsql_usage"><strong><code>shp2pgsql</code></strong></a> и <a href="https://postgis.net/docs/using_postgis_dbmanagement.html#pgsql2shp-usage"><strong><code>pgsql2shp</code></strong></a> , позволяющие импортировать из и экспортировать данные в формат <a href="https://www.esri.com/content/dam/esrisites/sitecore-archive/Files/Pdfs/library/whitepapers/pdfs/shapefile.pdf">Shapefile</a>.</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode numberSource bash number-lines code-with-copy"><code class="sourceCode bash"><span id="cb9-1"><a href="#cb9-1"></a><span class="ex">Last</span> login: Fri Sep 22 14:36:05 on console</span>
<span id="cb9-2"><a href="#cb9-2"></a><span class="kw">(</span><span class="ex">base</span><span class="kw">)</span> <span class="ex">tsamsonov@Butterfly</span> ~ % shp2pgsql</span>
<span id="cb9-3"><a href="#cb9-3"></a><span class="ex">RELEASE:</span> 3.3.4 <span class="er">(</span><span class="ex">3.3.4</span><span class="kw">)</span></span>
<span id="cb9-4"><a href="#cb9-4"></a><span class="ex">USAGE:</span> shp2pgsql [<span class="op">&lt;</span>options<span class="op">&gt;</span>] <span class="op">&lt;</span>shapefile<span class="op">&gt;</span> [[<span class="op">&lt;</span>schema<span class="op">&gt;</span>.]<span class="op">&lt;</span>table<span class="op">&gt;</span>]</span>
<span id="cb9-5"><a href="#cb9-5"></a><span class="ex">OPTIONS:</span></span>
<span id="cb9-6"><a href="#cb9-6"></a> <span class="ex">-s</span> [<span class="op">&lt;</span>from<span class="op">&gt;</span>:]<span class="op">&lt;</span>srid<span class="op">&gt;</span> Set the SRID field. Defaults to 0.</span>
<span id="cb9-7"><a href="#cb9-7"></a> <span class="ex">Optionally</span> reprojects from given SRID.</span>
<span id="cb9-8"><a href="#cb9-8"></a> <span class="kw">(</span><span class="ex">-d</span><span class="kw">|</span><span class="ex">a</span><span class="kw">|</span><span class="ex">c</span><span class="kw">|</span><span class="ex">p</span><span class="kw">)</span> <span class="ex">These</span> are mutually exclusive options:</span>
<span id="cb9-9"><a href="#cb9-9"></a> <span class="ex">-d</span> Drops the table, then recreates it and populates</span>
<span id="cb9-10"><a href="#cb9-10"></a> <span class="ex">it</span> with current shape file data.</span>
<span id="cb9-11"><a href="#cb9-11"></a> <span class="ex">-a</span> Appends shape file into current table, must be</span>
<span id="cb9-12"><a href="#cb9-12"></a> <span class="ex">exactly</span> the same table schema.</span>
<span id="cb9-13"><a href="#cb9-13"></a> <span class="ex">-c</span> Creates a new table and populates it, this is the</span>
<span id="cb9-14"><a href="#cb9-14"></a> <span class="ex">default</span> if you do not specify any options.</span>
<span id="cb9-15"><a href="#cb9-15"></a> <span class="ex">-p</span> Prepare mode, only creates the table.</span></code><button title="Скопировать текст" class="code-copy-button"><i class="bi"></i></button></pre></div>
</section>
<section id="shp2pgsql-на-windows" class="slide level2">
<h2>shp2pgsql на Windows</h2>
<p>При установке путь к утилите не прописывается в переменные среды:</p>

<img data-src="images/shp2pgsql_win.png" class="r-stretch"></section>
<section id="shp2pgsql-на-windows-1" class="slide level2">
<h2>shp2pgsql на Windows</h2>
<p>На <em>Windows</em> утилита по умолчанию находится в папке <code>C:\Program Files\PostgreSQL\&lt;version&gt;\bin</code></p>

<img data-src="images/shp2pgsql.png" class="r-stretch"></section>
<section id="shp2pgsql-на-windows-2" class="slide level2">
<h2>shp2pgsql на Windows</h2>
<p>Чтобы не вводить каждый раз полный путь к программе, необходимо прописать его в переменные окружения:</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode numberSource bash number-lines code-with-copy"><code class="sourceCode bash"><span id="cb10-1"><a href="#cb10-1"></a><span class="ex">setx</span> path <span class="st">"%PATH%;C:\Program Files\PostgreSQL\15\bin"</span></span></code><button title="Скопировать текст" class="code-copy-button"><i class="bi"></i></button></pre></div>
<p>После этого перезапустите командную строку, и утилита будет запускаться:</p>

<img data-src="images/shp2pgsql2.png" class="r-stretch"></section>
<section id="импорт-из-шейп-файла-1" class="slide level2">
<h2>Импорт из шейп-файла</h2>
<p>Если запустить без параметров, то будет только диагностика без импорта:</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode numberSource bash number-lines code-with-copy"><code class="sourceCode bash"><span id="cb11-1"><a href="#cb11-1"></a><span class="ex">tsamsonov@Butterfly</span> satino_base % shp2pgsql border.shp postgis.border</span>
<span id="cb11-2"><a href="#cb11-2"></a><span class="ex">Field</span> fid is an FTDouble with width 20 and precision 0</span>
<span id="cb11-3"><a href="#cb11-3"></a><span class="ex">Shapefile</span> type: Polygon</span>
<span id="cb11-4"><a href="#cb11-4"></a><span class="ex">Postgis</span> type: MULTIPOLYGON<span class="pp">[</span><span class="ss">2</span><span class="pp">]</span></span>
<span id="cb11-5"><a href="#cb11-5"></a><span class="ex">SET</span> CLIENT_ENCODING TO UTF8<span class="kw">;</span></span>
<span id="cb11-6"><a href="#cb11-6"></a><span class="ex">SET</span> STANDARD_CONFORMING_STRINGS TO ON<span class="kw">;</span></span>
<span id="cb11-7"><a href="#cb11-7"></a><span class="ex">BEGIN</span><span class="kw">;</span></span>
<span id="cb11-8"><a href="#cb11-8"></a><span class="ex">CREATE</span> TABLE <span class="st">"postgis"</span>.<span class="st">"border"</span> <span class="er">(</span><span class="ex">gid</span> serial,</span>
<span id="cb11-9"><a href="#cb11-9"></a><span class="st">"fid"</span> numeric,</span>
<span id="cb11-10"><a href="#cb11-10"></a><span class="st">"name"</span> varchar<span class="er">(</span><span class="ex">60</span><span class="kw">));</span></span>
<span id="cb11-11"><a href="#cb11-11"></a><span class="ex">ALTER</span> TABLE <span class="st">"postgis"</span>.<span class="st">"border"</span> ADD PRIMARY KEY <span class="er">(</span><span class="ex">gid</span><span class="kw">);</span></span>
<span id="cb11-12"><a href="#cb11-12"></a><span class="ex">SELECT</span> AddGeometryColumn<span class="er">(</span><span class="st">'postgis'</span><span class="ex">,</span><span class="st">'border'</span><span class="ex">,</span><span class="st">'geom'</span><span class="ex">,</span><span class="st">'0'</span><span class="ex">,</span><span class="st">'MULTIPOLYGON'</span><span class="ex">,2</span><span class="kw">);</span></span>
<span id="cb11-13"><a href="#cb11-13"></a><span class="ex">INSERT</span> INTO <span class="st">"postgis"</span>.<span class="st">"border"</span> <span class="er">(</span><span class="st">"fid"</span><span class="ex">,</span><span class="st">"name"</span><span class="ex">,geom</span><span class="kw">)</span> <span class="ex">VALUES</span> <span class="er">(</span><span class="st">'1'</span><span class="ex">,NULL,</span><span class="st">'0106000000010000000103000000010000000500000030FF21BDE4231441BAFC8774DB575741503789C1D8231441C05B2081C35B5741F04A59C6FA711441C442AD71C45B5741F0DBD7C106721441BCE31465DC57574130FF21BDE4231441BAFC8774DB575741'</span><span class="kw">);</span></span>
<span id="cb11-14"><a href="#cb11-14"></a><span class="ex">COMMIT</span><span class="kw">;</span></span>
<span id="cb11-15"><a href="#cb11-15"></a><span class="ex">ANALYZE</span> <span class="st">"postgis"</span>.<span class="st">"border"</span><span class="kw">;</span></span>
<span id="cb11-16"><a href="#cb11-16"></a><span class="ex">tsamsonov@Butterfly</span> satino_base % </span></code><button title="Скопировать текст" class="code-copy-button"><i class="bi"></i></button></pre></div>
</section>
<section id="импорт-из-шейп-файла-2" class="slide level2">
<h2>Импорт из шейп-файла</h2>
<p>По факту утилита создает SQL-запрос, который можно направить в файл через <code>&gt;</code>:</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode numberSource bash number-lines code-with-copy"><code class="sourceCode bash"><span id="cb12-1"><a href="#cb12-1"></a><span class="ex">shp2pgsql</span> <span class="at">-g</span> geom border.shp postgis.border <span class="op">&gt;</span> border.sql</span></code><button title="Скопировать текст" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="columns">
<div class="column" style="width:30%;">
<p>Полученный файл можно открыть средствами СУБД и запустить.</p>
<div class="callout callout-tip callout-titled callout-style-default">
<div class="callout-body">
<div class="callout-title">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<p><strong>Большие файлы</strong></p>
</div>
<div class="callout-content">
<p>При импорте больших файлов рекомендуется использовать параметр <code>-D</code>, при котором будет создаваться не SQL-запрос, а бинарный файл <em>дампа</em> базы данных.</p>
</div>
</div>
</div>
</div><div class="column" style="width:70%;">
<p><img data-src="images/importsql.png"></p>
</div>
</div>
</section>
<section id="библиография" class="slide level2">
<h2>Библиография</h2>

Expand Down
Binary file added docs/images/importsql.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/images/shp2pgsql.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/images/shp2pgsql2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/images/shp2pgsql_win.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
42 changes: 42 additions & 0 deletions docs/search.json
Original file line number Diff line number Diff line change
Expand Up @@ -5584,5 +5584,47 @@
"title": "PostGIS. Создание и загрузка данных",
"section": "Активация пространственных точек",
"text": "Активация пространственных точек\n\n\nЕсли данные точечные и содержат координаты в столбцах, то можно на их основе создать геометрию\nALTER TABLE postgis.geo_points \n ADD geom geometry(point, 32637);\nUPDATE postgis.geo_points\n SET geom = ST_Point(x, y)\n\n\nДля преобразования используем одну из функций PostGIS (без или с указанием SRID)."
},
{
"objectID": "adv_05_PostGIS.html#импорт-из-шейп-файла",
"href": "adv_05_PostGIS.html#импорт-из-шейп-файла",
"title": "PostGIS. Создание и загрузка данных",
"section": "Импорт из шейп-файла",
"text": "Импорт из шейп-файла\nВместе с PostGIS устанавливаются утилиты shp2pgsql и pgsql2shp , позволяющие импортировать из и экспортировать данные в формат Shapefile.\nLast login: Fri Sep 22 14:36:05 on console\n(base) tsamsonov@Butterfly ~ % shp2pgsql\nRELEASE: 3.3.4 (3.3.4)\nUSAGE: shp2pgsql [&lt;options&gt;] &lt;shapefile&gt; [[&lt;schema&gt;.]&lt;table&gt;]\nOPTIONS:\n -s [&lt;from&gt;:]&lt;srid&gt; Set the SRID field. Defaults to 0.\n Optionally reprojects from given SRID.\n (-d|a|c|p) These are mutually exclusive options:\n -d Drops the table, then recreates it and populates\n it with current shape file data.\n -a Appends shape file into current table, must be\n exactly the same table schema.\n -c Creates a new table and populates it, this is the\n default if you do not specify any options.\n -p Prepare mode, only creates the table."
},
{
"objectID": "adv_05_PostGIS.html#импорт-из-шейп-файла-1",
"href": "adv_05_PostGIS.html#импорт-из-шейп-файла-1",
"title": "PostGIS. Создание и загрузка данных",
"section": "Импорт из шейп-файла",
"text": "Импорт из шейп-файла\nЕсли запустить без параметров, то будет только диагностика без импорта:\ntsamsonov@Butterfly satino_base % shp2pgsql border.shp postgis.border\nField fid is an FTDouble with width 20 and precision 0\nShapefile type: Polygon\nPostgis type: MULTIPOLYGON[2]\nSET CLIENT_ENCODING TO UTF8;\nSET STANDARD_CONFORMING_STRINGS TO ON;\nBEGIN;\nCREATE TABLE \"postgis\".\"border\" (gid serial,\n\"fid\" numeric,\n\"name\" varchar(60));\nALTER TABLE \"postgis\".\"border\" ADD PRIMARY KEY (gid);\nSELECT AddGeometryColumn('postgis','border','geom','0','MULTIPOLYGON',2);\nINSERT INTO \"postgis\".\"border\" (\"fid\",\"name\",geom) VALUES ('1',NULL,'0106000000010000000103000000010000000500000030FF21BDE4231441BAFC8774DB575741503789C1D8231441C05B2081C35B5741F04A59C6FA711441C442AD71C45B5741F0DBD7C106721441BCE31465DC57574130FF21BDE4231441BAFC8774DB575741');\nCOMMIT;\nANALYZE \"postgis\".\"border\";\ntsamsonov@Butterfly satino_base %"
},
{
"objectID": "adv_05_PostGIS.html#shp2pgsql-на-windows",
"href": "adv_05_PostGIS.html#shp2pgsql-на-windows",
"title": "PostGIS. Создание и загрузка данных",
"section": "shp2pgsql на Windows",
"text": "shp2pgsql на Windows\nПри установке путь к утилите не прописывается в переменные среды:"
},
{
"objectID": "adv_05_PostGIS.html#shp2pgsql-на-windows-1",
"href": "adv_05_PostGIS.html#shp2pgsql-на-windows-1",
"title": "PostGIS. Создание и загрузка данных",
"section": "shp2pgsql на Windows",
"text": "shp2pgsql на Windows\nНа Windows утилита по умолчанию находится в папке C:\\Program Files\\PostgreSQL\\&lt;version&gt;\\bin"
},
{
"objectID": "adv_05_PostGIS.html#shp2pgsql-на-windows-2",
"href": "adv_05_PostGIS.html#shp2pgsql-на-windows-2",
"title": "PostGIS. Создание и загрузка данных",
"section": "shp2pgsql на Windows",
"text": "shp2pgsql на Windows\nЧтобы не вводить каждый раз полный путь к программе, необходимо прописать его в переменные окружения:\nsetx path \"%PATH%;C:\\Program Files\\PostgreSQL\\15\\bin\"\nПосле этого перезапустите командную строку, и утилита будет запускаться:"
},
{
"objectID": "adv_05_PostGIS.html#импорт-из-шейп-файла-2",
"href": "adv_05_PostGIS.html#импорт-из-шейп-файла-2",
"title": "PostGIS. Создание и загрузка данных",
"section": "Импорт из шейп-файла",
"text": "Импорт из шейп-файла\nПо факту утилита создает SQL-запрос, который можно направить в файл через &gt;:\nshp2pgsql -g geom border.shp postgis.border &gt; border.sql\n\n\nПолученный файл можно открыть средствами СУБД и запустить.\n\n\n\n\n\n\nБольшие файлы\n\n\nПри импорте больших файлов рекомендуется использовать параметр -D, при котором будет создаваться не SQL-запрос, а бинарный файл дампа базы данных."
}
]
Binary file added images/importsql.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/shp2pgsql.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/shp2pgsql2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/shp2pgsql_win.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit fcc3138

Please sign in to comment.