write_pg.c 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616
  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. default:
  527. G_warning(_("Unsupported feature type %d"), pg_info->feature_type);
  528. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  529. return -1;
  530. }
  531. /* add geometry column */
  532. sprintf(stmt, "SELECT AddGeometryColumn('%s', '%s', "
  533. "'%s', %d, '%s', %d)",
  534. pg_info->schema_name, pg_info->table_name,
  535. pg_info->geom_column, pg_info->srid,
  536. geom_type, pg_info->coor_dim);
  537. G_debug(2, "SQL: %s", stmt);
  538. result = PQexec(pg_info->conn, stmt);
  539. if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
  540. G_warning("%s", PQresultErrorMessage(result));
  541. PQclear(result);
  542. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  543. return -1;
  544. }
  545. /* create indeces
  546. - GV_KEY_COLUMN
  547. - geometry column
  548. */
  549. sprintf(stmt,
  550. "CREATE INDEX %s_%s_idx ON \"%s\".\"%s\" (%s)",
  551. pg_info->table_name, GV_KEY_COLUMN,
  552. pg_info->schema_name, pg_info->table_name,
  553. GV_KEY_COLUMN);
  554. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  555. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  556. return -1;
  557. }
  558. if (spatial_index) {
  559. G_verbose_message(_("Building spatial index on <%s>..."),
  560. pg_info->geom_column);
  561. sprintf(stmt,
  562. "CREATE INDEX %s_%s_idx ON \"%s\".\"%s\" USING GIST (%s)",
  563. pg_info->table_name, pg_info->geom_column,
  564. pg_info->schema_name, pg_info->table_name,
  565. pg_info->geom_column);
  566. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  567. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  568. return -1;
  569. }
  570. }
  571. /* close transaction (create table) */
  572. if (Vect__execute_pg(pg_info->conn, "COMMIT") == -1) {
  573. return -1;
  574. }
  575. return 0;
  576. }
  577. /*!
  578. \brief Creates new schema for feature table if not exists
  579. \param pg_info pointer to Format_info_pg
  580. \return -1 on error
  581. \return 0 on success
  582. */
  583. int check_schema(const struct Format_info_pg *pg_info)
  584. {
  585. int i, found, nschema;
  586. char stmt[DB_SQL_MAX];
  587. PGresult *result;
  588. /* add geometry column */
  589. sprintf(stmt, "SELECT nspname FROM pg_namespace");
  590. G_debug(2, "SQL: %s", stmt);
  591. result = PQexec(pg_info->conn, stmt);
  592. if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
  593. PQclear(result);
  594. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  595. return -1;
  596. }
  597. found = FALSE;
  598. nschema = PQntuples(result);
  599. for (i = 0; i < nschema && !found; i++) {
  600. if (strcmp(pg_info->schema_name, PQgetvalue(result, i, 0)) == 0)
  601. found = TRUE;
  602. }
  603. PQclear(result);
  604. if (!found) {
  605. sprintf(stmt, "CREATE SCHEMA %s", pg_info->schema_name);
  606. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  607. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  608. return -1;
  609. }
  610. G_warning(_("Schema <%s> doesn't exist, created"),
  611. pg_info->schema_name);
  612. }
  613. return 0;
  614. }
  615. /*!
  616. \brief Create new PostGIS topology schema
  617. - create topology schema
  618. - add topology column to the feature table
  619. \param pg_info pointer to Format_info_pg
  620. \return 0 on success
  621. \return 1 topology disable, nothing to do
  622. \return -1 on failure
  623. */
  624. int create_topo_schema(struct Format_info_pg *pg_info, int with_z)
  625. {
  626. double tolerance;
  627. char stmt[DB_SQL_MAX];
  628. char *def_file;
  629. PGresult *result;
  630. def_file = getenv("GRASS_VECTOR_PGFILE");
  631. /* read default values from PG file*/
  632. tolerance = 0.;
  633. if (G_find_file2("", def_file ? def_file : "PG", G_mapset())) {
  634. FILE *fp;
  635. const char *p;
  636. struct Key_Value *key_val;
  637. fp = G_fopen_old("", def_file ? def_file : "PG", G_mapset());
  638. if (!fp) {
  639. G_fatal_error(_("Unable to open PG file"));
  640. }
  641. key_val = G_fread_key_value(fp);
  642. fclose(fp);
  643. /* tolerance */
  644. p = G_find_key_value("tolerance", key_val);
  645. if (p)
  646. tolerance = atof(p);
  647. /* topogeom column */
  648. p = G_find_key_value("topogeom_column", key_val);
  649. if (p)
  650. pg_info->topogeom_column = G_store(p);
  651. else
  652. pg_info->topogeom_column = G_store(TOPOGEOM_COLUMN);
  653. }
  654. /* begin transaction (create topo schema) */
  655. if (Vect__execute_pg(pg_info->conn, "BEGIN") == -1) {
  656. return -1;
  657. }
  658. /* create topology schema */
  659. G_verbose_message(_("Creating topology schema <%s>..."),
  660. pg_info->toposchema_name);
  661. sprintf(stmt, "SELECT topology.createtopology('%s', "
  662. "find_srid('%s', '%s', '%s'), %f, '%s')",
  663. pg_info->toposchema_name, pg_info->schema_name,
  664. pg_info->table_name, pg_info->geom_column, tolerance,
  665. with_z == WITH_Z ? "t" : "f");
  666. G_debug(2, "SQL: %s", stmt);
  667. result = PQexec(pg_info->conn, stmt);
  668. if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
  669. G_warning(_("Execution failed: %s"), PQerrorMessage(pg_info->conn));
  670. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  671. return -1;
  672. }
  673. /* store toposchema id */
  674. pg_info->toposchema_id = atoi(PQgetvalue(result, 0, 0));
  675. /* add topo column to the feature table */
  676. G_verbose_message(_("Adding new topology column <%s>..."),
  677. pg_info->topogeom_column);
  678. sprintf(stmt, "SELECT topology.AddTopoGeometryColumn('%s', '%s', '%s', "
  679. "'%s', '%s')", pg_info->toposchema_name, pg_info->schema_name,
  680. pg_info->table_name, pg_info->topogeom_column,
  681. get_sftype(pg_info->feature_type));
  682. G_debug(2, "SQL: %s", stmt);
  683. result = PQexec(pg_info->conn, stmt);
  684. if (!result || PQresultStatus(result) != PGRES_TUPLES_OK) {
  685. G_warning(_("Execution failed: %s"), PQerrorMessage(pg_info->conn));
  686. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  687. return -1;
  688. }
  689. /* close transaction (create topo schema) */
  690. if (Vect__execute_pg(pg_info->conn, "COMMIT") == -1) {
  691. return -1;
  692. }
  693. return 0;
  694. }
  695. /*!
  696. \brief Create new PostGIS layer in given database (internal use only)
  697. V1_open_new_pg() must be called before this function.
  698. List of currently supported types:
  699. - GV_POINT (SF_POINT)
  700. - GV_LINE (SF_LINESTRING)
  701. - GV_BOUNDARY (SF_POLYGON)
  702. When PostGIS Topology the map level is updated to topological level
  703. and build level set to GV_BUILD_BASE.
  704. \param[in,out] Map pointer to Map_info structure
  705. \param type feature type (GV_POINT, GV_LINE, ...)
  706. \return 0 success
  707. \return -1 error
  708. */
  709. int create_pg_layer(struct Map_info *Map, int type)
  710. {
  711. int ndblinks;
  712. struct Format_info_pg *pg_info;
  713. struct field_info *Fi;
  714. Fi = NULL;
  715. pg_info = &(Map->fInfo.pg);
  716. if (!pg_info->conninfo) {
  717. G_warning(_("Connection string not defined"));
  718. return -1;
  719. }
  720. if (!pg_info->table_name) {
  721. G_warning(_("PostGIS feature table not defined"));
  722. return -1;
  723. }
  724. G_debug(1, "Vect__open_new_pg(): conninfo='%s' table='%s' -> type = %d",
  725. pg_info->conninfo, pg_info->table_name, type);
  726. /* determine geometry type */
  727. switch (type) {
  728. case GV_POINT:
  729. pg_info->feature_type = SF_POINT;
  730. break;
  731. case GV_LINE:
  732. pg_info->feature_type = SF_LINESTRING;
  733. break;
  734. case GV_BOUNDARY:
  735. pg_info->feature_type = SF_POLYGON;
  736. break;
  737. default:
  738. G_warning(_("Unsupported geometry type (%d)"), type);
  739. return -1;
  740. }
  741. /* coordinate dimension */
  742. pg_info->coor_dim = Vect_is_3d(Map) ? 3 : 2;
  743. /* create new PostGIS table */
  744. ndblinks = Vect_get_num_dblinks(Map);
  745. if (ndblinks > 0) {
  746. Fi = Vect_get_dblink(Map, 0);
  747. if (Fi) {
  748. if (ndblinks > 1)
  749. G_warning(_("More layers defined, using driver <%s> and "
  750. "database <%s>"), Fi->driver, Fi->database);
  751. }
  752. else {
  753. G_warning(_("Database connection not defined. "
  754. "Unable to write attributes."));
  755. }
  756. }
  757. /* create new feature table */
  758. if (create_table(pg_info, Fi) == -1) {
  759. G_warning(_("Unable to create new PostGIS feature table"));
  760. return -1;
  761. }
  762. /* create new topology schema (if PostGIS topology support is enabled) */
  763. if (pg_info->toposchema_name) {
  764. /* force topological level */
  765. Map->level = LEVEL_2;
  766. Map->plus.built = GV_BUILD_BASE;
  767. /* track updated features, used in V2__add_line_to_topo_nat() */
  768. Vect_set_updated(Map, TRUE);
  769. if (create_topo_schema(pg_info, Vect_is_3d(Map)) == -1) {
  770. G_warning(_("Unable to create new PostGIS topology schema"));
  771. return -1;
  772. }
  773. }
  774. if (Fi)
  775. G_free(Fi);
  776. return 0;
  777. }
  778. /*!
  779. \brief Get simple feature type as a string
  780. Used for AddTopoGeometryColumn().
  781. Valid types:
  782. - SF_POINT
  783. - SF_LINESTRING
  784. - SF_POLYGON
  785. \return string with feature type
  786. \return empty string
  787. */
  788. char *get_sftype(SF_FeatureType sftype)
  789. {
  790. if (sftype == SF_POINT)
  791. return "POINT";
  792. else if (sftype == SF_LINESTRING)
  793. return "LINE";
  794. else if (sftype == SF_POLYGON)
  795. return "POLYGON";
  796. else
  797. G_warning(_("Unsupported feature type %d"), sftype);
  798. return "";
  799. }
  800. /*!
  801. \brief Write vector features as PostGIS simple feature element
  802. \param Map pointer to Map_info structure
  803. \param type feature type (GV_POINT, GV_LINE, ...)
  804. \param points feature geometry (exterior + interior rings for polygonsx)
  805. \param nparts number of parts
  806. \param cats feature categories
  807. \return feature offset
  808. \return -1 on error
  809. */
  810. off_t write_line_sf(struct Map_info *Map, int type,
  811. const struct line_pnts **points, int nparts,
  812. const struct line_cats *cats)
  813. {
  814. int cat;
  815. off_t offset;
  816. SF_FeatureType sf_type;
  817. struct field_info *Fi;
  818. struct Format_info_pg *pg_info;
  819. struct Format_info_offset *offset_info;
  820. pg_info = &(Map->fInfo.pg);
  821. offset_info = &(pg_info->offset);
  822. if (nparts < 1)
  823. return -1;
  824. /* check required PG settings */
  825. if (!pg_info->conn) {
  826. G_warning(_("No connection defined"));
  827. return -1;
  828. }
  829. if (!pg_info->table_name) {
  830. G_warning(_("PostGIS feature table not defined"));
  831. return -1;
  832. }
  833. /* create PostGIS table if doesn't exist */
  834. if (pg_info->feature_type == SF_UNKNOWN) {
  835. if (create_pg_layer(Map, type) < 0)
  836. return -1;
  837. }
  838. /* get category & check for attributes */
  839. Fi = NULL;
  840. cat = -1;
  841. if (cats->n_cats > 0) {
  842. int field;
  843. field = cats->field[0]; /* we assume only one layer defined */
  844. if (Vect_get_num_dblinks(Map) > 0) {
  845. /* check for attributes */
  846. Fi = Vect_get_field(Map, field);
  847. }
  848. if (!Vect_cat_get(cats, field, &cat))
  849. G_warning(_("No category defined for layer %d"), field);
  850. if (cats->n_cats > 1) {
  851. G_warning(_("Feature has more categories, using "
  852. "category %d (from layer %d)"),
  853. cat, field);
  854. }
  855. }
  856. sf_type = pg_info->feature_type;
  857. /* determine matching PostGIS feature geometry type */
  858. if (type & (GV_POINT | GV_KERNEL)) {
  859. if (sf_type != SF_POINT && sf_type != SF_POINT25D) {
  860. G_warning(_("Point skipped (output feature type: %s)"),
  861. Vect_get_finfo_geometry_type(Map));
  862. return 0;
  863. }
  864. }
  865. else if (type & GV_LINE) {
  866. if (sf_type != SF_LINESTRING && sf_type != SF_LINESTRING25D) {
  867. G_warning(_("Line skipped (output feature type: %s)"),
  868. Vect_get_finfo_geometry_type(Map));
  869. return 0;
  870. }
  871. }
  872. else if (type & GV_BOUNDARY || type & GV_CENTROID) {
  873. if (sf_type != SF_POLYGON) {
  874. G_warning(_("Boundary/centroid skipped (output feature type: %s)"),
  875. Vect_get_finfo_geometry_type(Map));
  876. G_warning(_("Feature is not a polygon. Skipping."));
  877. return 0;
  878. }
  879. }
  880. else if (type & GV_FACE) {
  881. if (sf_type != SF_POLYGON25D) {
  882. G_warning(_("Face skipped (output feature type: %s)"),
  883. Vect_get_finfo_geometry_type(Map));
  884. return 0;
  885. }
  886. }
  887. else {
  888. G_warning(_("Unsupported feature type %d"), type);
  889. return -1;
  890. }
  891. G_debug(3, "write_line_sf(): type = %d n_points = %d cat = %d",
  892. type, points[0]->n_points, cat);
  893. if (sf_type == SF_POLYGON || sf_type == SF_POLYGON25D) {
  894. /* skip this check when writing PostGIS topology */
  895. int part, npoints;
  896. for (part = 0; part < nparts; part++) {
  897. npoints = points[part]->n_points - 1;
  898. if (points[part]->x[0] != points[part]->x[npoints] ||
  899. points[part]->y[0] != points[part]->y[npoints] ||
  900. points[part]->z[0] != points[part]->z[npoints]) {
  901. G_warning(_("Boundary is not closed. Skipping."));
  902. return -1;
  903. }
  904. }
  905. }
  906. /* write feature's geometry and fid */
  907. if (-1 == write_feature(Map, -1, type, points, nparts, cat, Fi)) {
  908. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  909. return -1;
  910. }
  911. /* update offset array */
  912. if (offset_info->array_num >= offset_info->array_alloc) {
  913. offset_info->array_alloc += 1000;
  914. offset_info->array = (int *)G_realloc(offset_info->array,
  915. offset_info->array_alloc *
  916. sizeof(int));
  917. }
  918. offset = offset_info->array_num;
  919. offset_info->array[offset_info->array_num++] = cat;
  920. if (sf_type == SF_POLYGON || sf_type == SF_POLYGON25D) {
  921. /* register first part in offset array */
  922. offset_info->array[offset_info->array_num++] = 0;
  923. }
  924. G_debug(3, "write_line_sf(): -> offset = %lu offset_num = %d cat = %d",
  925. (unsigned long)offset, offset_info->array_num, cat);
  926. return offset;
  927. }
  928. /*!
  929. \brief Write vector feature in PostGIS topology schema and
  930. updates internal topology structures
  931. \param Map vector map
  932. \param type feature type to be written
  933. \param points feature geometry
  934. \param is_node TRUE for nodes (written as points)
  935. \return feature id (build level >= GV_BUILD_BASE otherwise 0)
  936. \return -1 on error
  937. */
  938. off_t write_line_tp(struct Map_info *Map, int type, int is_node,
  939. const struct line_pnts *points,
  940. const struct line_cats *cats)
  941. {
  942. int line, cat;
  943. struct field_info *Fi;
  944. struct Format_info_pg *pg_info;
  945. struct Plus_head *plus;
  946. pg_info = &(Map->fInfo.pg);
  947. plus = &(Map->plus);
  948. /* check type for nodes */
  949. if (is_node && type != GV_POINT) {
  950. G_warning(_("Invalid feature type (%d) for nodes"), type);
  951. return -1;
  952. }
  953. /* check required PG settings */
  954. if (!pg_info->conn) {
  955. G_warning(_("No connection defined"));
  956. return -1;
  957. }
  958. if (!pg_info->table_name) {
  959. G_warning(_("PostGIS feature table not defined"));
  960. return -1;
  961. }
  962. if (!pg_info->toposchema_name) {
  963. G_warning(_("PostGIS topology schema not defined"));
  964. return -1;
  965. }
  966. /* create PostGIS table if doesn't exist */
  967. if (pg_info->feature_type == SF_UNKNOWN) {
  968. if (create_pg_layer(Map, type) < 0)
  969. return -1;
  970. }
  971. if (!points)
  972. return 0;
  973. G_debug(3, "write_line_pg(): type = %d n_points = %d",
  974. type, points->n_points);
  975. Fi = NULL; /* no attributes to be written */
  976. cat = -1;
  977. if (cats && cats->n_cats > 0) {
  978. if (Vect_get_num_dblinks(Map) > 0) {
  979. /* check for attributes */
  980. Fi = Vect_get_dblink(Map, 0);
  981. if (Fi) {
  982. if (!Vect_cat_get(cats, Fi->number, &cat))
  983. G_warning(_("No category defined for layer %d"), Fi->number);
  984. if (cats->n_cats > 1) {
  985. G_warning(_("Feature has more categories, using "
  986. "category %d (from layer %d)"),
  987. cat, cats->field[0]);
  988. }
  989. }
  990. }
  991. /* assume layer=1 */
  992. Vect_cat_get(cats, 1, &cat);
  993. }
  994. /* update GRASS topology before writing PostGIS feature */
  995. line = 0;
  996. if (plus->built >= GV_BUILD_BASE) {
  997. if (is_node) {
  998. /* nodes are given with negative id */
  999. line = -1 * dig_add_node(plus, points->x[0], points->y[0], points->z[0]);
  1000. }
  1001. else {
  1002. off_t offset;
  1003. /* better is probably to check nextval directly */
  1004. if (type & GV_POINTS) {
  1005. offset = Vect_get_num_primitives(Map, GV_POINTS) + 1; /* next */
  1006. offset += Vect_get_num_nodes(Map); /* nodes are also stored in 'node' table */
  1007. }
  1008. else { /* LINES */
  1009. offset = Vect_get_num_primitives(Map, GV_LINES) + 1; /* next */
  1010. }
  1011. line = add_line_to_topo_pg(Map, offset, type, points);
  1012. }
  1013. }
  1014. /* write new feature to PostGIS
  1015. - feature table for simple features
  1016. - feature table and topo schema for topological access
  1017. */
  1018. if (-1 == write_feature(Map, line, type, &points, 1, cat, Fi)) {
  1019. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1020. return -1;
  1021. }
  1022. /* update PostGIS-line topo */
  1023. if (plus->built >= GV_BUILD_AREAS && type == GV_BOUNDARY)
  1024. update_topo_face(Map, line); /* TODO: avoid extra statements */
  1025. return !is_node ? line : 0;
  1026. }
  1027. /*!
  1028. \brief Binary data to HEX
  1029. Allocated buffer should be freed by G_free().
  1030. \param nbytes number of bytes to allocate
  1031. \param wkb_data WKB data
  1032. \return allocated buffer with HEX data
  1033. */
  1034. char *binary_to_hex(int nbytes, const unsigned char *wkb_data)
  1035. {
  1036. char *hex_data;
  1037. int i, nlow, nhigh;
  1038. static const char ach_hex[] = "0123456789ABCDEF";
  1039. hex_data = (char *)G_malloc(nbytes * 2 + 1);
  1040. hex_data[nbytes * 2] = '\0';
  1041. for (i = 0; i < nbytes; i++) {
  1042. nlow = wkb_data[i] & 0x0f;
  1043. nhigh = (wkb_data[i] & 0xf0) >> 4;
  1044. hex_data[i * 2] = ach_hex[nhigh];
  1045. hex_data[i * 2 + 1] = ach_hex[nlow];
  1046. }
  1047. return hex_data;
  1048. }
  1049. /*!
  1050. \brief Write point into WKB buffer
  1051. See OGRPoint::exportToWkb from GDAL/OGR library
  1052. \param byte_order byte order (ENDIAN_LITTLE or BIG_ENDIAN)
  1053. \param points feature geometry
  1054. \param with_z WITH_Z for 3D data
  1055. \param[out] nsize buffer size
  1056. \return allocated WKB buffer
  1057. \return NULL on error
  1058. */
  1059. unsigned char *point_to_wkb(int byte_order,
  1060. const struct line_pnts *points, int with_z,
  1061. int *nsize)
  1062. {
  1063. unsigned char *wkb_data;
  1064. unsigned int sf_type;
  1065. if (points->n_points != 1)
  1066. return NULL;
  1067. /* allocate buffer */
  1068. *nsize = with_z ? 29 : 21;
  1069. wkb_data = G_malloc(*nsize);
  1070. G_zero(wkb_data, *nsize);
  1071. G_debug(5, "\t->point size=%d (with_z = %d)", *nsize, with_z);
  1072. /* set the byte order */
  1073. if (byte_order == ENDIAN_LITTLE)
  1074. wkb_data[0] = '\001';
  1075. else
  1076. wkb_data[0] = '\000';
  1077. /* set the geometry feature type */
  1078. sf_type = with_z ? SF_POINT25D : SF_POINT;
  1079. if (byte_order == ENDIAN_LITTLE)
  1080. sf_type = LSBWORD32(sf_type);
  1081. else
  1082. sf_type = MSBWORD32(sf_type);
  1083. memcpy(wkb_data + 1, &sf_type, 4);
  1084. /* copy in the raw data */
  1085. memcpy(wkb_data + 5, &(points->x[0]), 8);
  1086. memcpy(wkb_data + 5 + 8, &(points->y[0]), 8);
  1087. if (with_z) {
  1088. memcpy(wkb_data + 5 + 16, &(points->z[0]), 8);
  1089. }
  1090. /* swap if needed */
  1091. if (byte_order == ENDIAN_BIG) {
  1092. SWAPDOUBLE(wkb_data + 5);
  1093. SWAPDOUBLE(wkb_data + 5 + 8);
  1094. if (with_z)
  1095. SWAPDOUBLE(wkb_data + 5 + 16);
  1096. }
  1097. return wkb_data;
  1098. }
  1099. /*!
  1100. \bried Write linestring into WKB buffer
  1101. See OGRLineString::exportToWkb from GDAL/OGR library
  1102. \param byte_order byte order (ENDIAN_LITTLE or ENDIAN_BIG)
  1103. \param points feature geometry
  1104. \param with_z WITH_Z for 3D data
  1105. \param[out] nsize buffer size
  1106. \return allocated WKB buffer
  1107. \return NULL on error
  1108. */
  1109. unsigned char *linestring_to_wkb(int byte_order,
  1110. const struct line_pnts *points, int with_z,
  1111. int *nsize)
  1112. {
  1113. int i, point_size;
  1114. unsigned char *wkb_data;
  1115. unsigned int sf_type;
  1116. if (points->n_points < 1)
  1117. return NULL;
  1118. /* allocate buffer */
  1119. point_size = 8 * (with_z ? 3 : 2);
  1120. *nsize = 5 + 4 + points->n_points * point_size;
  1121. wkb_data = G_malloc(*nsize);
  1122. G_zero(wkb_data, *nsize);
  1123. G_debug(5, "\t->linestring size=%d (with_z = %d)", *nsize, with_z);
  1124. /* set the byte order */
  1125. if (byte_order == ENDIAN_LITTLE)
  1126. wkb_data[0] = '\001';
  1127. else
  1128. wkb_data[0] = '\000';
  1129. /* set the geometry feature type */
  1130. sf_type = with_z ? SF_LINESTRING25D : SF_LINESTRING;
  1131. if (byte_order == ENDIAN_LITTLE)
  1132. sf_type = LSBWORD32(sf_type);
  1133. else
  1134. sf_type = MSBWORD32(sf_type);
  1135. memcpy(wkb_data + 1, &sf_type, 4);
  1136. /* copy in the data count */
  1137. memcpy(wkb_data + 5, &(points->n_points), 4);
  1138. /* copy in the raw data */
  1139. for (i = 0; i < points->n_points; i++) {
  1140. memcpy(wkb_data + 9 + point_size * i, &(points->x[i]), 8);
  1141. memcpy(wkb_data + 9 + 8 + point_size * i, &(points->y[i]), 8);
  1142. if (with_z) {
  1143. memcpy(wkb_data + 9 + 16 + point_size * i, &(points->z[i]), 8);
  1144. }
  1145. }
  1146. /* swap if needed */
  1147. if (byte_order == ENDIAN_BIG) {
  1148. int npoints, nitems;
  1149. npoints = SWAP32(points->n_points);
  1150. memcpy(wkb_data + 5, &npoints, 4);
  1151. nitems = (with_z ? 3 : 2) * points->n_points;
  1152. for (i = 0; i < nitems; i++) {
  1153. SWAPDOUBLE(wkb_data + 9 + 4 + 8 * i);
  1154. }
  1155. }
  1156. return wkb_data;
  1157. }
  1158. /*!
  1159. \bried Write polygon into WKB buffer
  1160. See OGRPolygon::exportToWkb from GDAL/OGR library
  1161. \param byte_order byte order (ENDIAN_LITTLE or ENDIAN_BIG)
  1162. \param ipoints list of ring geometries (first is outer ring)
  1163. \param nrings number of rings
  1164. \param with_z WITH_Z for 3D data
  1165. \param[out] nsize buffer size
  1166. \return allocated WKB buffer
  1167. \return NULL on error
  1168. */
  1169. unsigned char *polygon_to_wkb(int byte_order,
  1170. const struct line_pnts** points, int nrings,
  1171. int with_z, int *nsize)
  1172. {
  1173. int i, ring, point_size, offset;
  1174. unsigned char *wkb_data;
  1175. unsigned int sf_type;
  1176. /* check data validity */
  1177. if (nrings < 1)
  1178. return NULL;
  1179. for (ring = 0; ring < nrings; ring++) {
  1180. if (points[ring]->n_points < 3)
  1181. return NULL;
  1182. }
  1183. /* allocate buffer */
  1184. point_size = 8 * (with_z ? 3 : 2);
  1185. *nsize = 9;
  1186. for (ring = 0; ring < nrings; ring++)
  1187. *nsize += 4 + point_size * points[ring]->n_points;
  1188. wkb_data = G_malloc(*nsize);
  1189. G_zero(wkb_data, *nsize);
  1190. G_debug(5, "\t->polygon size=%d (with_z = %d)", *nsize, with_z);
  1191. /* set the byte order */
  1192. if (byte_order == ENDIAN_LITTLE)
  1193. wkb_data[0] = '\001';
  1194. else
  1195. wkb_data[0] = '\000';
  1196. /* set the geometry feature type */
  1197. sf_type = with_z ? SF_POLYGON25D : SF_POLYGON;
  1198. if (byte_order == ENDIAN_LITTLE)
  1199. sf_type = LSBWORD32(sf_type);
  1200. else
  1201. sf_type = MSBWORD32(sf_type);
  1202. memcpy(wkb_data + 1, &sf_type, 4);
  1203. /* copy in the raw data */
  1204. if (byte_order == ENDIAN_BIG) {
  1205. int ncount;
  1206. ncount = SWAP32(nrings);
  1207. memcpy(wkb_data + 5, &ncount, 4);
  1208. }
  1209. else {
  1210. memcpy(wkb_data + 5, &nrings, 4);
  1211. }
  1212. /* serialize rings */
  1213. offset = 9;
  1214. for (ring = 0; ring < nrings; ring++) {
  1215. memcpy(wkb_data + offset, &(points[ring]->n_points), 4);
  1216. for (i = 0; i < points[ring]->n_points; i++) {
  1217. memcpy(wkb_data + offset +
  1218. 4 + point_size * i, &(points[ring]->x[i]), 8);
  1219. memcpy(wkb_data + offset +
  1220. 4 + 8 + point_size * i, &(points[ring]->y[i]), 8);
  1221. if (with_z) {
  1222. memcpy(wkb_data + offset +
  1223. 4 + 16 + point_size * i, &(points[ring]->z[i]), 8);
  1224. }
  1225. }
  1226. offset += 4 + point_size * points[ring]->n_points;
  1227. /* swap if needed */
  1228. if (byte_order == ENDIAN_BIG) {
  1229. int npoints, nitems;
  1230. npoints = SWAP32(points[ring]->n_points);
  1231. memcpy(wkb_data + 5, &npoints, 4);
  1232. nitems = (with_z ? 3 : 2) * points[ring]->n_points;
  1233. for (i = 0; i < nitems; i++) {
  1234. SWAPDOUBLE(wkb_data + offset + 4 + 8 * i);
  1235. }
  1236. }
  1237. }
  1238. return wkb_data;
  1239. }
  1240. /*!
  1241. \brief Write feature to WKB buffer
  1242. Allocated string buffer should be freed by G_free().
  1243. \param pg_info pointer to Format_info_pg struct
  1244. \param points array of geometries which form feature
  1245. \param nparts number of geometries in array
  1246. \param type feature type (GV_POINT, GV_LINE, ...)
  1247. \param with_z WITH_Z for 3D data
  1248. \return allocated string buffer
  1249. \return NULL on error
  1250. */
  1251. char *line_to_wkb(struct Format_info_pg *pg_info,
  1252. const struct line_pnts **points, int nparts, int type, int with_z)
  1253. {
  1254. int byte_order, nbytes, nsize;
  1255. unsigned int sf_type;
  1256. unsigned char *wkb_data;
  1257. char *text_data, *text_data_p, *hex_data;
  1258. byte_order = dig__byte_order_out();
  1259. /* get wkb data */
  1260. nbytes = -1;
  1261. wkb_data = NULL;
  1262. if (type & GV_POINTS) /* point or centroid */
  1263. wkb_data = point_to_wkb(byte_order, points[0], with_z, &nbytes);
  1264. else if (type == GV_LINE)
  1265. wkb_data = linestring_to_wkb(byte_order, points[0], with_z, &nbytes);
  1266. else if (type == GV_BOUNDARY) {
  1267. if (!pg_info->toposchema_name) {
  1268. /* PostGIS simple feature access */
  1269. wkb_data = polygon_to_wkb(byte_order, points, nparts,
  1270. with_z, &nbytes);
  1271. }
  1272. else {
  1273. /* PostGIS topology access */
  1274. wkb_data = linestring_to_wkb(byte_order, points[0], with_z, &nbytes);
  1275. }
  1276. }
  1277. if (!wkb_data || nbytes < 1) {
  1278. G_warning(_("Unsupported feature type %d"), type);
  1279. return NULL;
  1280. }
  1281. /* When converting to hex, each byte takes 2 hex characters. In
  1282. addition we add in 8 characters to represent the SRID integer
  1283. in hex, and one for a null terminator */
  1284. nsize = nbytes * 2 + 8 + 1;
  1285. text_data = text_data_p = (char *)G_malloc(nsize);
  1286. /* convert the 1st byte, which is the endianess flag, to hex */
  1287. hex_data = binary_to_hex(1, wkb_data);
  1288. strcpy(text_data_p, hex_data);
  1289. G_free(hex_data);
  1290. text_data_p += 2;
  1291. /* get the geom type which is bytes 2 through 5 */
  1292. memcpy(&sf_type, wkb_data + 1, 4);
  1293. /* add the SRID flag if an SRID is provided */
  1294. if (pg_info->srid > 0) {
  1295. unsigned int srs_flag;
  1296. /* change the flag to little endianess */
  1297. srs_flag = LSBWORD32(WKBSRIDFLAG);
  1298. /* apply the flag */
  1299. sf_type = sf_type | srs_flag;
  1300. }
  1301. /* write the geom type which is 4 bytes */
  1302. hex_data = binary_to_hex(4, (unsigned char *)&sf_type);
  1303. strcpy(text_data_p, hex_data);
  1304. G_free(hex_data);
  1305. text_data_p += 8;
  1306. /* include SRID if provided */
  1307. if (pg_info->srid > 0) {
  1308. unsigned int srs_id;
  1309. /* force the srsid to little endianess */
  1310. srs_id = LSBWORD32(pg_info->srid);
  1311. hex_data = binary_to_hex(sizeof(srs_id), (unsigned char *)&srs_id);
  1312. strcpy(text_data_p, hex_data);
  1313. G_free(hex_data);
  1314. text_data_p += 8;
  1315. }
  1316. /* copy the rest of the data over - subtract 5 since we already
  1317. copied 5 bytes above */
  1318. hex_data = binary_to_hex(nbytes - 5, wkb_data + 5);
  1319. strcpy(text_data_p, hex_data);
  1320. G_free(hex_data);
  1321. return text_data;
  1322. }
  1323. /*!
  1324. \brief Insert feature into table
  1325. \param Map pointer to Map_info structure
  1326. \param line feature id (topo access only)
  1327. \param type feature type (GV_POINT, GV_LINE, ...)
  1328. \param points pointer to line_pnts struct
  1329. \param nparts number of parts (rings for polygon)
  1330. \param cat category number (-1 for no category)
  1331. \param Fi pointer to field_info (attributes to copy, NULL for no attributes)
  1332. \return -1 on error
  1333. \retirn 0 on success
  1334. */
  1335. int write_feature(struct Map_info *Map, int line, int type,
  1336. const struct line_pnts **points, int nparts,
  1337. int cat, const struct field_info *Fi)
  1338. {
  1339. int with_z, topo_id;
  1340. char *stmt, *geom_data;
  1341. struct Format_info_pg *pg_info;
  1342. pg_info = &(Map->fInfo.pg);
  1343. with_z = Map->head.with_z;
  1344. if (with_z && pg_info->coor_dim != 3) {
  1345. G_warning(_("Trying to insert 3D data into feature table "
  1346. "which store 2D data only"));
  1347. return -1;
  1348. }
  1349. if (!with_z && pg_info->coor_dim != 2) {
  1350. G_warning(_("Trying to insert 2D data into feature table "
  1351. "which store 3D data only"));
  1352. return -1;
  1353. }
  1354. /* build WKB geometry from line_pnts structures */
  1355. geom_data = line_to_wkb(pg_info, points, nparts, type, with_z);
  1356. if (!geom_data)
  1357. return -1;
  1358. /* start transaction */
  1359. if (!pg_info->inTransaction) {
  1360. pg_info->inTransaction = TRUE;
  1361. if (Vect__execute_pg(pg_info->conn, "BEGIN") == -1) {
  1362. G_free(geom_data);
  1363. return -1;
  1364. }
  1365. }
  1366. /* write feature in PostGIS topology schema if enabled */
  1367. topo_id = -1;
  1368. if (pg_info->toposchema_name) {
  1369. /* insert feature into topology schema (node or edge) */
  1370. topo_id = insert_topo_element(Map, line, type, geom_data);
  1371. if (topo_id < 0) {
  1372. G_warning(_("Unable to insert topological element into PostGIS Topology schema"));
  1373. G_free(geom_data);
  1374. return -1;
  1375. }
  1376. }
  1377. /* build INSERT statement
  1378. simple feature geometry + attributes
  1379. */
  1380. stmt = build_insert_stmt(pg_info, geom_data, topo_id, cat, Fi);
  1381. /* stmt can NULL when writing PostGIS topology with no attributes
  1382. * attached */
  1383. if (stmt && Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1384. /* rollback transaction */
  1385. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1386. G_free(geom_data);
  1387. G_free(stmt);
  1388. return -1;
  1389. }
  1390. G_free(geom_data);
  1391. return 0;
  1392. }
  1393. /*!
  1394. \brief Build INSERT statement to add new feature to the feature
  1395. table
  1396. Note: Allocated string should be freed.
  1397. \param pg_info pointer to Format_info_pg structure
  1398. \param geom_data geometry data
  1399. \param type feature type (GV_POINT, GV_LINE, ...) - (only for PostGIS Topology)
  1400. \param id topology element id (only for PostGIS Topology)
  1401. \param cat category number (or -1 for no category)
  1402. \param Fi pointer to field_info structure (NULL for no attributes)
  1403. \return allocated string with INSERT statement
  1404. */
  1405. char *build_insert_stmt(const struct Format_info_pg *pg_info,
  1406. const char *geom_data, int topo_id,
  1407. int cat, const struct field_info *Fi)
  1408. {
  1409. int topogeom_type;
  1410. char *stmt, buf[DB_SQL_MAX];
  1411. topogeom_type = -1;
  1412. if (pg_info->toposchema_name) {
  1413. switch (pg_info->feature_type) {
  1414. case SF_POINT:
  1415. topogeom_type = 1;
  1416. break;
  1417. case SF_LINESTRING:
  1418. topogeom_type = 2;
  1419. break;
  1420. case SF_POLYGON:
  1421. topogeom_type = 3;
  1422. break;
  1423. default:
  1424. G_warning(_("Unsupported feature type %d"), pg_info->feature_type);
  1425. return NULL;
  1426. }
  1427. }
  1428. stmt = NULL;
  1429. if (Fi && cat > -1) { /* write attributes (simple features and topology elements) */
  1430. int col, ncol, more;
  1431. int sqltype, ctype, is_fid;
  1432. char buf_val[DB_SQL_MAX], buf_tmp[DB_SQL_MAX];
  1433. const char *colname;
  1434. dbString dbstmt;
  1435. dbCursor cursor;
  1436. dbTable *table;
  1437. dbColumn *column;
  1438. dbValue *value;
  1439. db_init_string(&dbstmt);
  1440. buf_val[0] = '\0';
  1441. /* read & set attributes */
  1442. sprintf(buf, "SELECT * FROM %s WHERE %s = %d", Fi->table, Fi->key,
  1443. cat);
  1444. G_debug(4, "SQL: %s", buf);
  1445. db_set_string(&dbstmt, buf);
  1446. /* prepare INSERT statement */
  1447. sprintf(buf, "INSERT INTO \"%s\".\"%s\" (",
  1448. pg_info->schema_name, pg_info->table_name);
  1449. /* select data */
  1450. if (db_open_select_cursor(pg_info->dbdriver, &dbstmt,
  1451. &cursor, DB_SEQUENTIAL) != DB_OK) {
  1452. G_warning(_("Unable to select attributes for category %d"), cat);
  1453. }
  1454. else {
  1455. if (db_fetch(&cursor, DB_NEXT, &more) != DB_OK) {
  1456. G_warning(_("Unable to fetch data from table <%s>"),
  1457. Fi->table);
  1458. }
  1459. if (!more) {
  1460. G_warning(_("No database record for category %d, "
  1461. "no attributes will be written"), cat);
  1462. }
  1463. else {
  1464. table = db_get_cursor_table(&cursor);
  1465. ncol = db_get_table_number_of_columns(table);
  1466. for (col = 0; col < ncol; col++) {
  1467. column = db_get_table_column(table, col);
  1468. colname = db_get_column_name(column);
  1469. /* -> values */
  1470. value = db_get_column_value(column);
  1471. /* for debug only */
  1472. db_convert_column_value_to_string(column, &dbstmt);
  1473. G_debug(2, "col %d : val = %s", col,
  1474. db_get_string(&dbstmt));
  1475. sqltype = db_get_column_sqltype(column);
  1476. ctype = db_sqltype_to_Ctype(sqltype);
  1477. is_fid = strcmp(pg_info->fid_column, colname) == 0;
  1478. /* check fid column (must be integer) */
  1479. if (is_fid == TRUE &&
  1480. ctype != DB_C_TYPE_INT) {
  1481. G_warning(_("FID column must be integer, column <%s> ignored!"),
  1482. colname);
  1483. continue;
  1484. }
  1485. /* -> columns */
  1486. sprintf(buf_tmp, "%s", colname);
  1487. strcat(buf, buf_tmp);
  1488. if (col < ncol - 1)
  1489. strcat(buf, ",");
  1490. /* prevent writing NULL values */
  1491. if (!db_test_value_isnull(value)) {
  1492. switch (ctype) {
  1493. case DB_C_TYPE_INT:
  1494. sprintf(buf_tmp, "%d", db_get_value_int(value));
  1495. break;
  1496. case DB_C_TYPE_DOUBLE:
  1497. sprintf(buf_tmp, "%.14f",
  1498. db_get_value_double(value));
  1499. break;
  1500. case DB_C_TYPE_STRING: {
  1501. char *value_tmp;
  1502. value_tmp = G_str_replace(db_get_value_string(value), "'", "''");
  1503. sprintf(buf_tmp, "'%s'", value_tmp);
  1504. G_free(value_tmp);
  1505. break;
  1506. }
  1507. case DB_C_TYPE_DATETIME:
  1508. db_convert_column_value_to_string(column,
  1509. &dbstmt);
  1510. sprintf(buf_tmp, "%s", db_get_string(&dbstmt));
  1511. break;
  1512. default:
  1513. G_warning(_("Unsupported column type %d"), ctype);
  1514. sprintf(buf_tmp, "NULL");
  1515. break;
  1516. }
  1517. }
  1518. else {
  1519. if (is_fid == TRUE)
  1520. G_warning(_("Invalid value for FID column: NULL"));
  1521. sprintf(buf_tmp, "NULL");
  1522. }
  1523. strcat(buf_val, buf_tmp);
  1524. if (col < ncol - 1)
  1525. strcat(buf_val, ",");
  1526. }
  1527. if (!pg_info->toposchema_name) {
  1528. /* simple feature access */
  1529. G_asprintf(&stmt, "%s,%s) VALUES (%s,'%s'::GEOMETRY)",
  1530. buf, pg_info->geom_column, buf_val, geom_data);
  1531. }
  1532. else {
  1533. /* PostGIS topology access, write geometry in
  1534. * topology schema, skip geometry at this point */
  1535. if (buf[strlen(buf)-1] == ',') { /* last column skipped */
  1536. buf[strlen(buf)-1] = '\0';
  1537. buf_val[strlen(buf_val)-1] = '\0';
  1538. }
  1539. G_asprintf(&stmt, "%s, %s) VALUES (%s, '(%d, 1, %d, %d)'::topology.TopoGeometry)",
  1540. buf, pg_info->topogeom_column, buf_val,
  1541. pg_info->toposchema_id, topo_id, topogeom_type);
  1542. }
  1543. }
  1544. }
  1545. }
  1546. else {
  1547. /* no attributes */
  1548. if (!pg_info->toposchema_name) {
  1549. /* no attributes (simple features access) */
  1550. if (cat > 0) {
  1551. /* cetegory defined */
  1552. G_asprintf(&stmt, "INSERT INTO \"%s\".\"%s\" (%s,%s) VALUES "
  1553. "(%d, '%s'::GEOMETRY)",
  1554. pg_info->schema_name, pg_info->table_name,
  1555. GV_KEY_COLUMN, pg_info->geom_column,
  1556. cat, geom_data);
  1557. }
  1558. else {
  1559. /* no category */
  1560. G_asprintf(&stmt, "INSERT INTO \"%s\".\"%s\" (%s) VALUES "
  1561. "('%s'::GEOMETRY)",
  1562. pg_info->schema_name, pg_info->table_name,
  1563. pg_info->geom_column, geom_data);
  1564. }
  1565. }
  1566. else {
  1567. if (cat > 0) {
  1568. /* no attributes (topology elements) */
  1569. G_asprintf(&stmt, "INSERT INTO \"%s\".\"%s\" (%s,%s) VALUES "
  1570. "(%d, '(%d, 1, %d, %d)'::topology.TopoGeometry)",
  1571. pg_info->schema_name, pg_info->table_name,
  1572. GV_KEY_COLUMN, pg_info->topogeom_column, cat,
  1573. pg_info->toposchema_id, topo_id, topogeom_type);
  1574. }
  1575. }
  1576. }
  1577. return stmt;
  1578. }
  1579. /*!
  1580. \brief Insert topological element into 'node' or 'edge' table
  1581. Negative id for nodes, 0 for next value.
  1582. \param Map pointer to Map_info struct
  1583. \param id feature id (0 for next val)
  1584. \param type feature type (GV_POINT, GV_LINE, ...)
  1585. \param geom_data geometry in wkb
  1586. \return new topo id
  1587. \return -1 on error
  1588. */
  1589. int insert_topo_element(struct Map_info *Map, int id, int type,
  1590. const char *geom_data)
  1591. {
  1592. int ret, topo_id;
  1593. char *stmt, stmt_id[DB_SQL_MAX];
  1594. struct Format_info_pg *pg_info;
  1595. struct Plus_head *plus;
  1596. struct P_line *Line;
  1597. pg_info = &(Map->fInfo.pg);
  1598. plus = &(Map->plus);
  1599. Line = NULL;
  1600. if (plus->built >= GV_BUILD_BASE) {
  1601. if (id > 0) { /* -> feature */
  1602. topo_id = id;
  1603. if (topo_id > Map->plus.n_lines) {
  1604. G_warning(_("Invalid feature %d (max: %d)"), topo_id, Map->plus.n_lines);
  1605. return -1;
  1606. }
  1607. Line = Map->plus.Line[topo_id];
  1608. }
  1609. else if (id < 0) { /* node */
  1610. topo_id = abs(id);
  1611. if (type != GV_POINT) {
  1612. G_warning(_("Invalid feature type (%d) for node"), type);
  1613. return -1;
  1614. }
  1615. if (topo_id > Map->plus.n_nodes) {
  1616. G_warning(_("Invalid node %d (%d)"), topo_id, Map->plus.n_nodes);
  1617. return -1;
  1618. }
  1619. }
  1620. }
  1621. stmt = NULL;
  1622. switch(type) {
  1623. case GV_POINT: {
  1624. /* insert new node */
  1625. #if USE_TOPO_STMT
  1626. G_asprintf(&stmt, "SELECT topology.AddNode('%s', '%s'::GEOMETRY)",
  1627. pg_info->toposchema_name, geom_data);
  1628. #else
  1629. if (id == 0) {
  1630. /* get node_id */
  1631. sprintf(stmt_id, "SELECT nextval('\"%s\".node_node_id_seq')",
  1632. pg_info->toposchema_name);
  1633. topo_id = Vect__execute_get_value_pg(pg_info->conn, stmt_id);
  1634. }
  1635. /* build insert statement */
  1636. G_asprintf(&stmt, "INSERT INTO \"%s\".node (node_id, geom) VALUES "
  1637. "(%d, '%s'::GEOMETRY)", pg_info->toposchema_name, topo_id, geom_data);
  1638. #endif
  1639. break;
  1640. }
  1641. case GV_LINE:
  1642. case GV_BOUNDARY: {
  1643. /* insert new edge */
  1644. #if USE_TOPO_STMT
  1645. G_asprintf(&stmt, "SELECT topology.AddEdge('%s', '%s'::GEOMETRY)",
  1646. pg_info->toposchema_name, geom_data);
  1647. #else
  1648. int n1, n2, nle, nre;
  1649. if (id == 0) {
  1650. /* get edge_id */
  1651. sprintf(stmt_id, "SELECT nextval('\"%s\".edge_data_edge_id_seq')",
  1652. pg_info->toposchema_name);
  1653. topo_id = Vect__execute_get_value_pg(pg_info->conn, stmt_id);
  1654. }
  1655. nle = -topo_id; /* assuming isolated lines */
  1656. nre = topo_id;
  1657. if (Line) {
  1658. int i, n, next_edge;
  1659. struct P_topo_l *topo = (struct P_topo_l *) Line->topo;
  1660. topo_id = (int)Line->offset;
  1661. /* start & end node */
  1662. n1 = topo->N1;
  1663. n2 = topo->N2;
  1664. /* next left & right edge */
  1665. for (i = 0; i < 2; i++) {
  1666. n = Vect_get_node_n_lines(Map, i == 0 ? n1 : n2);
  1667. if (n < 2) /* no connection */
  1668. continue;
  1669. next_edge = update_next_edge(Map, n,
  1670. i == 0 ? topo_id : -topo_id);
  1671. if (next_edge != 0) {
  1672. if (i == 0)
  1673. nre = next_edge; /* update next right edge for start node */
  1674. else
  1675. nle = next_edge; /* update next left edge for end node */
  1676. }
  1677. else {
  1678. G_warning(_("Unable to determine next left/right edge for edge %d"), topo_id);
  1679. }
  1680. }
  1681. }
  1682. else {
  1683. G_warning(_("Unable to insert new edge. Topology not available."));
  1684. return -1;
  1685. }
  1686. G_debug(3, "new edge: id=%d next_left_edge=%d next_right_edge=%d",
  1687. topo_id, nle, nre);
  1688. /* build insert statement */
  1689. G_asprintf(&stmt, "INSERT INTO \"%s\".edge_data (edge_id, start_node, end_node, "
  1690. "next_left_edge, abs_next_left_edge, next_right_edge, abs_next_right_edge, "
  1691. "left_face, right_face, geom) VALUES "
  1692. "(%d, %d, %d, %d, %d, %d, %d, 0, 0, '%s'::GEOMETRY)",
  1693. pg_info->toposchema_name, topo_id, n1, n2,
  1694. nle, abs(nle), nre, abs(nre), geom_data);
  1695. #endif
  1696. break;
  1697. }
  1698. case GV_CENTROID: {
  1699. /* insert new node (with containing_face) */
  1700. #if USE_TOPO_STMT
  1701. G_asprintf(&stmt, "SELECT topology.AddNode('%s', '%s'::GEOMETRY)",
  1702. pg_info->toposchema_name, geom_data);
  1703. #else
  1704. int area;
  1705. if (id == 0) {
  1706. /* get node_id */
  1707. sprintf(stmt_id, "SELECT nextval('\"%s\".node_node_id_seq')",
  1708. pg_info->toposchema_name);
  1709. topo_id = Vect__execute_get_value_pg(pg_info->conn, stmt_id);
  1710. }
  1711. if (Line) {
  1712. struct P_topo_c *topo = (struct P_topo_c *) Line->topo;
  1713. area = topo->area;
  1714. }
  1715. else {
  1716. area = 0;
  1717. }
  1718. G_asprintf(&stmt, "INSERT INTO \"%s\".node (node_id, containing_face, geom) VALUES "
  1719. "(%d, %d, '%s'::GEOMETRY)", pg_info->toposchema_name,
  1720. topo_id, area, geom_data);
  1721. #endif
  1722. break;
  1723. }
  1724. default:
  1725. G_warning(_("Unsupported feature type %d"), type);
  1726. break;
  1727. }
  1728. /* execute insert statement */
  1729. ret = Vect__execute_pg(pg_info->conn, stmt);
  1730. G_free(stmt);
  1731. if (ret == -1) {
  1732. /* rollback transaction */
  1733. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1734. return -1;
  1735. }
  1736. return topo_id;
  1737. }
  1738. /*!
  1739. \brief Find next line (topo only)
  1740. \param Map pointer to Map_info struct
  1741. \param nlines number of lines
  1742. \param line current line
  1743. \param[out] left left line
  1744. \param[out] right right line
  1745. \return left (line < 0) or right (line > 0) next edge
  1746. \return 0 on failure
  1747. */
  1748. int update_next_edge(struct Map_info* Map, int nlines, int line)
  1749. {
  1750. int ret, next_line, edge;
  1751. char stmt[DB_SQL_MAX];
  1752. const struct Format_info_pg *pg_info;
  1753. struct P_line *Line_next, *Line;
  1754. Line = Line_next = NULL;
  1755. pg_info = &(Map->fInfo.pg);
  1756. /* find next line
  1757. start node -> next on the left
  1758. end node -> next on the right
  1759. */
  1760. next_line = dig_angle_next_line(&(Map->plus), line, GV_LEFT, GV_LINES, NULL);
  1761. G_debug(3, "line=%d next_line=%d", line, next_line);
  1762. if (next_line == 0) {
  1763. G_warning(_("Invalid topology"));
  1764. return 0;
  1765. }
  1766. Line = Map->plus.Line[abs(line)];
  1767. Line_next = Map->plus.Line[abs(next_line)];
  1768. if (!Line || !Line_next) {
  1769. G_warning(_("Invalid topology"));
  1770. return 0;
  1771. }
  1772. if (line > 0) {
  1773. edge = Line->offset;
  1774. ret = next_line > 0 ? Line_next->offset : -Line_next->offset;
  1775. }
  1776. else {
  1777. edge = -Line->offset;
  1778. ret = next_line > 0 ? Line_next->offset : -Line_next->offset;
  1779. }
  1780. if (next_line < 0) {
  1781. sprintf(stmt, "UPDATE \"%s\".edge_data SET next_left_edge = %d, "
  1782. "abs_next_left_edge = %d WHERE edge_id = %d AND abs_next_left_edge = %d",
  1783. pg_info->toposchema_name, edge, abs(edge), (int)Line_next->offset, (int)Line_next->offset);
  1784. G_debug(3, "update edge=%d next_left_edge=%d (?)", (int)Line_next->offset, edge);
  1785. }
  1786. else {
  1787. sprintf(stmt, "UPDATE \"%s\".edge_data SET next_right_edge = %d, "
  1788. "abs_next_right_edge = %d WHERE edge_id = %d AND abs_next_right_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_right_edge=%d (?)", (int)Line_next->offset, edge);
  1791. }
  1792. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1793. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1794. return 0;
  1795. }
  1796. if (nlines > 2) {
  1797. /* more lines connected to the node
  1798. start node -> next on the right
  1799. end node -> next on the left
  1800. */
  1801. next_line = dig_angle_next_line(&(Map->plus), line, GV_RIGHT, GV_LINES, NULL);
  1802. Line_next = Map->plus.Line[abs(next_line)];
  1803. if (next_line < 0) {
  1804. sprintf(stmt, "UPDATE \"%s\".edge_data SET next_left_edge = %d, "
  1805. "abs_next_left_edge = %d WHERE edge_id = %d",
  1806. pg_info->toposchema_name, edge, abs(edge), (int)Line_next->offset);
  1807. G_debug(3, "update edge=%d next_left_edge=%d", (int)Line_next->offset, edge);
  1808. }
  1809. else {
  1810. sprintf(stmt, "UPDATE \"%s\".edge_data SET next_right_edge = %d, "
  1811. "abs_next_right_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_right_edge=%d", (int)Line_next->offset, edge);
  1814. }
  1815. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1816. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1817. return 0;
  1818. }
  1819. }
  1820. return ret;
  1821. }
  1822. /*!
  1823. \brief Insert new face to the 'face' table (topo only)
  1824. \param Map pointer to Map_info struct
  1825. \param area area id (negative id for isles)
  1826. \return 0 on error
  1827. \return area id on success (>0)
  1828. */
  1829. int Vect__insert_face_pg(struct Map_info *Map, int area)
  1830. {
  1831. char *stmt;
  1832. struct Format_info_pg *pg_info;
  1833. struct bound_box box;
  1834. if (area == 0)
  1835. return 0; /* universal face has id '0' in PostGIS Topology */
  1836. stmt = NULL;
  1837. pg_info = &(Map->fInfo.pg);
  1838. /* check if face exists */
  1839. /* get mbr of the area */
  1840. if (area > 0)
  1841. Vect_get_area_box(Map, area, &box);
  1842. else
  1843. Vect_get_isle_box(Map, abs(area), &box);
  1844. /* insert face if not exists */
  1845. G_asprintf(&stmt, "INSERT INTO \"%s\".face (face_id, mbr) VALUES "
  1846. "(%d, ST_GeomFromText('POLYGON((%.12f %.12f, %.12f %.12f, %.12f %.12f, %.12f %.12f, "
  1847. "%.12f %.12f))', %d))", pg_info->toposchema_name, area,
  1848. box.W, box.S, box.W, box.N, box.E, box.N,
  1849. box.E, box.S, box.W, box.S, pg_info->srid);
  1850. G_debug(3, "new face id=%d", area);
  1851. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1852. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1853. return 0;
  1854. }
  1855. G_free(stmt);
  1856. return area;
  1857. }
  1858. /*!
  1859. \brief Delete existing face (currently unused)
  1860. \todo Set foreign keys as DEFERRABLE INITIALLY DEFERRED and use SET
  1861. CONSTRAINTS ALL DEFERRED
  1862. \param Map pointer to Map_info struct
  1863. \param area area id to delete
  1864. \return 0 on success
  1865. \return -1 on error
  1866. */
  1867. int delete_face(const struct Map_info *Map, int area)
  1868. {
  1869. char stmt[DB_SQL_MAX];
  1870. const struct Format_info_pg *pg_info;
  1871. pg_info = &(Map->fInfo.pg);
  1872. /* update centroids first */
  1873. sprintf(stmt, "UPDATE \"%s\".node SET containing_face = 0 "
  1874. "WHERE containing_face = %d",
  1875. pg_info->toposchema_name, area);
  1876. G_debug(3, "SQL: %s", stmt);
  1877. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1878. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1879. return -1;
  1880. }
  1881. /* update also edges (left face) */
  1882. sprintf(stmt, "UPDATE \"%s\".edge_data SET left_face = 0 "
  1883. "WHERE left_face = %d",
  1884. pg_info->toposchema_name, area);
  1885. G_debug(3, "SQL: %s", stmt);
  1886. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1887. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1888. return -1;
  1889. }
  1890. /* update also edges (left face) */
  1891. sprintf(stmt, "UPDATE \"%s\".edge_data SET right_face = 0 "
  1892. "WHERE right_face = %d",
  1893. pg_info->toposchema_name, area);
  1894. G_debug(3, "SQL: %s", stmt);
  1895. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1896. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1897. return -1;
  1898. }
  1899. /* delete face */
  1900. sprintf(stmt, "DELETE FROM \"%s\".face WHERE face_id = %d",
  1901. pg_info->toposchema_name, area);
  1902. G_debug(3, "delete face id=%d", area);
  1903. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1904. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1905. return -1;
  1906. }
  1907. return 0;
  1908. }
  1909. /*!
  1910. \brief Update lines (next left and right edges)
  1911. - isolated edges
  1912. next left edge: -edge
  1913. next right edge: edge
  1914. - connected edges
  1915. next left edge: next edge or -edge
  1916. next right edge: next edge or edge
  1917. \param Map pointer to Map_info struct
  1918. \param line feature id
  1919. \return 0 on success
  1920. \return -1 on error
  1921. */
  1922. int update_topo_edge(struct Map_info *Map, int line)
  1923. {
  1924. int i, n;
  1925. int nle, nre, next_edge;
  1926. char stmt[DB_SQL_MAX];
  1927. struct Format_info_pg *pg_info;
  1928. struct P_line *Line;
  1929. pg_info = &(Map->fInfo.pg);
  1930. if (line < 1 || line > Map->plus.n_lines) {
  1931. G_warning(_("Attempt to access non-existing feature %d"), line);
  1932. return -1;
  1933. }
  1934. Line = Map->plus.Line[line];
  1935. if (!Line) {
  1936. G_warning(_("Attempt to access dead feature %d"), line);
  1937. return -1;
  1938. }
  1939. struct P_topo_l *topo = (struct P_topo_l *) Line->topo;
  1940. nre = nle = 0; /* edge = 0 is an illegal value */
  1941. /* check for line connection */
  1942. for (i = 0; i < 2; i++) {
  1943. /* first check start node then end node */
  1944. n = i == 0 ? Vect_get_node_n_lines(Map, topo->N1)
  1945. : Vect_get_node_n_lines(Map, topo->N2);
  1946. if (n < 2) /* no connection */
  1947. continue;
  1948. next_edge = update_next_edge(Map, n,
  1949. i == 0 ? line : -line);
  1950. if (next_edge != 0) {
  1951. if (i == 0)
  1952. nre = next_edge; /* update next right edge for start node */
  1953. else
  1954. nle = next_edge; /* update next left edge for end node */
  1955. }
  1956. else {
  1957. G_warning(_("Unable to determine next left/right edge"));
  1958. return -1;
  1959. }
  1960. }
  1961. if (nle == 0 && nre == 0) /* nothing changed */
  1962. return 0;
  1963. if (nle != 0 && nre != 0) {
  1964. /* update both next left and right edge */
  1965. sprintf(stmt, "UPDATE \"%s\".edge_data SET "
  1966. "next_left_edge = %d, abs_next_left_edge = %d, "
  1967. "next_right_edge = %d, abs_next_right_edge = %d "
  1968. "WHERE edge_id = %d", pg_info->toposchema_name,
  1969. nle, abs(nle), nre, abs(nre), (int)Line->offset);
  1970. }
  1971. else if (nle != 0) {
  1972. /* update next left edge only */
  1973. sprintf(stmt, "UPDATE \"%s\".edge_data SET "
  1974. "next_left_edge = %d, abs_next_left_edge = %d "
  1975. "WHERE edge_id = %d", pg_info->toposchema_name,
  1976. nle, abs(nle), (int)Line->offset);
  1977. }
  1978. else {
  1979. /* update next right edge only */
  1980. sprintf(stmt, "UPDATE \"%s\".edge_data SET "
  1981. "next_right_edge = %d, abs_next_right_edge = %d "
  1982. "WHERE edge_id = %d", pg_info->toposchema_name,
  1983. nre, abs(nre), (int)Line->offset);
  1984. }
  1985. G_debug(3, "update edge=%d next_left_edge=%d next_right_edge=%d",
  1986. (int)Line->offset, nle, nre);
  1987. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  1988. /* rollback transaction */
  1989. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  1990. return -1;
  1991. }
  1992. return 0;
  1993. }
  1994. /*!
  1995. \brief Update lines (left and right faces)
  1996. TODO: handle isles
  1997. \param Map pointer to Map_info struct
  1998. \param line feature id
  1999. \return 0 on success
  2000. \return -1 on error
  2001. */
  2002. int update_topo_face(struct Map_info *Map, int line)
  2003. {
  2004. int i, s, area, face[2];
  2005. char stmt[DB_SQL_MAX];
  2006. struct Format_info_pg *pg_info;
  2007. struct P_line *Line, *Line_i;
  2008. struct P_area *Area;
  2009. struct P_topo_b *topo, *topo_i;
  2010. pg_info = &(Map->fInfo.pg);
  2011. if (line < 1 || line > Map->plus.n_lines) {
  2012. G_warning(_("Attempt to access non-existing feature %d"), line);
  2013. return -1;
  2014. }
  2015. Line = Map->plus.Line[line];
  2016. if (!Line) {
  2017. G_warning(_("Attempt to access dead feature %d"), line);
  2018. return -1;
  2019. }
  2020. topo = (struct P_topo_b *)Line->topo;
  2021. /* for both side on the current boundary (line) */
  2022. /* create new faces */
  2023. for (s = 0; s < 2; s++) { /* for each side */
  2024. area = s == 0 ? topo->left : topo->right;
  2025. if (area <= 0) /* no area - skip */
  2026. continue;
  2027. face[s] = Vect__insert_face_pg(Map, area);
  2028. if (face[s] < 1) {
  2029. G_warning(_("Unable to create new face"));
  2030. return -1;
  2031. }
  2032. }
  2033. /* update edges forming faces */
  2034. for (s = 0; s < 2; s++) { /* for each side */
  2035. area = s == 0 ? topo->left : topo->right;
  2036. if (area <= 0) /* no area - skip */
  2037. continue;
  2038. Area = Map->plus.Area[area];
  2039. for (i = 0; i < Area->n_lines; i++) {
  2040. Line_i = Map->plus.Line[abs(Area->lines[i])];
  2041. topo_i = (struct P_topo_b *)Line_i->topo;
  2042. sprintf(stmt, "UPDATE \"%s\".edge_data SET "
  2043. "left_face = %d, right_face = %d "
  2044. "WHERE edge_id = %d", pg_info->toposchema_name,
  2045. topo_i->left > 0 ? topo_i->left : 0,
  2046. topo_i->right > 0 ? topo_i->right : 0,
  2047. (int) Line_i->offset);
  2048. G_debug(2, "SQL: %s", stmt);
  2049. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  2050. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  2051. return -1;
  2052. }
  2053. }
  2054. /* update also centroids (stored as nodes) */
  2055. if (Area->centroid > 0) {
  2056. Line_i = Map->plus.Line[Area->centroid];
  2057. sprintf(stmt, "UPDATE \"%s\".node SET containing_face = %d "
  2058. "WHERE node_id = %d", pg_info->toposchema_name,
  2059. face[s], (int)Line_i->offset);
  2060. G_debug(2, "SQL: %s", stmt);
  2061. if(Vect__execute_pg(pg_info->conn, stmt) == -1) {
  2062. /* rollback transaction */
  2063. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  2064. return -1;
  2065. }
  2066. }
  2067. }
  2068. return 0;
  2069. }
  2070. /*!
  2071. \brief Add line to native and PostGIS topology
  2072. \param Map vector map
  2073. \param line feature id to remove from topo
  2074. \param type feature type
  2075. \param Points feature vertices
  2076. \return feature id
  2077. \return -1 on error
  2078. */
  2079. int add_line_to_topo_pg(struct Map_info *Map, off_t offset, int type,
  2080. const struct line_pnts *points)
  2081. {
  2082. int line, n_nodes;
  2083. struct Plus_head *plus;
  2084. plus = &(Map->plus);
  2085. Vect_reset_updated(Map);
  2086. line = V2__add_line_to_topo_nat(Map, offset, type, points, NULL,
  2087. -1, NULL);
  2088. /* insert new nodes into 'node' table */
  2089. n_nodes = Vect_get_num_updated_nodes(Map);
  2090. if (n_nodes > 0) {
  2091. int i, node;
  2092. double x, y, z;
  2093. if (!Points)
  2094. Points = Vect_new_line_struct();
  2095. for (i = 0; i < n_nodes; i++) {
  2096. node = Vect_get_updated_node(Map, i);
  2097. /* skip updated and deleted nodes */
  2098. if (node > 0 || plus->Node[abs(node)] == NULL)
  2099. continue;
  2100. G_debug(3, " new node: %d", node);
  2101. Vect_get_node_coor(Map, abs(node), &x, &y, &z);
  2102. Vect_reset_line(Points);
  2103. Vect_append_point(Points, x, y, z);
  2104. write_feature(Map, node, GV_POINT, (const struct line_pnts **) &Points, 1,
  2105. -1, NULL);
  2106. }
  2107. }
  2108. return line;
  2109. }
  2110. /*!
  2111. \brief Delete line from native and PostGIS topology
  2112. \todo Implement deleting nodes on request
  2113. \param Map vector map
  2114. \param line feature id to remove from topo
  2115. \param type feature type
  2116. \param Points feature vertices
  2117. \return 0 on success
  2118. \return -1 on error
  2119. */
  2120. int delete_line_from_topo_pg(struct Map_info *Map, int line, int type,
  2121. const struct line_pnts *Points)
  2122. {
  2123. Vect_reset_updated(Map);
  2124. if (0 != V2__delete_line_from_topo_nat(Map, line, type, Points, NULL))
  2125. return -1;
  2126. /* disabled: remove isolated nodes when closing the map
  2127. note: node id cannot be used as node_id
  2128. delete nodes from 'node' table
  2129. int n_nodes;
  2130. char stmt[DB_SQL_MAX];
  2131. struct Format_info_pg *pg_info;
  2132. struct Plus_head *plus;
  2133. pg_info = &(Map->fInfo.pg);
  2134. plus = &(Map->plus);
  2135. n_nodes = Vect_get_num_updated_nodes(Map);
  2136. if (n_nodes > 0) {
  2137. int i, node;
  2138. for (i = 0; i < n_nodes; i++) {
  2139. node = Vect_get_updated_node(Map, i);
  2140. if (node > 0 || plus->Node[abs(node)] != NULL)
  2141. continue;
  2142. node = abs(node);
  2143. G_debug(3, "delete node %d from 'node' table", node);
  2144. sprintf(stmt, "DELETE FROM \"%s\".\"node\" WHERE node_id = %d",
  2145. pg_info->toposchema_name, node);
  2146. if (Vect__execute_pg(pg_info->conn, stmt) == -1) {
  2147. G_warning(_("Unable to delete node %d"), node);
  2148. Vect__execute_pg(pg_info->conn, "ROLLBACK");
  2149. return -1;
  2150. }
  2151. }
  2152. }
  2153. */
  2154. return 0;
  2155. }
  2156. #endif