write_pg.c 85 KB

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