x03_b_soci_example.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // Boost.Geometry (aka GGL, Generic Geometry Library)
  2. //
  3. // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
  4. // Use, modification and distribution is subject to the Boost Software License,
  5. // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  6. // http://www.boost.org/LICENSE_1_0.txt)
  7. // SOCI example
  8. // b: using WKT to retrieve points
  9. // To build and run this example, see comments in example a
  10. #include <soci.h>
  11. #include <soci-postgresql.h>
  12. #include <boost/algorithm/string.hpp>
  13. #include <boost/optional.hpp>
  14. #include <boost/timer.hpp>
  15. #include <boost/random.hpp>
  16. #include <boost/tuple/tuple.hpp>
  17. #include <iostream>
  18. #include <istream>
  19. #include <ostream>
  20. #include <sstream>
  21. #include <string>
  22. #include <exception>
  23. #include <boost/geometry/geometry.hpp>
  24. #include <boost/geometry/geometries/geometries.hpp>
  25. #include <boost/geometry/io/wkt/wkt.hpp>
  26. struct city
  27. {
  28. boost::geometry::model::point<float, 2, boost::geometry::cs::geographic<boost::geometry::degree> > location;
  29. std::string name;
  30. };
  31. namespace soci
  32. {
  33. template <>
  34. struct type_conversion<city>
  35. {
  36. typedef soci::values base_type;
  37. static void from_base(const base_type& v, soci::indicator ind, city& value)
  38. {
  39. try
  40. {
  41. value.name = v.get<std::string>("name");
  42. boost::geometry::read_wkt(v.get<std::string>("wkt"), value.location);
  43. }
  44. catch(const std::exception& e)
  45. {
  46. std::cout << e.what() << std::endl;
  47. }
  48. }
  49. static void to_base(const city& value, base_type& v, soci::indicator& ind)
  50. {
  51. v.set("name", value.name);
  52. std::ostringstream out;
  53. out << boost::geometry::wkt(value.location);
  54. v.set("wkt", out.str());
  55. ind = i_ok;
  56. }
  57. };
  58. }
  59. int main()
  60. {
  61. try
  62. {
  63. soci::session sql(soci::postgresql, "dbname=ggl user=ggl password=ggl");
  64. typedef std::vector<city> V;
  65. soci::rowset<city> rows = sql.prepare << "select name,astext(location) as wkt from cities";
  66. V vec;
  67. std::copy(rows.begin(), rows.end(), std::back_inserter(vec));
  68. for (V::const_iterator it = vec.begin(); it != vec.end(); ++it)
  69. {
  70. static const double sqrkm = 1000.0 * 1000.0;
  71. std::cout << it->name
  72. << " " << boost::geometry::dsv(it->location)
  73. //<< " " << boost::geometry::area(it->shape) / sqrkm << " km2"
  74. << std::endl;
  75. }
  76. }
  77. catch (std::exception const &e)
  78. {
  79. std::cerr << "Error: " << e.what() << '\n';
  80. }
  81. return 0;
  82. }