write_pg.c 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622
  1. /*!
  2. \file lib/vector/Vlib/write_pg.c
  3. \brief Vector library - write vector feature (PostGIS format)
  4. Higher level functions for reading/writing/manipulating vectors.
  5. Write subroutine inspired by OGR PostgreSQL driver.
  6. \todo PostGIS version of V2__delete_area_cats_from_cidx_nat()
  7. \todo function to delete corresponding entry in fidx
  8. \todo PostGIS version of V2__add_area_cats_to_cidx_nat
  9. (C) 2012-2013 by Martin Landa, and the GRASS Development Team
  10. This program is free software under the GNU General Public License
  11. (>=v2). Read the file COPYING that comes with GRASS for details.
  12. \author Martin Landa <landa.martin gmail.com>
  13. */
  14. #include <string.h>
  15. #include <grass/vector.h>
  16. #include <grass/glocale.h>
  17. #include "local_proto.h"
  18. #ifdef HAVE_POSTGRES
  19. #include "pg_local_proto.h"
  20. #define WKBSRIDFLAG 0x20000000
  21. #define TOPOGEOM_COLUMN "topo"
  22. /*! Use SQL statements from PostGIS Topology extension (this options
  23. is quite slow. By default are used simple SQL statements (INSERT, UPDATE)
  24. */
  25. #define USE_TOPO_STMT 0
  26. static int create_table(struct Format_info_pg *, const struct field_info *);
  27. static int check_schema(const struct Format_info_pg *);
  28. static int create_topo_schema(struct Format_info_pg *, int);
  29. static int create_pg_layer(struct Map_info *, int);
  30. static char *get_sftype(SF_FeatureType);
  31. static off_t write_line_sf(struct Map_info *, int,
  32. const struct line_pnts **, int,
  33. const struct line_cats *);
  34. static off_t write_line_tp(struct Map_info *, int, int,
  35. const struct line_pnts *,
  36. const struct line_cats *);
  37. static char *binary_to_hex(int, const unsigned char *);
  38. static unsigned char *point_to_wkb(int, const struct line_pnts *, int, int *);
  39. static unsigned char *linestring_to_wkb(int, const struct line_pnts *,
  40. int, int *);
  41. static unsigned char *polygon_to_wkb(int, const struct line_pnts **, int,
  42. int, int *);
  43. static char *line_to_wkb(struct Format_info_pg *, const struct line_pnts **,
  44. int, int, int);
  45. static int write_feature(struct Map_info *, int, int,
  46. const struct line_pnts **, int, int, const struct field_info *);
  47. static char *build_insert_stmt(const struct Format_info_pg *, const char *, int,
  48. int, const struct field_info *);
  49. static int insert_topo_element(struct Map_info *, int, int, const char *);
  50. static int update_next_edge(struct Map_info*, int, int);
  51. static int delete_face(const struct Map_info *, int);
  52. static int update_topo_edge(struct Map_info *, int);
  53. static int update_topo_face(struct Map_info *, int);
  54. static int add_line_to_topo_pg(struct Map_info *, off_t, int, const struct line_pnts *);
  55. static int delete_line_from_topo_pg(struct Map_info *, int, int, const struct line_pnts *);
  56. #endif
  57. static struct line_pnts *Points;
  58. /*!
  59. \brief Writes feature on level 1 (PostGIS interface)
  60. Notes for simple feature access:
  61. - centroids are not supported in PostGIS, pseudotopo holds virtual
  62. centroids
  63. - boundaries are not supported in PostGIS, pseudotopo treats polygons
  64. as boundaries
  65. Notes for PostGIS Topology access:
  66. - centroids are stored as isolated nodes
  67. - boundaries are stored as edges
  68. \param Map pointer to Map_info structure
  69. \param type feature type (GV_POINT, GV_LINE, ...)
  70. \param points pointer to line_pnts structure (feature geometry)
  71. \param cats pointer to line_cats structure (feature categories)
  72. \return feature offset into file
  73. \return -1 on error
  74. */
  75. off_t V1_write_line_pg(struct Map_info *Map, int type,
  76. const struct line_pnts *points,
  77. const struct line_cats *cats)
  78. {
  79. #ifdef HAVE_POSTGRES
  80. struct Format_info_pg *pg_info;
  81. pg_info = &(Map->fInfo.pg);
  82. if (pg_info->feature_type == SF_UNKNOWN) {
  83. /* create PostGIS table if doesn't exist */
  84. if (create_pg_layer(Map, type) < 0)
  85. return -1;
  86. }
  87. if (!points)
  88. return 0;
  89. if (!pg_info->toposchema_name) { /* simple features access */
  90. return write_line_sf(Map, type, &points, 1, cats);
  91. }
  92. /* PostGIS Topology access */
  93. return write_line_tp(Map, type, FALSE, points, cats);
  94. #else
  95. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  96. return -1;
  97. #endif
  98. }
  99. /*!
  100. \brief Writes feature on topological level (PostGIS interface)
  101. Calls V2_write_line_sfa() for simple features access.
  102. \param Map pointer to Map_info structure
  103. \param type feature type (GV_POINT, GV_LINE, ...)
  104. \param points pointer to line_pnts structure (feature geometry)
  105. \param cats pointer to line_cats structure (feature categories)
  106. \return feature offset into file
  107. \return -1 on error
  108. */
  109. off_t V2_write_line_pg(struct Map_info *Map, int type,
  110. const struct line_pnts *points,
  111. const struct line_cats *cats)
  112. {
  113. #ifdef HAVE_POSTGRES
  114. struct Format_info_pg *pg_info;
  115. pg_info = &(Map->fInfo.pg);
  116. if (!pg_info->toposchema_name) { /* pseudo-topology */
  117. return V2_write_line_sfa(Map, type, points, cats);
  118. }
  119. /* PostGIS Topology */
  120. return write_line_tp(Map, type, FALSE, points, cats);
  121. #else
  122. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  123. return -1;
  124. #endif
  125. }
  126. /*!
  127. \brief Rewrites feature at the given offset (level 1) (PostGIS interface, internal use only)
  128. Only for simple feature access. PostGIS Topology requires level 2.
  129. \todo Use UPDATE statement ?
  130. \param Map pointer to Map_info structure
  131. \param offset feature offset
  132. \param type feature type (GV_POINT, GV_LINE, ...)
  133. \param points feature geometry
  134. \param cats feature categories
  135. \return feature offset (rewriten feature)
  136. \return -1 on error
  137. */
  138. off_t V1_rewrite_line_pg(struct Map_info * Map,
  139. int line, int type, off_t offset,
  140. const struct line_pnts * points,
  141. const struct line_cats * cats)
  142. {
  143. G_debug(3, "V1_rewrite_line_pg(): line=%d type=%d offset=%"PRI_OFF_T,
  144. line, type, offset);
  145. #ifdef HAVE_POSTGRES
  146. if (type != V1_read_line_pg(Map, NULL, NULL, offset)) {
  147. G_warning(_("Unable to rewrite feature (incompatible feature types)"));
  148. return -1;
  149. }
  150. /* delete old */
  151. V1_delete_line_pg(Map, offset);
  152. return V1_write_line_pg(Map, type, points, cats);
  153. #else
  154. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  155. return -1;
  156. #endif
  157. }
  158. /*!
  159. \brief Rewrites feature at topological level (PostGIS interface, internal use only)
  160. Note: Topology must be built at level >= GV_BUILD_BASE
  161. \todo Handle also categories
  162. \todo Store original geometry in tmp table for restore
  163. \param Map pointer to Map_info structure
  164. \param type feature type (GV_POINT, GV_LINE, ...)
  165. \param line feature id
  166. \param points feature geometry
  167. \param cats feature categories
  168. \return offset where feature was rewritten
  169. \return -1 on error
  170. */
  171. off_t V2_rewrite_line_pg(struct Map_info *Map, int line, int type, off_t old_offset,
  172. const struct line_pnts *points, const struct line_cats *cats)
  173. {
  174. G_debug(3, "V2_rewrite_line_pg(): line=%d type=%d offset=%"PRI_OFF_T,
  175. line, type, old_offset);
  176. #ifdef HAVE_POSTGRES
  177. const char *schema_name, *table_name, *keycolumn;
  178. char *stmt, *geom_data;
  179. struct Format_info_pg *pg_info;
  180. struct P_line *Line;
  181. geom_data = NULL;
  182. stmt = NULL;
  183. pg_info = &(Map->fInfo.pg);
  184. if (line < 1 || line > Map->plus.n_lines) {
  185. G_warning(_("Attempt to access feature with invalid id (%d)"), line);
  186. return -1;
  187. }
  188. Line = Map->plus.Line[line];
  189. if (Line == NULL) {
  190. G_warning(_("Attempt to access dead feature %d"), line);
  191. return -1;
  192. }
  193. if (!Points)
  194. Points = Vect_new_line_struct();
  195. if (type != V2_read_line_pg(Map, Points, NULL, line)) {
  196. G_warning(_("Unable to rewrite feature (incompatible feature types)"));
  197. return -1;
  198. }
  199. /* remove line from topology */
  200. if (0 != delete_line_from_topo_pg(Map, line, type, Points))
  201. return -1;
  202. if (pg_info->toposchema_name) { /* PostGIS Topology */
  203. schema_name = pg_info->toposchema_name;
  204. if (type & GV_POINTS) {
  205. table_name = keycolumn = "node";
  206. }
  207. else {
  208. table_name = "edge_data";
  209. keycolumn = "edge";
  210. }
  211. }
  212. else { /* simple features access */
  213. schema_name = pg_info->schema_name;
  214. table_name = pg_info->table_name;
  215. keycolumn = pg_info->fid_column;
  216. }
  217. geom_data = line_to_wkb(pg_info, &points, 1, type, Map->head.with_z);
  218. G_asprintf(&stmt, "UPDATE \"%s\".\"%s\" SET geom = '%s'::GEOMETRY WHERE %s_id = %d",
  219. schema_name, table_name, geom_data, keycolumn, line);
  220. G_free(geom_data);
  221. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  222. G_warning(_("Unable to rewrite feature %d"), line);
  223. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  224. return -1;
  225. }
  226. /* update topology
  227. note: offset is not changed */
  228. return add_line_to_topo_pg(Map, old_offset, type, points);
  229. #else
  230. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  231. return -1;
  232. #endif
  233. }
  234. /*!
  235. \brief Deletes feature at the given offset (level 1)
  236. Only for simple feature access. PostGIS Topology requires level 2.
  237. \param Map pointer Map_info structure
  238. \param offset feature offset
  239. \return 0 on success
  240. \return -1 on error
  241. */
  242. int V1_delete_line_pg(struct Map_info *Map, off_t offset)
  243. {
  244. #ifdef HAVE_POSTGRES
  245. long fid;
  246. char stmt[DB_SQL_MAX];
  247. struct Format_info_pg *pg_info;
  248. pg_info = &(Map->fInfo.pg);
  249. if (!pg_info->conn || !pg_info->table_name) {
  250. G_warning(_("No connection defined"));
  251. return -1;
  252. }
  253. if (offset >= pg_info->offset.array_num) {
  254. G_warning(_("Invalid offset (%d)"), offset);
  255. return -1;
  256. }
  257. fid = pg_info->offset.array[offset];
  258. G_debug(3, "V1_delete_line_pg(): offset = %lu -> fid = %ld",
  259. (unsigned long)offset, fid);
  260. if (!pg_info->inTransaction) {
  261. /* start transaction */
  262. pg_info->inTransaction = TRUE;
  263. if (Vect__execute_pg(pg_info->conn, "BEGIN") == -1)
  264. return -1;
  265. }
  266. sprintf(stmt, "DELETE FROM %s WHERE %s = %ld",
  267. pg_info->table_name, pg_info->fid_column, fid);
  268. G_debug(2, "SQL: %s", stmt);
  269. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  270. G_warning(_("Unable to delete feature"));
  271. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  272. return -1;
  273. }
  274. return 0;
  275. #else
  276. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  277. return -1;
  278. #endif
  279. }
  280. /*!
  281. \brief Deletes feature on topological level (PostGIS interface)
  282. Note: Topology must be built at level >= GV_BUILD_BASE
  283. Calls V2_delete_line_sfa() for simple feature access.
  284. \param Map pointer to Map_info structure
  285. \param line feature id to be deleted
  286. \return 0 on success
  287. \return -1 on error
  288. */
  289. int V2_delete_line_pg(struct Map_info *Map, int line)
  290. {
  291. #ifdef HAVE_POSTGRES
  292. struct Format_info_pg *pg_info;
  293. pg_info = &(Map->fInfo.pg);
  294. if (line < 1 || line > Map->plus.n_lines) {
  295. G_warning(_("Attempt to access feature with invalid id (%d)"), line);
  296. return -1;
  297. }
  298. if (!pg_info->toposchema_name) { /* pseudo-topology */
  299. return V2_delete_line_sfa(Map, line);
  300. }
  301. else { /* PostGIS topology */
  302. int type;
  303. char stmt[DB_SQL_MAX];
  304. const char *table_name, *keycolumn;
  305. struct P_line *Line;
  306. if (line < 1 || line > Map->plus.n_lines) {
  307. G_warning(_("Attempt to access feature with invalid id (%d)"), line);
  308. return -1;
  309. }
  310. Line = Map->plus.Line[line];
  311. if (!Line) {
  312. G_warning(_("Attempt to access dead feature %d"), line);
  313. return -1;
  314. }
  315. if (Line->type & GV_POINTS) {
  316. table_name = keycolumn = "node";
  317. }
  318. else {
  319. table_name = "edge_data";
  320. keycolumn = "edge";
  321. /* first remove references to this edge */
  322. /* (1) left next edge */
  323. sprintf(stmt, "UPDATE \"%s\".\"%s\" SET abs_next_left_edge = edge_id, "
  324. "next_left_edge = -edge_id WHERE abs_next_left_edge = %d",
  325. pg_info->toposchema_name, table_name, (int)Line->offset);
  326. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  327. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  328. return -1;
  329. }
  330. /* (2) right next edge */
  331. sprintf(stmt, "UPDATE \"%s\".\"%s\" SET abs_next_right_edge = edge_id, "
  332. "next_right_edge = edge_id WHERE abs_next_right_edge = %d",
  333. pg_info->toposchema_name, table_name, (int)Line->offset);
  334. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  335. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  336. return -1;
  337. }
  338. }
  339. /* read the line */
  340. if (!Points)
  341. Points = Vect_new_line_struct();
  342. type = V2_read_line_pg(Map, Points, NULL, line);
  343. if (type < 0)
  344. return -1;
  345. /* delete record from topology table */
  346. sprintf(stmt, "DELETE FROM \"%s\".\"%s\" WHERE %s_id = %d",
  347. pg_info->toposchema_name, table_name, keycolumn, (int)Line->offset);
  348. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  349. G_warning(_("Unable to delete feature (%s) %d"), keycolumn,
  350. line);
  351. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  352. return -1;
  353. }
  354. /* update topology */
  355. return delete_line_from_topo_pg(Map, line, type, Points);
  356. }
  357. #else
  358. G_fatal_error(_("GRASS is not compiled with PostgreSQL support"));
  359. return -1;
  360. #endif
  361. }
  362. #ifdef HAVE_POSTGRES
  363. /*!
  364. \brief Writes node on topological level (PostGIS Topology
  365. interface, internal use only)
  366. The vector map must be open on level 2 at least with
  367. GV_BUILD_BASE. PostGIS Topology schema must be defined.
  368. \param Map pointer to Map_info structure
  369. \param points pointer to line_pnts structure
  370. \return 0 on success
  371. \return -1 on error
  372. */
  373. off_t V2__write_node_pg(struct Map_info *Map, const struct line_pnts *points)
  374. {
  375. struct Format_info_pg *pg_info;
  376. pg_info = &(Map->fInfo.pg);
  377. if (!pg_info->toposchema_name)
  378. return -1; /* PostGIS Topology required */
  379. return write_line_tp(Map, GV_POINT, TRUE, points, NULL);
  380. }
  381. /*!
  382. \brief Writes area on topological level (PostGIS Simple Features
  383. interface, internal use only)
  384. \param Map pointer to Map_info structure
  385. \param points feature geometry (exterior + interior rings)
  386. \param nparts number of parts including exterior ring
  387. \param cats feature categories
  388. \return feature offset
  389. \return -1 on error
  390. */
  391. off_t V2__write_area_pg(struct Map_info *Map,
  392. const struct line_pnts **points, int nparts,
  393. const struct line_cats *cats)
  394. {
  395. return write_line_sf(Map, GV_BOUNDARY, points, nparts, cats);
  396. }
  397. /*!
  398. \brief Create new feature table
  399. \param pg_info pointer to Format_info_pg
  400. \param Fi pointer to field_info
  401. \return -1 on error
  402. \return 0 on success
  403. */
  404. int create_table(struct Format_info_pg *pg_info, const struct field_info *Fi)
  405. {
  406. int spatial_index, primary_key;
  407. char stmt[DB_SQL_MAX];
  408. char *geom_type, *def_file;
  409. PGresult *result;
  410. def_file = getenv("GRASS_VECTOR_PGFILE");
  411. /* by default create spatial index & add primary key */
  412. spatial_index = primary_key = TRUE;
  413. if (G_find_file2("", def_file ? def_file : "PG", G_mapset())) {
  414. FILE *fp;
  415. const char *p;
  416. struct Key_Value *key_val;
  417. fp = G_fopen_old("", def_file ? def_file : "PG", G_mapset());
  418. if (!fp) {
  419. G_warning(_("Unable to open PG file"));
  420. }
  421. else {
  422. key_val = G_fread_key_value(fp);
  423. fclose(fp);
  424. /* disable spatial index ? */
  425. p = G_find_key_value("spatial_index", key_val);
  426. if (p && G_strcasecmp(p, "no") == 0)
  427. spatial_index = FALSE;
  428. /* disable primary key ? */
  429. p = G_find_key_value("primary_key", key_val);
  430. if (p && G_strcasecmp(p, "no") == 0)
  431. primary_key = FALSE;
  432. }
  433. }
  434. /* create schema if not exists */
  435. if (G_strcasecmp(pg_info->schema_name, "public") != 0) {
  436. if (check_schema(pg_info) != 0)
  437. return -1;
  438. }
  439. /* prepare CREATE TABLE statement */
  440. sprintf(stmt, "CREATE TABLE \"%s\".\"%s\" (%s SERIAL%s, %s INTEGER",
  441. pg_info->schema_name, pg_info->table_name, pg_info->fid_column,
  442. primary_key ? " PRIMARY KEY" : "", GV_KEY_COLUMN);
  443. if (Fi) {
  444. /* append attributes */
  445. int col, ncols, sqltype, length;
  446. char stmt_col[DB_SQL_MAX];
  447. const char *colname;
  448. dbString dbtable_name;
  449. dbHandle handle;
  450. dbDriver *driver;
  451. dbTable *table;
  452. dbColumn *column;
  453. db_init_string(&dbtable_name);
  454. db_init_handle(&handle);
  455. pg_info->dbdriver = driver = db_start_driver(Fi->driver);
  456. if (!driver) {
  457. G_warning(_("Unable to start driver <%s>"), Fi->driver);
  458. return -1;
  459. }
  460. db_set_handle(&handle, Fi->database, NULL);
  461. if (db_open_database(driver, &handle) != DB_OK) {
  462. G_warning(_("Unable to open database <%s> by driver <%s>"),
  463. Fi->database, Fi->driver);
  464. db_close_database_shutdown_driver(driver);
  465. pg_info->dbdriver = NULL;
  466. return -1;
  467. }
  468. /* describe table */
  469. db_set_string(&dbtable_name, Fi->table);
  470. if (db_describe_table(driver, &dbtable_name, &table) != DB_OK) {
  471. G_warning(_("Unable to desribe table <%s>"),
  472. Fi->table);
  473. db_close_database_shutdown_driver(driver);
  474. pg_info->dbdriver = NULL;
  475. return -1;
  476. }
  477. ncols = db_get_table_number_of_columns(table);
  478. G_debug(3,
  479. "copying attributes: driver = %s database = %s table = %s cols = %d",
  480. Fi->driver, Fi->database, Fi->table, ncols);
  481. for (col = 0; col < ncols; col++) {
  482. column = db_get_table_column(table, col);
  483. colname = db_get_column_name(column);
  484. sqltype = db_get_column_sqltype(column);
  485. length = db_get_column_length(column);
  486. G_debug(3, "\tcolumn = %d name = %s type = %d length = %d",
  487. col, colname, sqltype, length);
  488. if (strcmp(pg_info->fid_column, colname) == 0 ||
  489. strcmp(GV_KEY_COLUMN, colname) == 0) {
  490. /* skip fid column if exists */
  491. G_debug(3, "\t%s skipped", colname);
  492. continue;
  493. }
  494. /* append column */
  495. sprintf(stmt_col, ",%s %s", colname, db_sqltype_name(sqltype));
  496. strcat(stmt, stmt_col);
  497. if (sqltype == DB_SQL_TYPE_CHARACTER) {
  498. /* length only for string columns */
  499. sprintf(stmt_col, "(%d)", length);
  500. strcat(stmt, stmt_col);
  501. }
  502. }
  503. db_free_string(&dbtable_name);
  504. }
  505. strcat(stmt, ")"); /* close CREATE TABLE statement */
  506. /* begin transaction (create table) */
  507. if (Vect__execute_pg(pg_info->conn, "BEGIN") == -1) {
  508. return -1;
  509. }
  510. /* create table */
  511. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  512. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  513. return -1;
  514. }
  515. /* determine geometry type (string) */
  516. switch (pg_info->feature_type) {
  517. case (SF_POINT):
  518. geom_type = "POINT";
  519. break;
  520. case (SF_LINESTRING):
  521. geom_type = "LINESTRING";
  522. break;
  523. case (SF_POLYGON):
  524. geom_type = "POLYGON";
  525. break;
  526. case (SF_POLYGON25D):
  527. geom_type = "POLYGONZ";
  528. break;
  529. default:
  530. G_warning(_("Unsupported feature type %d"), pg_info->feature_type);
  531. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  532. return -1;
  533. }
  534. /* add geometry column */
  535. sprintf(stmt, "SELECT AddGeometryColumn('%s', '%s', "
  536. "'%s', %d, '%s', %d)",
  537. pg_info->schema_name, pg_info->table_name,
  538. pg_info->geom_column, pg_info->srid,
  539. geom_type, pg_info->coor_dim);
  540. G_debug(2, "SQL: %s", stmt);
  541. result = PQexec(pg_info->conn, stmt);
  542. if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
  543. G_warning("%s", PQresultErrorMessage(result));
  544. PQclear(result);
  545. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  546. return -1;
  547. }
  548. /* create indeces
  549. - GV_KEY_COLUMN
  550. - geometry column
  551. */
  552. sprintf(stmt,
  553. "CREATE INDEX %s_%s_idx ON \"%s\".\"%s\" (%s)",
  554. pg_info->table_name, GV_KEY_COLUMN,
  555. pg_info->schema_name, pg_info->table_name,
  556. GV_KEY_COLUMN);
  557. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  558. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  559. return -1;
  560. }
  561. if (spatial_index) {
  562. G_verbose_message(_("Building spatial index on <%s>..."),
  563. pg_info->geom_column);
  564. sprintf(stmt,
  565. "CREATE INDEX %s_%s_idx ON \"%s\".\"%s\" USING GIST (%s)",
  566. pg_info->table_name, pg_info->geom_column,
  567. pg_info->schema_name, pg_info->table_name,
  568. pg_info->geom_column);
  569. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  570. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  571. return -1;
  572. }
  573. }
  574. /* close transaction (create table) */
  575. if (Vect__execute_pg(pg_info->conn, "COMMIT") == -1) {
  576. return -1;
  577. }
  578. return 0;
  579. }
  580. /*!
  581. \brief Creates new schema for feature table if not exists
  582. \param pg_info pointer to Format_info_pg
  583. \return -1 on error
  584. \return 0 on success
  585. */
  586. int check_schema(const struct Format_info_pg *pg_info)
  587. {
  588. int i, found, nschema;
  589. char stmt[DB_SQL_MAX];
  590. PGresult *result;
  591. /* add geometry column */
  592. sprintf(stmt, "SELECT nspname FROM pg_namespace");
  593. G_debug(2, "SQL: %s", stmt);
  594. result = PQexec(pg_info->conn, stmt);
  595. if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
  596. PQclear(result);
  597. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  598. return -1;
  599. }
  600. found = FALSE;
  601. nschema = PQntuples(result);
  602. for (i = 0; i < nschema && !found; i++) {
  603. if (strcmp(pg_info->schema_name, PQgetvalue(result, i, 0)) == 0)
  604. found = TRUE;
  605. }
  606. PQclear(result);
  607. if (!found) {
  608. sprintf(stmt, "CREATE SCHEMA %s", pg_info->schema_name);
  609. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  610. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  611. return -1;
  612. }
  613. G_warning(_("Schema <%s> doesn't exist, created"),
  614. pg_info->schema_name);
  615. }
  616. return 0;
  617. }
  618. /*!
  619. \brief Create new PostGIS topology schema
  620. - create topology schema
  621. - add topology column to the feature table
  622. \param pg_info pointer to Format_info_pg
  623. \return 0 on success
  624. \return 1 topology disable, nothing to do
  625. \return -1 on failure
  626. */
  627. int create_topo_schema(struct Format_info_pg *pg_info, int with_z)
  628. {
  629. double tolerance;
  630. char stmt[DB_SQL_MAX];
  631. char *def_file;
  632. PGresult *result;
  633. def_file = getenv("GRASS_VECTOR_PGFILE");
  634. /* read default values from PG file*/
  635. tolerance = 0.;
  636. if (G_find_file2("", def_file ? def_file : "PG", G_mapset())) {
  637. FILE *fp;
  638. const char *p;
  639. struct Key_Value *key_val;
  640. fp = G_fopen_old("", def_file ? def_file : "PG", G_mapset());
  641. if (!fp) {
  642. G_fatal_error(_("Unable to open PG file"));
  643. }
  644. key_val = G_fread_key_value(fp);
  645. fclose(fp);
  646. /* tolerance */
  647. p = G_find_key_value("tolerance", key_val);
  648. if (p)
  649. tolerance = atof(p);
  650. /* topogeom column */
  651. p = G_find_key_value("topogeom_column", key_val);
  652. if (p)
  653. pg_info->topogeom_column = G_store(p);
  654. else
  655. pg_info->topogeom_column = G_store(TOPOGEOM_COLUMN);
  656. }
  657. /* begin transaction (create topo schema) */
  658. if (Vect__execute_pg(pg_info->conn, "BEGIN") == -1) {
  659. return -1;
  660. }
  661. /* create topology schema */
  662. G_verbose_message(_("Creating topology schema <%s>..."),
  663. pg_info->toposchema_name);
  664. sprintf(stmt, "SELECT topology.createtopology('%s', "
  665. "find_srid('%s', '%s', '%s'), %f, '%s')",
  666. pg_info->toposchema_name, pg_info->schema_name,
  667. pg_info->table_name, pg_info->geom_column, tolerance,
  668. with_z == WITH_Z ? "t" : "f");
  669. G_debug(2, "SQL: %s", stmt);
  670. result = PQexec(pg_info->conn, stmt);
  671. if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
  672. G_warning(_("Execution failed: %s"), PQerrorMessage(pg_info->conn));
  673. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  674. return -1;
  675. }
  676. /* store toposchema id */
  677. pg_info->toposchema_id = atoi(PQgetvalue(result, 0, 0));
  678. /* add topo column to the feature table */
  679. G_verbose_message(_("Adding new topology column <%s>..."),
  680. pg_info->topogeom_column);
  681. sprintf(stmt, "SELECT topology.AddTopoGeometryColumn('%s', '%s', '%s', "
  682. "'%s', '%s')", pg_info->toposchema_name, pg_info->schema_name,
  683. pg_info->table_name, pg_info->topogeom_column,
  684. get_sftype(pg_info->feature_type));
  685. G_debug(2, "SQL: %s", stmt);
  686. result = PQexec(pg_info->conn, stmt);
  687. if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
  688. G_warning(_("Execution failed: %s"), PQerrorMessage(pg_info->conn));
  689. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  690. return -1;
  691. }
  692. /* close transaction (create topo schema) */
  693. if (Vect__execute_pg(pg_info->conn, "COMMIT") == -1) {
  694. return -1;
  695. }
  696. return 0;
  697. }
  698. /*!
  699. \brief Create new PostGIS layer in given database (internal use only)
  700. V1_open_new_pg() must be called before this function.
  701. List of currently supported types:
  702. - GV_POINT (SF_POINT)
  703. - GV_LINE (SF_LINESTRING)
  704. - GV_BOUNDARY (SF_POLYGON)
  705. When PostGIS Topology the map level is updated to topological level
  706. and build level set to GV_BUILD_BASE.
  707. \param[in,out] Map pointer to Map_info structure
  708. \param type feature type (GV_POINT, GV_LINE, ...)
  709. \return 0 success
  710. \return -1 error
  711. */
  712. int create_pg_layer(struct Map_info *Map, int type)
  713. {
  714. int ndblinks;
  715. struct Format_info_pg *pg_info;
  716. struct field_info *Fi;
  717. Fi = NULL;
  718. pg_info = &(Map->fInfo.pg);
  719. if (!pg_info->conninfo) {
  720. G_warning(_("Connection string not defined"));
  721. return -1;
  722. }
  723. if (!pg_info->table_name) {
  724. G_warning(_("PostGIS feature table not defined"));
  725. return -1;
  726. }
  727. G_debug(1, "Vect__open_new_pg(): conninfo='%s' table='%s' -> type = %d",
  728. pg_info->conninfo, pg_info->table_name, type);
  729. /* determine geometry type */
  730. switch (type) {
  731. case GV_POINT:
  732. pg_info->feature_type = SF_POINT;
  733. break;
  734. case GV_LINE:
  735. pg_info->feature_type = SF_LINESTRING;
  736. break;
  737. case GV_BOUNDARY:
  738. pg_info->feature_type = SF_POLYGON;
  739. break;
  740. case GV_FACE:
  741. pg_info->feature_type = SF_POLYGON25D;
  742. break;
  743. default:
  744. G_warning(_("Unsupported geometry type (%d)"), type);
  745. return -1;
  746. }
  747. /* coordinate dimension */
  748. pg_info->coor_dim = Vect_is_3d(Map) ? 3 : 2;
  749. /* create new PostGIS table */
  750. ndblinks = Vect_get_num_dblinks(Map);
  751. if (ndblinks > 0) {
  752. Fi = Vect_get_dblink(Map, 0);
  753. if (Fi) {
  754. if (ndblinks > 1)
  755. G_warning(_("More layers defined, using driver <%s> and "
  756. "database <%s>"), Fi->driver, Fi->database);
  757. }
  758. else {
  759. G_warning(_("Database connection not defined. "
  760. "Unable to write attributes."));
  761. }
  762. }
  763. /* create new feature table */
  764. if (create_table(pg_info, Fi) == -1) {
  765. G_warning(_("Unable to create new PostGIS feature table"));
  766. return -1;
  767. }
  768. /* create new topology schema (if PostGIS topology support is enabled) */
  769. if (pg_info->toposchema_name) {
  770. /* force topological level */
  771. Map->level = LEVEL_2;
  772. Map->plus.built = GV_BUILD_BASE;
  773. /* track updated features, used in V2__add_line_to_topo_nat() */
  774. Vect_set_updated(Map, TRUE);
  775. if (create_topo_schema(pg_info, Vect_is_3d(Map)) == -1) {
  776. G_warning(_("Unable to create new PostGIS topology schema"));
  777. return -1;
  778. }
  779. }
  780. if (Fi)
  781. G_free(Fi);
  782. return 0;
  783. }
  784. /*!
  785. \brief Get simple feature type as a string
  786. Used for AddTopoGeometryColumn().
  787. Valid types:
  788. - SF_POINT
  789. - SF_LINESTRING
  790. - SF_POLYGON
  791. \return string with feature type
  792. \return empty string
  793. */
  794. char *get_sftype(SF_FeatureType sftype)
  795. {
  796. if (sftype == SF_POINT)
  797. return "POINT";
  798. else if (sftype == SF_LINESTRING)
  799. return "LINE";
  800. else if (sftype == SF_POLYGON)
  801. return "POLYGON";
  802. else
  803. G_warning(_("Unsupported feature type %d"), sftype);
  804. return "";
  805. }
  806. /*!
  807. \brief Write vector features as PostGIS simple feature element
  808. \param Map pointer to Map_info structure
  809. \param type feature type (GV_POINT, GV_LINE, ...)
  810. \param points feature geometry (exterior + interior rings for polygonsx)
  811. \param nparts number of parts
  812. \param cats feature categories
  813. \return feature offset
  814. \return -1 on error
  815. */
  816. off_t write_line_sf(struct Map_info *Map, int type,
  817. const struct line_pnts **points, int nparts,
  818. const struct line_cats *cats)
  819. {
  820. int cat;
  821. off_t offset;
  822. SF_FeatureType sf_type;
  823. struct field_info *Fi;
  824. struct Format_info_pg *pg_info;
  825. struct Format_info_offset *offset_info;
  826. pg_info = &(Map->fInfo.pg);
  827. offset_info = &(pg_info->offset);
  828. if (nparts < 1)
  829. return -1;
  830. /* check required PG settings */
  831. if (!pg_info->conn) {
  832. G_warning(_("No connection defined"));
  833. return -1;
  834. }
  835. if (!pg_info->table_name) {
  836. G_warning(_("PostGIS feature table not defined"));
  837. return -1;
  838. }
  839. /* create PostGIS table if doesn't exist */
  840. if (pg_info->feature_type == SF_UNKNOWN) {
  841. if (create_pg_layer(Map, type) < 0)
  842. return -1;
  843. }
  844. /* get category & check for attributes */
  845. Fi = NULL;
  846. cat = -1;
  847. if (cats->n_cats > 0) {
  848. int field;
  849. field = cats->field[0]; /* we assume only one layer defined */
  850. if (Vect_get_num_dblinks(Map) > 0) {
  851. /* check for attributes */
  852. Fi = Vect_get_field(Map, field);
  853. }
  854. if (!Vect_cat_get(cats, field, &cat))
  855. G_warning(_("No category defined for layer %d"), field);
  856. if (cats->n_cats > 1) {
  857. G_warning(_("Feature has more categories, using "
  858. "category %d (from layer %d)"),
  859. cat, field);
  860. }
  861. }
  862. sf_type = pg_info->feature_type;
  863. /* determine matching PostGIS feature geometry type */
  864. if (type & (GV_POINT | GV_KERNEL)) {
  865. if (sf_type != SF_POINT && sf_type != SF_POINT25D) {
  866. G_warning(_("Point skipped (output feature type: %s)"),
  867. Vect_get_finfo_geometry_type(Map));
  868. return 0;
  869. }
  870. }
  871. else if (type & GV_LINE) {
  872. if (sf_type != SF_LINESTRING && sf_type != SF_LINESTRING25D) {
  873. G_warning(_("Line skipped (output feature type: %s)"),
  874. Vect_get_finfo_geometry_type(Map));
  875. return 0;
  876. }
  877. }
  878. else if (type & GV_BOUNDARY || type & GV_CENTROID) {
  879. if (sf_type != SF_POLYGON) {
  880. G_warning(_("Boundary/centroid skipped (output feature type: %s)"),
  881. Vect_get_finfo_geometry_type(Map));
  882. G_warning(_("Feature is not a polygon. Skipping."));
  883. return 0;
  884. }
  885. }
  886. else if (type & GV_FACE) {
  887. if (sf_type != SF_POLYGON25D) {
  888. G_warning(_("Face skipped (output feature type: %s)"),
  889. Vect_get_finfo_geometry_type(Map));
  890. return 0;
  891. }
  892. }
  893. else {
  894. G_warning(_("Unsupported feature type %d"), type);
  895. return -1;
  896. }
  897. G_debug(3, "write_line_sf(): type = %d n_points = %d cat = %d",
  898. type, points[0]->n_points, cat);
  899. if (sf_type == SF_POLYGON || sf_type == SF_POLYGON25D) {
  900. /* skip this check when writing PostGIS topology */
  901. int part, npoints;
  902. for (part = 0; part < nparts; part++) {
  903. npoints = points[part]->n_points - 1;
  904. if (points[part]->x[0] != points[part]->x[npoints] ||
  905. points[part]->y[0] != points[part]->y[npoints] ||
  906. points[part]->z[0] != points[part]->z[npoints]) {
  907. G_warning(_("Boundary is not closed. Skipping."));
  908. return -1;
  909. }
  910. }
  911. }
  912. /* write feature's geometry and fid */
  913. if (-1 == write_feature(Map, -1, type, points, nparts, cat, Fi)) {
  914. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  915. return -1;
  916. }
  917. /* update offset array */
  918. if (offset_info->array_num >= offset_info->array_alloc) {
  919. offset_info->array_alloc += 1000;
  920. offset_info->array = (int *)G_realloc(offset_info->array,
  921. offset_info->array_alloc *
  922. sizeof(int));
  923. }
  924. offset = offset_info->array_num;
  925. offset_info->array[offset_info->array_num++] = cat;
  926. if (sf_type == SF_POLYGON || sf_type == SF_POLYGON25D) {
  927. /* register first part in offset array */
  928. offset_info->array[offset_info->array_num++] = 0;
  929. }
  930. G_debug(3, "write_line_sf(): -> offset = %lu offset_num = %d cat = %d",
  931. (unsigned long)offset, offset_info->array_num, cat);
  932. return offset;
  933. }
  934. /*!
  935. \brief Write vector feature in PostGIS topology schema and
  936. updates internal topology structures
  937. \param Map vector map
  938. \param type feature type to be written
  939. \param points feature geometry
  940. \param is_node TRUE for nodes (written as points)
  941. \return feature id (build level >= GV_BUILD_BASE otherwise 0)
  942. \return -1 on error
  943. */
  944. off_t write_line_tp(struct Map_info *Map, int type, int is_node,
  945. const struct line_pnts *points,
  946. const struct line_cats *cats)
  947. {
  948. int line, cat;
  949. struct field_info *Fi;
  950. struct Format_info_pg *pg_info;
  951. struct Plus_head *plus;
  952. pg_info = &(Map->fInfo.pg);
  953. plus = &(Map->plus);
  954. /* check type for nodes */
  955. if (is_node && type != GV_POINT) {
  956. G_warning(_("Invalid feature type (%d) for nodes"), type);
  957. return -1;
  958. }
  959. /* check required PG settings */
  960. if (!pg_info->conn) {
  961. G_warning(_("No connection defined"));
  962. return -1;
  963. }
  964. if (!pg_info->table_name) {
  965. G_warning(_("PostGIS feature table not defined"));
  966. return -1;
  967. }
  968. if (!pg_info->toposchema_name) {
  969. G_warning(_("PostGIS topology schema not defined"));
  970. return -1;
  971. }
  972. /* create PostGIS table if doesn't exist */
  973. if (pg_info->feature_type == SF_UNKNOWN) {
  974. if (create_pg_layer(Map, type) < 0)
  975. return -1;
  976. }
  977. if (!points)
  978. return 0;
  979. G_debug(3, "write_line_pg(): type = %d n_points = %d",
  980. type, points->n_points);
  981. Fi = NULL; /* no attributes to be written */
  982. cat = -1;
  983. if (cats && cats->n_cats > 0) {
  984. if (Vect_get_num_dblinks(Map) > 0) {
  985. /* check for attributes */
  986. Fi = Vect_get_dblink(Map, 0);
  987. if (Fi) {
  988. if (!Vect_cat_get(cats, Fi->number, &cat))
  989. G_warning(_("No category defined for layer %d"), Fi->number);
  990. if (cats->n_cats > 1) {
  991. G_warning(_("Feature has more categories, using "
  992. "category %d (from layer %d)"),
  993. cat, cats->field[0]);
  994. }
  995. }
  996. }
  997. /* assume layer=1 */
  998. Vect_cat_get(cats, 1, &cat);
  999. }
  1000. /* update GRASS topology before writing PostGIS feature */
  1001. line = 0;
  1002. if (plus->built >= GV_BUILD_BASE) {
  1003. if (is_node) {
  1004. /* nodes are given with negative id */
  1005. line = -1 * dig_add_node(plus, points->x[0], points->y[0], points->z[0]);
  1006. }
  1007. else {
  1008. off_t offset;
  1009. /* better is probably to check nextval directly */
  1010. if (type & GV_POINTS) {
  1011. offset = Vect_get_num_primitives(Map, GV_POINTS) + 1; /* next */
  1012. offset += Vect_get_num_nodes(Map); /* nodes are also stored in 'node' table */
  1013. }
  1014. else { /* LINES */
  1015. offset = Vect_get_num_primitives(Map, GV_LINES) + 1; /* next */
  1016. }
  1017. line = add_line_to_topo_pg(Map, offset, type, points);
  1018. }
  1019. }
  1020. /* write new feature to PostGIS
  1021. - feature table for simple features
  1022. - feature table and topo schema for topological access
  1023. */
  1024. if (-1 == write_feature(Map, line, type, &points, 1, cat, Fi)) {
  1025. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1026. return -1;
  1027. }
  1028. /* update PostGIS-line topo */
  1029. if (plus->built >= GV_BUILD_AREAS && type == GV_BOUNDARY)
  1030. update_topo_face(Map, line); /* TODO: avoid extra statements */
  1031. return !is_node ? line : 0;
  1032. }
  1033. /*!
  1034. \brief Binary data to HEX
  1035. Allocated buffer should be freed by G_free().
  1036. \param nbytes number of bytes to allocate
  1037. \param wkb_data WKB data
  1038. \return allocated buffer with HEX data
  1039. */
  1040. char *binary_to_hex(int nbytes, const unsigned char *wkb_data)
  1041. {
  1042. char *hex_data;
  1043. int i, nlow, nhigh;
  1044. static const char ach_hex[] = "0123456789ABCDEF";
  1045. hex_data = (char *)G_malloc(nbytes * 2 + 1);
  1046. hex_data[nbytes * 2] = '\0';
  1047. for (i = 0; i < nbytes; i++) {
  1048. nlow = wkb_data[i] & 0x0f;
  1049. nhigh = (wkb_data[i] & 0xf0) >> 4;
  1050. hex_data[i * 2] = ach_hex[nhigh];
  1051. hex_data[i * 2 + 1] = ach_hex[nlow];
  1052. }
  1053. return hex_data;
  1054. }
  1055. /*!
  1056. \brief Write point into WKB buffer
  1057. See OGRPoint::exportToWkb from GDAL/OGR library
  1058. \param byte_order byte order (ENDIAN_LITTLE or BIG_ENDIAN)
  1059. \param points feature geometry
  1060. \param with_z WITH_Z for 3D data
  1061. \param[out] nsize buffer size
  1062. \return allocated WKB buffer
  1063. \return NULL on error
  1064. */
  1065. unsigned char *point_to_wkb(int byte_order,
  1066. const struct line_pnts *points, int with_z,
  1067. int *nsize)
  1068. {
  1069. unsigned char *wkb_data;
  1070. unsigned int sf_type;
  1071. if (points->n_points != 1)
  1072. return NULL;
  1073. /* allocate buffer */
  1074. *nsize = with_z ? 29 : 21;
  1075. wkb_data = G_malloc(*nsize);
  1076. G_zero(wkb_data, *nsize);
  1077. G_debug(5, "\t->point size=%d (with_z = %d)", *nsize, with_z);
  1078. /* set the byte order */
  1079. if (byte_order == ENDIAN_LITTLE)
  1080. wkb_data[0] = '\001';
  1081. else
  1082. wkb_data[0] = '\000';
  1083. /* set the geometry feature type */
  1084. sf_type = with_z ? SF_POINT25D : SF_POINT;
  1085. if (byte_order == ENDIAN_LITTLE)
  1086. sf_type = LSBWORD32(sf_type);
  1087. else
  1088. sf_type = MSBWORD32(sf_type);
  1089. memcpy(wkb_data + 1, &sf_type, 4);
  1090. /* copy in the raw data */
  1091. memcpy(wkb_data + 5, &(points->x[0]), 8);
  1092. memcpy(wkb_data + 5 + 8, &(points->y[0]), 8);
  1093. if (with_z) {
  1094. memcpy(wkb_data + 5 + 16, &(points->z[0]), 8);
  1095. }
  1096. /* swap if needed */
  1097. if (byte_order == ENDIAN_BIG) {
  1098. SWAPDOUBLE(wkb_data + 5);
  1099. SWAPDOUBLE(wkb_data + 5 + 8);
  1100. if (with_z)
  1101. SWAPDOUBLE(wkb_data + 5 + 16);
  1102. }
  1103. return wkb_data;
  1104. }
  1105. /*!
  1106. \bried Write linestring into WKB buffer
  1107. See OGRLineString::exportToWkb from GDAL/OGR library
  1108. \param byte_order byte order (ENDIAN_LITTLE or ENDIAN_BIG)
  1109. \param points feature geometry
  1110. \param with_z WITH_Z for 3D data
  1111. \param[out] nsize buffer size
  1112. \return allocated WKB buffer
  1113. \return NULL on error
  1114. */
  1115. unsigned char *linestring_to_wkb(int byte_order,
  1116. const struct line_pnts *points, int with_z,
  1117. int *nsize)
  1118. {
  1119. int i, point_size;
  1120. unsigned char *wkb_data;
  1121. unsigned int sf_type;
  1122. if (points->n_points < 1)
  1123. return NULL;
  1124. /* allocate buffer */
  1125. point_size = 8 * (with_z ? 3 : 2);
  1126. *nsize = 5 + 4 + points->n_points * point_size;
  1127. wkb_data = G_malloc(*nsize);
  1128. G_zero(wkb_data, *nsize);
  1129. G_debug(5, "\t->linestring size=%d (with_z = %d)", *nsize, with_z);
  1130. /* set the byte order */
  1131. if (byte_order == ENDIAN_LITTLE)
  1132. wkb_data[0] = '\001';
  1133. else
  1134. wkb_data[0] = '\000';
  1135. /* set the geometry feature type */
  1136. sf_type = with_z ? SF_LINESTRING25D : SF_LINESTRING;
  1137. if (byte_order == ENDIAN_LITTLE)
  1138. sf_type = LSBWORD32(sf_type);
  1139. else
  1140. sf_type = MSBWORD32(sf_type);
  1141. memcpy(wkb_data + 1, &sf_type, 4);
  1142. /* copy in the data count */
  1143. memcpy(wkb_data + 5, &(points->n_points), 4);
  1144. /* copy in the raw data */
  1145. for (i = 0; i < points->n_points; i++) {
  1146. memcpy(wkb_data + 9 + point_size * i, &(points->x[i]), 8);
  1147. memcpy(wkb_data + 9 + 8 + point_size * i, &(points->y[i]), 8);
  1148. if (with_z) {
  1149. memcpy(wkb_data + 9 + 16 + point_size * i, &(points->z[i]), 8);
  1150. }
  1151. }
  1152. /* swap if needed */
  1153. if (byte_order == ENDIAN_BIG) {
  1154. int npoints, nitems;
  1155. npoints = SWAP32(points->n_points);
  1156. memcpy(wkb_data + 5, &npoints, 4);
  1157. nitems = (with_z ? 3 : 2) * points->n_points;
  1158. for (i = 0; i < nitems; i++) {
  1159. SWAPDOUBLE(wkb_data + 9 + 4 + 8 * i);
  1160. }
  1161. }
  1162. return wkb_data;
  1163. }
  1164. /*!
  1165. \bried Write polygon into WKB buffer
  1166. See OGRPolygon::exportToWkb from GDAL/OGR library
  1167. \param byte_order byte order (ENDIAN_LITTLE or ENDIAN_BIG)
  1168. \param ipoints list of ring geometries (first is outer ring)
  1169. \param nrings number of rings
  1170. \param with_z WITH_Z for 3D data
  1171. \param[out] nsize buffer size
  1172. \return allocated WKB buffer
  1173. \return NULL on error
  1174. */
  1175. unsigned char *polygon_to_wkb(int byte_order,
  1176. const struct line_pnts** points, int nrings,
  1177. int with_z, int *nsize)
  1178. {
  1179. int i, ring, point_size, offset;
  1180. unsigned char *wkb_data;
  1181. unsigned int sf_type;
  1182. /* check data validity */
  1183. if (nrings < 1)
  1184. return NULL;
  1185. for (ring = 0; ring < nrings; ring++) {
  1186. if (points[ring]->n_points < 3)
  1187. return NULL;
  1188. }
  1189. /* allocate buffer */
  1190. point_size = 8 * (with_z ? 3 : 2);
  1191. *nsize = 9;
  1192. for (ring = 0; ring < nrings; ring++)
  1193. *nsize += 4 + point_size * points[ring]->n_points;
  1194. wkb_data = G_malloc(*nsize);
  1195. G_zero(wkb_data, *nsize);
  1196. G_debug(5, "\t->polygon size=%d (with_z = %d)", *nsize, with_z);
  1197. /* set the byte order */
  1198. if (byte_order == ENDIAN_LITTLE)
  1199. wkb_data[0] = '\001';
  1200. else
  1201. wkb_data[0] = '\000';
  1202. /* set the geometry feature type */
  1203. sf_type = with_z ? SF_POLYGON25D : SF_POLYGON;
  1204. if (byte_order == ENDIAN_LITTLE)
  1205. sf_type = LSBWORD32(sf_type);
  1206. else
  1207. sf_type = MSBWORD32(sf_type);
  1208. memcpy(wkb_data + 1, &sf_type, 4);
  1209. /* copy in the raw data */
  1210. if (byte_order == ENDIAN_BIG) {
  1211. int ncount;
  1212. ncount = SWAP32(nrings);
  1213. memcpy(wkb_data + 5, &ncount, 4);
  1214. }
  1215. else {
  1216. memcpy(wkb_data + 5, &nrings, 4);
  1217. }
  1218. /* serialize rings */
  1219. offset = 9;
  1220. for (ring = 0; ring < nrings; ring++) {
  1221. memcpy(wkb_data + offset, &(points[ring]->n_points), 4);
  1222. for (i = 0; i < points[ring]->n_points; i++) {
  1223. memcpy(wkb_data + offset +
  1224. 4 + point_size * i, &(points[ring]->x[i]), 8);
  1225. memcpy(wkb_data + offset +
  1226. 4 + 8 + point_size * i, &(points[ring]->y[i]), 8);
  1227. if (with_z) {
  1228. memcpy(wkb_data + offset +
  1229. 4 + 16 + point_size * i, &(points[ring]->z[i]), 8);
  1230. }
  1231. }
  1232. offset += 4 + point_size * points[ring]->n_points;
  1233. /* swap if needed */
  1234. if (byte_order == ENDIAN_BIG) {
  1235. int npoints, nitems;
  1236. npoints = SWAP32(points[ring]->n_points);
  1237. memcpy(wkb_data + 5, &npoints, 4);
  1238. nitems = (with_z ? 3 : 2) * points[ring]->n_points;
  1239. for (i = 0; i < nitems; i++) {
  1240. SWAPDOUBLE(wkb_data + offset + 4 + 8 * i);
  1241. }
  1242. }
  1243. }
  1244. return wkb_data;
  1245. }
  1246. /*!
  1247. \brief Write feature to WKB buffer
  1248. Allocated string buffer should be freed by G_free().
  1249. \param pg_info pointer to Format_info_pg struct
  1250. \param points array of geometries which form feature
  1251. \param nparts number of geometries in array
  1252. \param type feature type (GV_POINT, GV_LINE, ...)
  1253. \param with_z WITH_Z for 3D data
  1254. \return allocated string buffer
  1255. \return NULL on error
  1256. */
  1257. char *line_to_wkb(struct Format_info_pg *pg_info,
  1258. const struct line_pnts **points, int nparts, int type, int with_z)
  1259. {
  1260. int byte_order, nbytes, nsize;
  1261. unsigned int sf_type;
  1262. unsigned char *wkb_data;
  1263. char *text_data, *text_data_p, *hex_data;
  1264. byte_order = dig__byte_order_out();
  1265. /* get wkb data */
  1266. nbytes = -1;
  1267. wkb_data = NULL;
  1268. if (type & GV_POINTS) /* point or centroid */
  1269. wkb_data = point_to_wkb(byte_order, points[0], with_z, &nbytes);
  1270. else if (type == GV_LINE)
  1271. wkb_data = linestring_to_wkb(byte_order, points[0], with_z, &nbytes);
  1272. else if (type & (GV_BOUNDARY | GV_FACE)) {
  1273. if (!pg_info->toposchema_name) {
  1274. /* PostGIS simple feature access */
  1275. wkb_data = polygon_to_wkb(byte_order, points, nparts,
  1276. with_z, &nbytes);
  1277. }
  1278. else {
  1279. /* PostGIS topology access */
  1280. wkb_data = linestring_to_wkb(byte_order, points[0], with_z, &nbytes);
  1281. }
  1282. }
  1283. if (!wkb_data || nbytes < 1) {
  1284. G_warning(_("Unsupported feature type %d"), type);
  1285. return NULL;
  1286. }
  1287. /* When converting to hex, each byte takes 2 hex characters. In
  1288. addition we add in 8 characters to represent the SRID integer
  1289. in hex, and one for a null terminator */
  1290. nsize = nbytes * 2 + 8 + 1;
  1291. text_data = text_data_p = (char *)G_malloc(nsize);
  1292. /* convert the 1st byte, which is the endianess flag, to hex */
  1293. hex_data = binary_to_hex(1, wkb_data);
  1294. strcpy(text_data_p, hex_data);
  1295. G_free(hex_data);
  1296. text_data_p += 2;
  1297. /* get the geom type which is bytes 2 through 5 */
  1298. memcpy(&sf_type, wkb_data + 1, 4);
  1299. /* add the SRID flag if an SRID is provided */
  1300. if (pg_info->srid > 0) {
  1301. unsigned int srs_flag;
  1302. /* change the flag to little endianess */
  1303. srs_flag = LSBWORD32(WKBSRIDFLAG);
  1304. /* apply the flag */
  1305. sf_type = sf_type | srs_flag;
  1306. }
  1307. /* write the geom type which is 4 bytes */
  1308. hex_data = binary_to_hex(4, (unsigned char *)&sf_type);
  1309. strcpy(text_data_p, hex_data);
  1310. G_free(hex_data);
  1311. text_data_p += 8;
  1312. /* include SRID if provided */
  1313. if (pg_info->srid > 0) {
  1314. unsigned int srs_id;
  1315. /* force the srsid to little endianess */
  1316. srs_id = LSBWORD32(pg_info->srid);
  1317. hex_data = binary_to_hex(sizeof(srs_id), (unsigned char *)&srs_id);
  1318. strcpy(text_data_p, hex_data);
  1319. G_free(hex_data);
  1320. text_data_p += 8;
  1321. }
  1322. /* copy the rest of the data over - subtract 5 since we already
  1323. copied 5 bytes above */
  1324. hex_data = binary_to_hex(nbytes - 5, wkb_data + 5);
  1325. strcpy(text_data_p, hex_data);
  1326. G_free(hex_data);
  1327. return text_data;
  1328. }
  1329. /*!
  1330. \brief Insert feature into table
  1331. \param Map pointer to Map_info structure
  1332. \param line feature id (topo access only)
  1333. \param type feature type (GV_POINT, GV_LINE, ...)
  1334. \param points pointer to line_pnts struct
  1335. \param nparts number of parts (rings for polygon)
  1336. \param cat category number (-1 for no category)
  1337. \param Fi pointer to field_info (attributes to copy, NULL for no attributes)
  1338. \return -1 on error
  1339. \retirn 0 on success
  1340. */
  1341. int write_feature(struct Map_info *Map, int line, int type,
  1342. const struct line_pnts **points, int nparts,
  1343. int cat, const struct field_info *Fi)
  1344. {
  1345. int with_z, topo_id;
  1346. char *stmt, *geom_data;
  1347. struct Format_info_pg *pg_info;
  1348. pg_info = &(Map->fInfo.pg);
  1349. with_z = Map->head.with_z;
  1350. if (with_z && pg_info->coor_dim != 3) {
  1351. G_warning(_("Trying to insert 3D data into feature table "
  1352. "which store 2D data only"));
  1353. return -1;
  1354. }
  1355. if (!with_z && pg_info->coor_dim != 2) {
  1356. G_warning(_("Trying to insert 2D data into feature table "
  1357. "which store 3D data only"));
  1358. return -1;
  1359. }
  1360. /* build WKB geometry from line_pnts structures */
  1361. geom_data = line_to_wkb(pg_info, points, nparts, type, with_z);
  1362. if (!geom_data)
  1363. return -1;
  1364. /* start transaction */
  1365. if (!pg_info->inTransaction) {
  1366. pg_info->inTransaction = TRUE;
  1367. if (Vect__execute_pg(pg_info->conn, "BEGIN") == -1) {
  1368. G_free(geom_data);
  1369. return -1;
  1370. }
  1371. }
  1372. /* write feature in PostGIS topology schema if enabled */
  1373. topo_id = -1;
  1374. if (pg_info->toposchema_name) {
  1375. /* insert feature into topology schema (node or edge) */
  1376. topo_id = insert_topo_element(Map, line, type, geom_data);
  1377. if (topo_id < 0) {
  1378. G_warning(_("Unable to insert topological element into PostGIS Topology schema"));
  1379. G_free(geom_data);
  1380. return -1;
  1381. }
  1382. }
  1383. /* build INSERT statement
  1384. simple feature geometry + attributes
  1385. */
  1386. stmt = build_insert_stmt(pg_info, geom_data, topo_id, cat, Fi);
  1387. /* stmt can NULL when writing PostGIS topology with no attributes
  1388. * attached */
  1389. if (stmt && Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1390. /* rollback transaction */
  1391. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1392. G_free(geom_data);
  1393. G_free(stmt);
  1394. return -1;
  1395. }
  1396. G_free(geom_data);
  1397. return 0;
  1398. }
  1399. /*!
  1400. \brief Build INSERT statement to add new feature to the feature
  1401. table
  1402. Note: Allocated string should be freed.
  1403. \param pg_info pointer to Format_info_pg structure
  1404. \param geom_data geometry data
  1405. \param type feature type (GV_POINT, GV_LINE, ...) - (only for PostGIS Topology)
  1406. \param id topology element id (only for PostGIS Topology)
  1407. \param cat category number (or -1 for no category)
  1408. \param Fi pointer to field_info structure (NULL for no attributes)
  1409. \return allocated string with INSERT statement
  1410. */
  1411. char *build_insert_stmt(const struct Format_info_pg *pg_info,
  1412. const char *geom_data, int topo_id,
  1413. int cat, const struct field_info *Fi)
  1414. {
  1415. int topogeom_type;
  1416. char *stmt, buf[DB_SQL_MAX];
  1417. topogeom_type = -1;
  1418. if (pg_info->toposchema_name) {
  1419. switch (pg_info->feature_type) {
  1420. case SF_POINT:
  1421. topogeom_type = 1;
  1422. break;
  1423. case SF_LINESTRING:
  1424. topogeom_type = 2;
  1425. break;
  1426. case SF_POLYGON:
  1427. topogeom_type = 3;
  1428. break;
  1429. default:
  1430. G_warning(_("Unsupported feature type %d"), pg_info->feature_type);
  1431. return NULL;
  1432. }
  1433. }
  1434. stmt = NULL;
  1435. if (Fi && cat > -1) { /* write attributes (simple features and topology elements) */
  1436. int col, ncol, more;
  1437. int sqltype, ctype, is_fid;
  1438. char buf_val[DB_SQL_MAX], buf_tmp[DB_SQL_MAX];
  1439. const char *colname;
  1440. dbString dbstmt;
  1441. dbCursor cursor;
  1442. dbTable *table;
  1443. dbColumn *column;
  1444. dbValue *value;
  1445. db_init_string(&dbstmt);
  1446. buf_val[0] = '\0';
  1447. /* read & set attributes */
  1448. sprintf(buf, "SELECT * FROM %s WHERE %s = %d", Fi->table, Fi->key,
  1449. cat);
  1450. G_debug(4, "SQL: %s", buf);
  1451. db_set_string(&dbstmt, buf);
  1452. /* prepare INSERT statement */
  1453. sprintf(buf, "INSERT INTO \"%s\".\"%s\" (",
  1454. pg_info->schema_name, pg_info->table_name);
  1455. /* select data */
  1456. if (db_open_select_cursor(pg_info->dbdriver, &dbstmt,
  1457. &cursor, DB_SEQUENTIAL) != DB_OK) {
  1458. G_warning(_("Unable to select attributes for category %d"), cat);
  1459. }
  1460. else {
  1461. if (db_fetch(&cursor, DB_NEXT, &more) != DB_OK) {
  1462. G_warning(_("Unable to fetch data from table <%s>"),
  1463. Fi->table);
  1464. }
  1465. if (!more) {
  1466. G_warning(_("No database record for category %d, "
  1467. "no attributes will be written"), cat);
  1468. }
  1469. else {
  1470. table = db_get_cursor_table(&cursor);
  1471. ncol = db_get_table_number_of_columns(table);
  1472. for (col = 0; col < ncol; col++) {
  1473. column = db_get_table_column(table, col);
  1474. colname = db_get_column_name(column);
  1475. /* -> values */
  1476. value = db_get_column_value(column);
  1477. /* for debug only */
  1478. db_convert_column_value_to_string(column, &dbstmt);
  1479. G_debug(2, "col %d : val = %s", col,
  1480. db_get_string(&dbstmt));
  1481. sqltype = db_get_column_sqltype(column);
  1482. ctype = db_sqltype_to_Ctype(sqltype);
  1483. is_fid = strcmp(pg_info->fid_column, colname) == 0;
  1484. /* check fid column (must be integer) */
  1485. if (is_fid == TRUE &&
  1486. ctype != DB_C_TYPE_INT) {
  1487. G_warning(_("FID column must be integer, column <%s> ignored!"),
  1488. colname);
  1489. continue;
  1490. }
  1491. /* -> columns */
  1492. sprintf(buf_tmp, "%s", colname);
  1493. strcat(buf, buf_tmp);
  1494. if (col < ncol - 1)
  1495. strcat(buf, ",");
  1496. /* prevent writing NULL values */
  1497. if (!db_test_value_isnull(value)) {
  1498. switch (ctype) {
  1499. case DB_C_TYPE_INT:
  1500. sprintf(buf_tmp, "%d", db_get_value_int(value));
  1501. break;
  1502. case DB_C_TYPE_DOUBLE:
  1503. sprintf(buf_tmp, "%.14f",
  1504. db_get_value_double(value));
  1505. break;
  1506. case DB_C_TYPE_STRING: {
  1507. char *value_tmp;
  1508. value_tmp = G_str_replace(db_get_value_string(value), "'", "''");
  1509. sprintf(buf_tmp, "'%s'", value_tmp);
  1510. G_free(value_tmp);
  1511. break;
  1512. }
  1513. case DB_C_TYPE_DATETIME:
  1514. db_convert_column_value_to_string(column,
  1515. &dbstmt);
  1516. sprintf(buf_tmp, "%s", db_get_string(&dbstmt));
  1517. break;
  1518. default:
  1519. G_warning(_("Unsupported column type %d"), ctype);
  1520. sprintf(buf_tmp, "NULL");
  1521. break;
  1522. }
  1523. }
  1524. else {
  1525. if (is_fid == TRUE)
  1526. G_warning(_("Invalid value for FID column: NULL"));
  1527. sprintf(buf_tmp, "NULL");
  1528. }
  1529. strcat(buf_val, buf_tmp);
  1530. if (col < ncol - 1)
  1531. strcat(buf_val, ",");
  1532. }
  1533. if (!pg_info->toposchema_name) {
  1534. /* simple feature access */
  1535. G_asprintf(&stmt, "%s,%s) VALUES (%s,'%s'::GEOMETRY)",
  1536. buf, pg_info->geom_column, buf_val, geom_data);
  1537. }
  1538. else {
  1539. /* PostGIS topology access, write geometry in
  1540. * topology schema, skip geometry at this point */
  1541. if (buf[strlen(buf)-1] == ',') { /* last column skipped */
  1542. buf[strlen(buf)-1] = '\0';
  1543. buf_val[strlen(buf_val)-1] = '\0';
  1544. }
  1545. G_asprintf(&stmt, "%s, %s) VALUES (%s, '(%d, 1, %d, %d)'::topology.TopoGeometry)",
  1546. buf, pg_info->topogeom_column, buf_val,
  1547. pg_info->toposchema_id, topo_id, topogeom_type);
  1548. }
  1549. }
  1550. }
  1551. }
  1552. else {
  1553. /* no attributes */
  1554. if (!pg_info->toposchema_name) {
  1555. /* no attributes (simple features access) */
  1556. if (cat > 0) {
  1557. /* cetegory defined */
  1558. G_asprintf(&stmt, "INSERT INTO \"%s\".\"%s\" (%s,%s) VALUES "
  1559. "(%d, '%s'::GEOMETRY)",
  1560. pg_info->schema_name, pg_info->table_name,
  1561. GV_KEY_COLUMN, pg_info->geom_column,
  1562. cat, geom_data);
  1563. }
  1564. else {
  1565. /* no category */
  1566. G_asprintf(&stmt, "INSERT INTO \"%s\".\"%s\" (%s) VALUES "
  1567. "('%s'::GEOMETRY)",
  1568. pg_info->schema_name, pg_info->table_name,
  1569. pg_info->geom_column, geom_data);
  1570. }
  1571. }
  1572. else {
  1573. if (cat > 0) {
  1574. /* no attributes (topology elements) */
  1575. G_asprintf(&stmt, "INSERT INTO \"%s\".\"%s\" (%s,%s) VALUES "
  1576. "(%d, '(%d, 1, %d, %d)'::topology.TopoGeometry)",
  1577. pg_info->schema_name, pg_info->table_name,
  1578. GV_KEY_COLUMN, pg_info->topogeom_column, cat,
  1579. pg_info->toposchema_id, topo_id, topogeom_type);
  1580. }
  1581. }
  1582. }
  1583. return stmt;
  1584. }
  1585. /*!
  1586. \brief Insert topological element into 'node' or 'edge' table
  1587. Negative id for nodes, 0 for next value.
  1588. \param Map pointer to Map_info struct
  1589. \param id feature id (0 for next val)
  1590. \param type feature type (GV_POINT, GV_LINE, ...)
  1591. \param geom_data geometry in wkb
  1592. \return new topo id
  1593. \return -1 on error
  1594. */
  1595. int insert_topo_element(struct Map_info *Map, int id, int type,
  1596. const char *geom_data)
  1597. {
  1598. int ret, topo_id;
  1599. char *stmt, stmt_id[DB_SQL_MAX];
  1600. struct Format_info_pg *pg_info;
  1601. struct Plus_head *plus;
  1602. struct P_line *Line;
  1603. pg_info = &(Map->fInfo.pg);
  1604. plus = &(Map->plus);
  1605. Line = NULL;
  1606. if (plus->built >= GV_BUILD_BASE) {
  1607. if (id > 0) { /* -> feature */
  1608. topo_id = id;
  1609. if (topo_id > Map->plus.n_lines) {
  1610. G_warning(_("Invalid feature %d (max: %d)"), topo_id, Map->plus.n_lines);
  1611. return -1;
  1612. }
  1613. Line = Map->plus.Line[topo_id];
  1614. }
  1615. else if (id < 0) { /* node */
  1616. topo_id = abs(id);
  1617. if (type != GV_POINT) {
  1618. G_warning(_("Invalid feature type (%d) for node"), type);
  1619. return -1;
  1620. }
  1621. if (topo_id > Map->plus.n_nodes) {
  1622. G_warning(_("Invalid node %d (%d)"), topo_id, Map->plus.n_nodes);
  1623. return -1;
  1624. }
  1625. }
  1626. }
  1627. stmt = NULL;
  1628. switch(type) {
  1629. case GV_POINT: {
  1630. /* insert new node */
  1631. #if USE_TOPO_STMT
  1632. G_asprintf(&stmt, "SELECT topology.AddNode('%s', '%s'::GEOMETRY)",
  1633. pg_info->toposchema_name, geom_data);
  1634. #else
  1635. if (id == 0) {
  1636. /* get node_id */
  1637. sprintf(stmt_id, "SELECT nextval('\"%s\".node_node_id_seq')",
  1638. pg_info->toposchema_name);
  1639. topo_id = Vect__execute_get_value_pg(pg_info->conn, stmt_id);
  1640. }
  1641. /* build insert statement */
  1642. G_asprintf(&stmt, "INSERT INTO \"%s\".node (node_id, geom) VALUES "
  1643. "(%d, '%s'::GEOMETRY)", pg_info->toposchema_name, topo_id, geom_data);
  1644. #endif
  1645. break;
  1646. }
  1647. case GV_LINE:
  1648. case GV_BOUNDARY: {
  1649. /* insert new edge */
  1650. #if USE_TOPO_STMT
  1651. G_asprintf(&stmt, "SELECT topology.AddEdge('%s', '%s'::GEOMETRY)",
  1652. pg_info->toposchema_name, geom_data);
  1653. #else
  1654. int n1, n2, nle, nre;
  1655. if (id == 0) {
  1656. /* get edge_id */
  1657. sprintf(stmt_id, "SELECT nextval('\"%s\".edge_data_edge_id_seq')",
  1658. pg_info->toposchema_name);
  1659. topo_id = Vect__execute_get_value_pg(pg_info->conn, stmt_id);
  1660. }
  1661. nle = -topo_id; /* assuming isolated lines */
  1662. nre = topo_id;
  1663. if (Line) {
  1664. int i, n, next_edge;
  1665. struct P_topo_l *topo = (struct P_topo_l *) Line->topo;
  1666. topo_id = (int)Line->offset;
  1667. /* start & end node */
  1668. n1 = topo->N1;
  1669. n2 = topo->N2;
  1670. /* next left & right edge */
  1671. for (i = 0; i < 2; i++) {
  1672. n = Vect_get_node_n_lines(Map, i == 0 ? n1 : n2);
  1673. if (n < 2) /* no connection */
  1674. continue;
  1675. next_edge = update_next_edge(Map, n,
  1676. i == 0 ? topo_id : -topo_id);
  1677. if (next_edge != 0) {
  1678. if (i == 0)
  1679. nre = next_edge; /* update next right edge for start node */
  1680. else
  1681. nle = next_edge; /* update next left edge for end node */
  1682. }
  1683. else {
  1684. G_warning(_("Unable to determine next left/right edge for edge %d"), topo_id);
  1685. }
  1686. }
  1687. }
  1688. else {
  1689. G_warning(_("Unable to insert new edge. Topology not available."));
  1690. return -1;
  1691. }
  1692. G_debug(3, "new edge: id=%d next_left_edge=%d next_right_edge=%d",
  1693. topo_id, nle, nre);
  1694. /* build insert statement */
  1695. G_asprintf(&stmt, "INSERT INTO \"%s\".edge_data (edge_id, start_node, end_node, "
  1696. "next_left_edge, abs_next_left_edge, next_right_edge, abs_next_right_edge, "
  1697. "left_face, right_face, geom) VALUES "
  1698. "(%d, %d, %d, %d, %d, %d, %d, 0, 0, '%s'::GEOMETRY)",
  1699. pg_info->toposchema_name, topo_id, n1, n2,
  1700. nle, abs(nle), nre, abs(nre), geom_data);
  1701. #endif
  1702. break;
  1703. }
  1704. case GV_CENTROID: {
  1705. /* insert new node (with containing_face) */
  1706. #if USE_TOPO_STMT
  1707. G_asprintf(&stmt, "SELECT topology.AddNode('%s', '%s'::GEOMETRY)",
  1708. pg_info->toposchema_name, geom_data);
  1709. #else
  1710. int area;
  1711. if (id == 0) {
  1712. /* get node_id */
  1713. sprintf(stmt_id, "SELECT nextval('\"%s\".node_node_id_seq')",
  1714. pg_info->toposchema_name);
  1715. topo_id = Vect__execute_get_value_pg(pg_info->conn, stmt_id);
  1716. }
  1717. if (Line) {
  1718. struct P_topo_c *topo = (struct P_topo_c *) Line->topo;
  1719. area = topo->area;
  1720. }
  1721. else {
  1722. area = 0;
  1723. }
  1724. G_asprintf(&stmt, "INSERT INTO \"%s\".node (node_id, containing_face, geom) VALUES "
  1725. "(%d, %d, '%s'::GEOMETRY)", pg_info->toposchema_name,
  1726. topo_id, area, geom_data);
  1727. #endif
  1728. break;
  1729. }
  1730. default:
  1731. G_warning(_("Unsupported feature type %d"), type);
  1732. break;
  1733. }
  1734. /* execute insert statement */
  1735. ret = Vect__execute_pg(pg_info->conn, stmt);
  1736. G_free(stmt);
  1737. if (ret == -1) {
  1738. /* rollback transaction */
  1739. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1740. return -1;
  1741. }
  1742. return topo_id;
  1743. }
  1744. /*!
  1745. \brief Find next line (topo only)
  1746. \param Map pointer to Map_info struct
  1747. \param nlines number of lines
  1748. \param line current line
  1749. \param[out] left left line
  1750. \param[out] right right line
  1751. \return left (line < 0) or right (line > 0) next edge
  1752. \return 0 on failure
  1753. */
  1754. int update_next_edge(struct Map_info* Map, int nlines, int line)
  1755. {
  1756. int ret, next_line, edge;
  1757. char stmt[DB_SQL_MAX];
  1758. const struct Format_info_pg *pg_info;
  1759. struct P_line *Line_next, *Line;
  1760. Line = Line_next = NULL;
  1761. pg_info = &(Map->fInfo.pg);
  1762. /* find next line
  1763. start node -> next on the left
  1764. end node -> next on the right
  1765. */
  1766. next_line = dig_angle_next_line(&(Map->plus), line, GV_LEFT, GV_LINES, NULL);
  1767. G_debug(3, "line=%d next_line=%d", line, next_line);
  1768. if (next_line == 0) {
  1769. G_warning(_("Invalid topology"));
  1770. return 0;
  1771. }
  1772. Line = Map->plus.Line[abs(line)];
  1773. Line_next = Map->plus.Line[abs(next_line)];
  1774. if (!Line || !Line_next) {
  1775. G_warning(_("Invalid topology"));
  1776. return 0;
  1777. }
  1778. if (line > 0) {
  1779. edge = Line->offset;
  1780. ret = next_line > 0 ? Line_next->offset : -Line_next->offset;
  1781. }
  1782. else {
  1783. edge = -Line->offset;
  1784. ret = next_line > 0 ? Line_next->offset : -Line_next->offset;
  1785. }
  1786. if (next_line < 0) {
  1787. sprintf(stmt, "UPDATE \"%s\".edge_data SET next_left_edge = %d, "
  1788. "abs_next_left_edge = %d WHERE edge_id = %d AND abs_next_left_edge = %d",
  1789. pg_info->toposchema_name, edge, abs(edge), (int)Line_next->offset, (int)Line_next->offset);
  1790. G_debug(3, "update edge=%d next_left_edge=%d (?)", (int)Line_next->offset, edge);
  1791. }
  1792. else {
  1793. sprintf(stmt, "UPDATE \"%s\".edge_data SET next_right_edge = %d, "
  1794. "abs_next_right_edge = %d WHERE edge_id = %d AND abs_next_right_edge = %d",
  1795. pg_info->toposchema_name, edge, abs(edge), (int)Line_next->offset, (int)Line_next->offset);
  1796. G_debug(3, "update edge=%d next_right_edge=%d (?)", (int)Line_next->offset, edge);
  1797. }
  1798. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1799. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1800. return 0;
  1801. }
  1802. if (nlines > 2) {
  1803. /* more lines connected to the node
  1804. start node -> next on the right
  1805. end node -> next on the left
  1806. */
  1807. next_line = dig_angle_next_line(&(Map->plus), line, GV_RIGHT, GV_LINES, NULL);
  1808. Line_next = Map->plus.Line[abs(next_line)];
  1809. if (next_line < 0) {
  1810. sprintf(stmt, "UPDATE \"%s\".edge_data SET next_left_edge = %d, "
  1811. "abs_next_left_edge = %d WHERE edge_id = %d",
  1812. pg_info->toposchema_name, edge, abs(edge), (int)Line_next->offset);
  1813. G_debug(3, "update edge=%d next_left_edge=%d", (int)Line_next->offset, edge);
  1814. }
  1815. else {
  1816. sprintf(stmt, "UPDATE \"%s\".edge_data SET next_right_edge = %d, "
  1817. "abs_next_right_edge = %d WHERE edge_id = %d",
  1818. pg_info->toposchema_name, edge, abs(edge), (int)Line_next->offset);
  1819. G_debug(3, "update edge=%d next_right_edge=%d", (int)Line_next->offset, edge);
  1820. }
  1821. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1822. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1823. return 0;
  1824. }
  1825. }
  1826. return ret;
  1827. }
  1828. /*!
  1829. \brief Insert new face to the 'face' table (topo only)
  1830. \param Map pointer to Map_info struct
  1831. \param area area id (negative id for isles)
  1832. \return 0 on error
  1833. \return area id on success (>0)
  1834. */
  1835. int Vect__insert_face_pg(struct Map_info *Map, int area)
  1836. {
  1837. char *stmt;
  1838. struct Format_info_pg *pg_info;
  1839. struct bound_box box;
  1840. if (area == 0)
  1841. return 0; /* universal face has id '0' in PostGIS Topology */
  1842. stmt = NULL;
  1843. pg_info = &(Map->fInfo.pg);
  1844. /* check if face exists */
  1845. /* get mbr of the area */
  1846. if (area > 0)
  1847. Vect_get_area_box(Map, area, &box);
  1848. else
  1849. Vect_get_isle_box(Map, abs(area), &box);
  1850. /* insert face if not exists */
  1851. G_asprintf(&stmt, "INSERT INTO \"%s\".face (face_id, mbr) VALUES "
  1852. "(%d, ST_GeomFromText('POLYGON((%.12f %.12f, %.12f %.12f, %.12f %.12f, %.12f %.12f, "
  1853. "%.12f %.12f))', %d))", pg_info->toposchema_name, area,
  1854. box.W, box.S, box.W, box.N, box.E, box.N,
  1855. box.E, box.S, box.W, box.S, pg_info->srid);
  1856. G_debug(3, "new face id=%d", area);
  1857. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1858. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1859. return 0;
  1860. }
  1861. G_free(stmt);
  1862. return area;
  1863. }
  1864. /*!
  1865. \brief Delete existing face (currently unused)
  1866. \todo Set foreign keys as DEFERRABLE INITIALLY DEFERRED and use SET
  1867. CONSTRAINTS ALL DEFERRED
  1868. \param Map pointer to Map_info struct
  1869. \param area area id to delete
  1870. \return 0 on success
  1871. \return -1 on error
  1872. */
  1873. int delete_face(const struct Map_info *Map, int area)
  1874. {
  1875. char stmt[DB_SQL_MAX];
  1876. const struct Format_info_pg *pg_info;
  1877. pg_info = &(Map->fInfo.pg);
  1878. /* update centroids first */
  1879. sprintf(stmt, "UPDATE \"%s\".node SET containing_face = 0 "
  1880. "WHERE containing_face = %d",
  1881. pg_info->toposchema_name, area);
  1882. G_debug(3, "SQL: %s", stmt);
  1883. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1884. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1885. return -1;
  1886. }
  1887. /* update also edges (left face) */
  1888. sprintf(stmt, "UPDATE \"%s\".edge_data SET left_face = 0 "
  1889. "WHERE left_face = %d",
  1890. pg_info->toposchema_name, area);
  1891. G_debug(3, "SQL: %s", stmt);
  1892. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1893. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1894. return -1;
  1895. }
  1896. /* update also edges (left face) */
  1897. sprintf(stmt, "UPDATE \"%s\".edge_data SET right_face = 0 "
  1898. "WHERE right_face = %d",
  1899. pg_info->toposchema_name, area);
  1900. G_debug(3, "SQL: %s", stmt);
  1901. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1902. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1903. return -1;
  1904. }
  1905. /* delete face */
  1906. sprintf(stmt, "DELETE FROM \"%s\".face WHERE face_id = %d",
  1907. pg_info->toposchema_name, area);
  1908. G_debug(3, "delete face id=%d", area);
  1909. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1910. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1911. return -1;
  1912. }
  1913. return 0;
  1914. }
  1915. /*!
  1916. \brief Update lines (next left and right edges)
  1917. - isolated edges
  1918. next left edge: -edge
  1919. next right edge: edge
  1920. - connected edges
  1921. next left edge: next edge or -edge
  1922. next right edge: next edge or edge
  1923. \param Map pointer to Map_info struct
  1924. \param line feature id
  1925. \return 0 on success
  1926. \return -1 on error
  1927. */
  1928. int update_topo_edge(struct Map_info *Map, int line)
  1929. {
  1930. int i, n;
  1931. int nle, nre, next_edge;
  1932. char stmt[DB_SQL_MAX];
  1933. struct Format_info_pg *pg_info;
  1934. struct P_line *Line;
  1935. pg_info = &(Map->fInfo.pg);
  1936. if (line < 1 || line > Map->plus.n_lines) {
  1937. G_warning(_("Attempt to access non-existing feature %d"), line);
  1938. return -1;
  1939. }
  1940. Line = Map->plus.Line[line];
  1941. if (!Line) {
  1942. G_warning(_("Attempt to access dead feature %d"), line);
  1943. return -1;
  1944. }
  1945. struct P_topo_l *topo = (struct P_topo_l *) Line->topo;
  1946. nre = nle = 0; /* edge = 0 is an illegal value */
  1947. /* check for line connection */
  1948. for (i = 0; i < 2; i++) {
  1949. /* first check start node then end node */
  1950. n = i == 0 ? Vect_get_node_n_lines(Map, topo->N1)
  1951. : Vect_get_node_n_lines(Map, topo->N2);
  1952. if (n < 2) /* no connection */
  1953. continue;
  1954. next_edge = update_next_edge(Map, n,
  1955. i == 0 ? line : -line);
  1956. if (next_edge != 0) {
  1957. if (i == 0)
  1958. nre = next_edge; /* update next right edge for start node */
  1959. else
  1960. nle = next_edge; /* update next left edge for end node */
  1961. }
  1962. else {
  1963. G_warning(_("Unable to determine next left/right edge"));
  1964. return -1;
  1965. }
  1966. }
  1967. if (nle == 0 && nre == 0) /* nothing changed */
  1968. return 0;
  1969. if (nle != 0 && nre != 0) {
  1970. /* update both next left and right edge */
  1971. sprintf(stmt, "UPDATE \"%s\".edge_data SET "
  1972. "next_left_edge = %d, abs_next_left_edge = %d, "
  1973. "next_right_edge = %d, abs_next_right_edge = %d "
  1974. "WHERE edge_id = %d", pg_info->toposchema_name,
  1975. nle, abs(nle), nre, abs(nre), (int)Line->offset);
  1976. }
  1977. else if (nle != 0) {
  1978. /* update next left edge only */
  1979. sprintf(stmt, "UPDATE \"%s\".edge_data SET "
  1980. "next_left_edge = %d, abs_next_left_edge = %d "
  1981. "WHERE edge_id = %d", pg_info->toposchema_name,
  1982. nle, abs(nle), (int)Line->offset);
  1983. }
  1984. else {
  1985. /* update next right edge only */
  1986. sprintf(stmt, "UPDATE \"%s\".edge_data SET "
  1987. "next_right_edge = %d, abs_next_right_edge = %d "
  1988. "WHERE edge_id = %d", pg_info->toposchema_name,
  1989. nre, abs(nre), (int)Line->offset);
  1990. }
  1991. G_debug(3, "update edge=%d next_left_edge=%d next_right_edge=%d",
  1992. (int)Line->offset, nle, nre);
  1993. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1994. /* rollback transaction */
  1995. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1996. return -1;
  1997. }
  1998. return 0;
  1999. }
  2000. /*!
  2001. \brief Update lines (left and right faces)
  2002. TODO: handle isles
  2003. \param Map pointer to Map_info struct
  2004. \param line feature id
  2005. \return 0 on success
  2006. \return -1 on error
  2007. */
  2008. int update_topo_face(struct Map_info *Map, int line)
  2009. {
  2010. int i, s, area, face[2];
  2011. char stmt[DB_SQL_MAX];
  2012. struct Format_info_pg *pg_info;
  2013. struct P_line *Line, *Line_i;
  2014. struct P_area *Area;
  2015. struct P_topo_b *topo, *topo_i;
  2016. pg_info = &(Map->fInfo.pg);
  2017. if (line < 1 || line > Map->plus.n_lines) {
  2018. G_warning(_("Attempt to access non-existing feature %d"), line);
  2019. return -1;
  2020. }
  2021. Line = Map->plus.Line[line];
  2022. if (!Line) {
  2023. G_warning(_("Attempt to access dead feature %d"), line);
  2024. return -1;
  2025. }
  2026. topo = (struct P_topo_b *)Line->topo;
  2027. /* for both side on the current boundary (line) */
  2028. /* create new faces */
  2029. for (s = 0; s < 2; s++) { /* for each side */
  2030. area = s == 0 ? topo->left : topo->right;
  2031. if (area <= 0) /* no area - skip */
  2032. continue;
  2033. face[s] = Vect__insert_face_pg(Map, area);
  2034. if (face[s] < 1) {
  2035. G_warning(_("Unable to create new face"));
  2036. return -1;
  2037. }
  2038. }
  2039. /* update edges forming faces */
  2040. for (s = 0; s < 2; s++) { /* for each side */
  2041. area = s == 0 ? topo->left : topo->right;
  2042. if (area <= 0) /* no area - skip */
  2043. continue;
  2044. Area = Map->plus.Area[area];
  2045. for (i = 0; i < Area->n_lines; i++) {
  2046. Line_i = Map->plus.Line[abs(Area->lines[i])];
  2047. topo_i = (struct P_topo_b *)Line_i->topo;
  2048. sprintf(stmt, "UPDATE \"%s\".edge_data SET "
  2049. "left_face = %d, right_face = %d "
  2050. "WHERE edge_id = %d", pg_info->toposchema_name,
  2051. topo_i->left > 0 ? topo_i->left : 0,
  2052. topo_i->right > 0 ? topo_i->right : 0,
  2053. (int) Line_i->offset);
  2054. G_debug(2, "SQL: %s", stmt);
  2055. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  2056. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  2057. return -1;
  2058. }
  2059. }
  2060. /* update also centroids (stored as nodes) */
  2061. if (Area->centroid > 0) {
  2062. Line_i = Map->plus.Line[Area->centroid];
  2063. sprintf(stmt, "UPDATE \"%s\".node SET containing_face = %d "
  2064. "WHERE node_id = %d", pg_info->toposchema_name,
  2065. face[s], (int)Line_i->offset);
  2066. G_debug(2, "SQL: %s", stmt);
  2067. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  2068. /* rollback transaction */
  2069. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  2070. return -1;
  2071. }
  2072. }
  2073. }
  2074. return 0;
  2075. }
  2076. /*!
  2077. \brief Add line to native and PostGIS topology
  2078. \param Map vector map
  2079. \param line feature id to remove from topo
  2080. \param type feature type
  2081. \param Points feature vertices
  2082. \return feature id
  2083. \return -1 on error
  2084. */
  2085. int add_line_to_topo_pg(struct Map_info *Map, off_t offset, int type,
  2086. const struct line_pnts *points)
  2087. {
  2088. int line, n_nodes;
  2089. struct Plus_head *plus;
  2090. plus = &(Map->plus);
  2091. Vect_reset_updated(Map);
  2092. line = V2__add_line_to_topo_nat(Map, offset, type, points, NULL,
  2093. -1, NULL);
  2094. /* insert new nodes into 'node' table */
  2095. n_nodes = Vect_get_num_updated_nodes(Map);
  2096. if (n_nodes > 0) {
  2097. int i, node;
  2098. double x, y, z;
  2099. if (!Points)
  2100. Points = Vect_new_line_struct();
  2101. for (i = 0; i < n_nodes; i++) {
  2102. node = Vect_get_updated_node(Map, i);
  2103. /* skip updated and deleted nodes */
  2104. if (node > 0 || plus->Node[abs(node)] == NULL)
  2105. continue;
  2106. G_debug(3, " new node: %d", node);
  2107. Vect_get_node_coor(Map, abs(node), &x, &y, &z);
  2108. Vect_reset_line(Points);
  2109. Vect_append_point(Points, x, y, z);
  2110. write_feature(Map, node, GV_POINT, (const struct line_pnts **) &Points, 1,
  2111. -1, NULL);
  2112. }
  2113. }
  2114. return line;
  2115. }
  2116. /*!
  2117. \brief Delete line from native and PostGIS topology
  2118. \todo Implement deleting nodes on request
  2119. \param Map vector map
  2120. \param line feature id to remove from topo
  2121. \param type feature type
  2122. \param Points feature vertices
  2123. \return 0 on success
  2124. \return -1 on error
  2125. */
  2126. int delete_line_from_topo_pg(struct Map_info *Map, int line, int type,
  2127. const struct line_pnts *Points)
  2128. {
  2129. Vect_reset_updated(Map);
  2130. if (0 != V2__delete_line_from_topo_nat(Map, line, type, Points, NULL))
  2131. return -1;
  2132. /* disabled: remove isolated nodes when closing the map
  2133. note: node id cannot be used as node_id
  2134. delete nodes from 'node' table
  2135. int n_nodes;
  2136. char stmt[DB_SQL_MAX];
  2137. struct Format_info_pg *pg_info;
  2138. struct Plus_head *plus;
  2139. pg_info = &(Map->fInfo.pg);
  2140. plus = &(Map->plus);
  2141. n_nodes = Vect_get_num_updated_nodes(Map);
  2142. if (n_nodes > 0) {
  2143. int i, node;
  2144. for (i = 0; i < n_nodes; i++) {
  2145. node = Vect_get_updated_node(Map, i);
  2146. if (node > 0 || plus->Node[abs(node)] != NULL)
  2147. continue;
  2148. node = abs(node);
  2149. G_debug(3, "delete node %d from 'node' table", node);
  2150. sprintf(stmt, "DELETE FROM \"%s\".\"node\" WHERE node_id = %d",
  2151. pg_info->toposchema_name, node);
  2152. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  2153. G_warning(_("Unable to delete node %d"), node);
  2154. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  2155. return -1;
  2156. }
  2157. }
  2158. }
  2159. */
  2160. return 0;
  2161. }
  2162. #endif