write_pg.c 86 KB

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