1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
|
/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_SQLITE_UTILS_HPP
#define MAPNIK_SQLITE_UTILS_HPP
// stl
#include <string>
#include <vector>
#include <algorithm>
// mapnik
#include <mapnik/debug.hpp>
#include <mapnik/utils.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/params.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/sql_utils.hpp>
#include <mapnik/util/fs.hpp>
// boost
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/algorithm/string.hpp>
// sqlite
extern "C" {
#include <sqlite3.h>
}
#include "sqlite_resultset.hpp"
#include "sqlite_prepared.hpp"
#include "sqlite_connection.hpp"
//==============================================================================
class sqlite_utils
{
public:
static bool needs_quoting(std::string const& name)
{
if (name.size() > 0)
{
const char first = name[0];
if (is_quote_char(first))
{
return false;
}
if ((first >= '0' && first <= '9') ||
(name.find("-") != std::string::npos)
)
{
return true;
}
}
return false;
}
static bool is_quote_char(const char z)
{
if (z == '"' || z == '\'' || z == '[' || z == '`')
{
return true;
}
return false;
}
static void dequote(std::string & z)
{
boost::algorithm::trim_if(z,boost::algorithm::is_any_of("[]'\"`"));
}
static std::string index_for_table(std::string const& table, std::string const& field)
{
std::string table_trimmed = table;
dequote(table_trimmed);
return "\"idx_" + table_trimmed + "_" + field + "\"";
}
static std::string index_for_db(std::string const& file)
{
//std::size_t idx = file.find_last_of(".");
//if(idx != std::string::npos) {
// return file.substr(0,idx) + ".index" + file.substr(idx);
//}
//else
//{
return file + ".index";
//}
}
static bool apply_spatial_filter(std::string & query,
mapnik::box2d<double> const& e,
std::string const& table,
std::string const& key_field,
std::string const& index_table,
std::string const& geometry_table,
std::string const& intersects_token)
{
std::ostringstream spatial_sql;
spatial_sql << std::setprecision(16);
spatial_sql << key_field << " IN (SELECT pkid FROM " << index_table;
spatial_sql << " WHERE xmax>=" << e.minx() << " AND xmin<=" << e.maxx() ;
spatial_sql << " AND ymax>=" << e.miny() << " AND ymin<=" << e.maxy() << ")";
if (boost::algorithm::ifind_first(query, intersects_token))
{
boost::algorithm::ireplace_all(query, intersects_token, spatial_sql.str());
return true;
}
// substitute first WHERE found if not using JOIN
// (because we can't know the WHERE is on the right table)
else if (boost::algorithm::ifind_first(query, "WHERE")
&& !boost::algorithm::ifind_first(query, "JOIN"))
{
std::string replace(" WHERE " + spatial_sql.str() + " AND ");
boost::algorithm::ireplace_first(query, "WHERE", replace);
return true;
}
// fallback to appending spatial filter at end of query
else if (boost::algorithm::ifind_first(query, geometry_table))
{
query = table + " WHERE " + spatial_sql.str();
return true;
}
return false;
}
static void get_tables(boost::shared_ptr<sqlite_connection> ds,
std::vector<std::string> & tables)
{
std::ostringstream sql;
// todo handle finding tables from attached db's
sql << " SELECT name FROM sqlite_master"
<< " WHERE type IN ('table','view')"
<< " AND name NOT LIKE 'sqlite_%'"
<< " AND name NOT LIKE 'idx_%'"
<< " AND name NOT LIKE '%geometry_columns%'"
<< " AND name NOT LIKE '%ref_sys%'"
<< " UNION ALL"
<< " SELECT name FROM sqlite_temp_master"
<< " WHERE type IN ('table','view')"
<< " ORDER BY 1";
sqlite3_stmt* stmt = 0;
const int rc = sqlite3_prepare_v2 (*(*ds), sql.str().c_str(), -1, &stmt, 0);
if (rc == SQLITE_OK)
{
boost::shared_ptr<sqlite_resultset> rs = boost::make_shared<sqlite_resultset>(stmt);
while (rs->is_valid() && rs->step_next())
{
const int type_oid = rs->column_type(0);
if (type_oid == SQLITE_TEXT)
{
const char * data = rs->column_text(0);
if (data)
{
tables.push_back(std::string(data));
}
}
}
}
}
static void query_extent(boost::shared_ptr<sqlite_resultset> rs,
mapnik::box2d<double>& extent)
{
bool first = true;
while (rs->is_valid() && rs->step_next())
{
int size;
const char* data = static_cast<const char*>(rs->column_blob(0, size));
if (data)
{
boost::ptr_vector<mapnik::geometry_type> paths;
if (mapnik::geometry_utils::from_wkb(paths, data, size, mapnik::wkbAuto))
{
for (unsigned i=0; i<paths.size(); ++i)
{
mapnik::box2d<double> const& bbox = paths[i].envelope();
if (bbox.valid())
{
if (first)
{
first = false;
extent = bbox;
}
else
{
extent.expand_to_include(bbox);
}
}
}
}
}
}
}
static bool create_spatial_index(std::string const& index_db,
std::string const& index_table,
boost::shared_ptr<sqlite_resultset> rs)
{
/* TODO
- speedups
- return early/recover from failure
- allow either in db or in separate
*/
if (!rs->is_valid())
return false;
#if SQLITE_VERSION_NUMBER >= 3005000
int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
#else
int flags;
#endif
bool existed = mapnik::util::exists(index_db);
boost::shared_ptr<sqlite_connection> ds = boost::make_shared<sqlite_connection>(index_db,flags);
bool one_success = false;
try
{
ds->execute("PRAGMA synchronous=OFF");
ds->execute("BEGIN IMMEDIATE TRANSACTION");
/*
ds->execute("PRAGMA journal_mode=WAL");
ds->execute("PRAGMA fullfsync=1");
ds->execute("PRAGMA locking_mode = EXCLUSIVE");
ds->execute("BEGIN EXCLUSIVE TRANSACTION");
*/
// first drop the index if it already exists
std::ostringstream spatial_index_drop_sql;
spatial_index_drop_sql << "DROP TABLE IF EXISTS " << index_table;
ds->execute(spatial_index_drop_sql.str());
// create the spatial index
std::ostringstream create_idx;
create_idx << "create virtual table "
<< index_table
<< " using rtree(pkid, xmin, xmax, ymin, ymax)";
// insert for prepared statement
std::ostringstream insert_idx;
insert_idx << "insert into "
<< index_table
<< " values (?,?,?,?,?)";
ds->execute(create_idx.str());
prepared_index_statement ps(ds,insert_idx.str());
while (rs->is_valid() && rs->step_next())
{
int size;
const char* data = (const char*) rs->column_blob(0, size);
if (data)
{
boost::ptr_vector<mapnik::geometry_type> paths;
mapnik::box2d<double> bbox;
if (mapnik::geometry_utils::from_wkb(paths, data, size, mapnik::wkbAuto))
{
for (unsigned i=0; i<paths.size(); ++i)
{
if (i==0)
{
bbox = paths[i].envelope();
}
else
{
bbox.expand_to_include(paths[i].envelope());
}
}
}
if (bbox.valid())
{
ps.bind(bbox);
const int type_oid = rs->column_type(1);
if (type_oid != SQLITE_INTEGER)
{
std::ostringstream error_msg;
error_msg << "Sqlite Plugin: invalid type for key field '"
<< rs->column_name(1) << "' when creating index '" << index_table
<< "' type was: " << type_oid << "";
throw mapnik::datasource_exception(error_msg.str());
}
const sqlite_int64 pkid = rs->column_integer64(1);
ps.bind(pkid);
}
else
{
std::ostringstream error_msg;
error_msg << "SQLite Plugin: encountered invalid bbox at '"
<< rs->column_name(1) << "' == " << rs->column_integer64(1);
throw mapnik::datasource_exception(error_msg.str());
}
ps.step_next();
one_success = true;
}
}
}
catch (mapnik::datasource_exception const& ex)
{
if (!existed)
{
try
{
mapnik::util::remove(index_db);
}
catch (...) {};
}
throw mapnik::datasource_exception(ex.what());
}
if (one_success)
{
ds->execute("COMMIT");
return true;
}
else if (!existed)
{
try
{
mapnik::util::remove(index_db);
}
catch (...) {};
}
return false;
}
typedef struct {
sqlite_int64 pkid;
mapnik::box2d<double> bbox;
} rtree_type;
static void build_tree(boost::shared_ptr<sqlite_resultset> rs,
std::vector<sqlite_utils::rtree_type> & rtree_list)
{
while (rs->is_valid() && rs->step_next())
{
int size;
const char* data = static_cast<const char*>(rs->column_blob(0, size));
if (data)
{
boost::ptr_vector<mapnik::geometry_type> paths;
if (mapnik::geometry_utils::from_wkb(paths, data, size, mapnik::wkbAuto))
{
for (unsigned i=0; i<paths.size(); ++i)
{
mapnik::box2d<double> const& bbox = paths[i].envelope();
if (bbox.valid())
{
const int type_oid = rs->column_type(1);
if (type_oid != SQLITE_INTEGER)
{
std::ostringstream error_msg;
error_msg << "Sqlite Plugin: invalid type for key field '"
<< rs->column_name(1) << "' when creating index "
<< "type was: " << type_oid << "";
throw mapnik::datasource_exception(error_msg.str());
}
const sqlite_int64 pkid = rs->column_integer64(1);
rtree_type entry = rtree_type();
entry.pkid = pkid;
entry.bbox = bbox;
rtree_list.push_back(entry);
}
else
{
std::ostringstream error_msg;
error_msg << "SQLite Plugin: encountered invalid bbox at '"
<< rs->column_name(1) << "' == " << rs->column_integer64(1);
throw mapnik::datasource_exception(error_msg.str());
}
}
}
}
}
}
static bool create_spatial_index2(std::string const& index_db,
std::string const& index_table,
std::vector<rtree_type> const& rtree_list)
{
#if SQLITE_VERSION_NUMBER >= 3005000
int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
#else
int flags;
#endif
bool existed = mapnik::util::exists(index_db);;
boost::shared_ptr<sqlite_connection> ds = boost::make_shared<sqlite_connection>(index_db,flags);
bool one_success = false;
try
{
ds->execute("PRAGMA synchronous=OFF");
ds->execute("BEGIN IMMEDIATE TRANSACTION");
// first drop the index if it already exists
std::ostringstream spatial_index_drop_sql;
spatial_index_drop_sql << "DROP TABLE IF EXISTS " << index_table;
ds->execute(spatial_index_drop_sql.str());
// create the spatial index
std::ostringstream create_idx;
create_idx << "create virtual table "
<< index_table
<< " using rtree(pkid, xmin, xmax, ymin, ymax)";
// insert for prepared statement
std::ostringstream insert_idx;
insert_idx << "insert into "
<< index_table
<< " values (?,?,?,?,?)";
ds->execute(create_idx.str());
prepared_index_statement ps(ds,insert_idx.str());
std::vector<rtree_type>::const_iterator it = rtree_list.begin();
std::vector<rtree_type>::const_iterator end = rtree_list.end();
for (; it != end; ++it)
{
ps.bind(it->bbox);
ps.bind(it->pkid);
ps.step_next();
one_success = true;
}
}
catch (mapnik::datasource_exception const& ex)
{
if (!existed)
{
try
{
mapnik::util::remove(index_db);
}
catch (...) {};
}
throw mapnik::datasource_exception(ex.what());
}
if (one_success)
{
ds->execute("COMMIT");
return true;
}
else if (!existed)
{
try
{
mapnik::util::remove(index_db);
}
catch (...) {};
}
return false;
}
static bool detect_extent(boost::shared_ptr<sqlite_connection> ds,
bool has_spatial_index,
mapnik::box2d<double> & extent,
std::string const& index_table,
std::string const& metadata,
std::string const& geometry_field,
std::string const& geometry_table,
std::string const& key_field,
std::string const& table
)
{
if (! metadata.empty())
{
std::ostringstream s;
s << "SELECT xmin, ymin, xmax, ymax FROM " << metadata;
s << " WHERE LOWER(f_table_name) = LOWER('" << geometry_table << "')";
boost::shared_ptr<sqlite_resultset> rs(ds->execute_query(s.str()));
if (rs->is_valid() && rs->step_next())
{
double xmin = rs->column_double(0);
double ymin = rs->column_double(1);
double xmax = rs->column_double(2);
double ymax = rs->column_double(3);
extent.init (xmin, ymin, xmax, ymax);
return true;
}
}
else if (has_spatial_index)
{
std::ostringstream s;
s << "SELECT MIN(xmin), MIN(ymin), MAX(xmax), MAX(ymax) FROM "
<< index_table;
boost::shared_ptr<sqlite_resultset> rs(ds->execute_query(s.str()));
if (rs->is_valid() && rs->step_next())
{
if (! rs->column_isnull(0))
{
double xmin = rs->column_double(0);
double ymin = rs->column_double(1);
double xmax = rs->column_double(2);
double ymax = rs->column_double(3);
extent.init (xmin, ymin, xmax, ymax);
return true;
}
}
}
else if (! key_field.empty())
{
std::ostringstream s;
s << "SELECT " << geometry_field << "," << key_field
<< " FROM (" << table << ")";
boost::shared_ptr<sqlite_resultset> rs(ds->execute_query(s.str()));
sqlite_utils::query_extent(rs,extent);
return true;
}
return false;
}
static bool has_rtree(std::string const& index_table,boost::shared_ptr<sqlite_connection> ds)
{
try
{
std::ostringstream s;
s << "SELECT pkid,xmin,xmax,ymin,ymax FROM " << index_table << " LIMIT 1";
boost::shared_ptr<sqlite_resultset> rs = ds->execute_query(s.str());
if (rs->is_valid() && rs->step_next())
{
return true;
}
}
catch (std::exception const& ex)
{
MAPNIK_LOG_DEBUG(sqlite) << "has_rtree returned:" << ex.what();
return false;
}
return false;
}
static bool detect_types_from_subquery(std::string const& query,
std::string & geometry_field,
mapnik::layer_descriptor & desc,
boost::shared_ptr<sqlite_connection> ds)
{
bool found = false;
boost::shared_ptr<sqlite_resultset> rs(ds->execute_query(query));
if (rs->is_valid() && rs->step_next())
{
for (int i = 0; i < rs->column_count(); ++i)
{
found = true;
const int type_oid = rs->column_type(i);
const char* fld_name = rs->column_name(i);
switch (type_oid)
{
case SQLITE_INTEGER:
desc.add_descriptor(mapnik::attribute_descriptor(fld_name, mapnik::Integer));
break;
case SQLITE_FLOAT:
desc.add_descriptor(mapnik::attribute_descriptor(fld_name, mapnik::Double));
break;
case SQLITE_TEXT:
desc.add_descriptor(mapnik::attribute_descriptor(fld_name, mapnik::String));
break;
case SQLITE_NULL:
// sqlite reports based on value, not actual column type unless
// PRAGMA table_info is used so here we assume the column is a string
// which is a lesser evil than altogether dropping the column
desc.add_descriptor(mapnik::attribute_descriptor(fld_name, mapnik::String));
break;
case SQLITE_BLOB:
if (geometry_field.empty()
&& (boost::algorithm::icontains(fld_name, "geom") ||
boost::algorithm::icontains(fld_name, "point") ||
boost::algorithm::icontains(fld_name, "linestring") ||
boost::algorithm::icontains(fld_name, "polygon")))
{
geometry_field = std::string(fld_name);
}
break;
default:
MAPNIK_LOG_DEBUG(sqlite) << "detect_types_from_subquery: unknown type_oid=" << type_oid;
break;
}
}
}
return found;
}
static bool table_info(std::string & key_field,
bool detected_types,
std::string & field,
std::string & table,
mapnik::layer_descriptor & desc,
boost::shared_ptr<sqlite_connection> ds)
{
// http://www.sqlite.org/pragma.html#pragma_table_info
// use pragma table_info to detect primary key
// and to detect types if no subquery is used or
// if the subquery-based type detection failed
std::ostringstream s;
s << "PRAGMA table_info(" << table << ")";
boost::shared_ptr<sqlite_resultset> rs(ds->execute_query(s.str()));
bool found_table = false;
bool found_pk = false;
while (rs->is_valid() && rs->step_next())
{
found_table = true;
const char* fld_name = rs->column_text(1);
std::string fld_type(rs->column_text(2));
sqlite_int64 fld_pk = rs->column_integer64(5);
std::transform(fld_type.begin(), fld_type.end(), fld_type.begin(), ::tolower);
// TODO - how to handle primary keys on multiple columns ?
if (key_field.empty() && ! found_pk && fld_pk != 0)
{
key_field = fld_name;
found_pk = true;
}
if (! detected_types)
{
// see 2.1 "Column Affinity" at http://www.sqlite.org/datatype3.html
// TODO - refactor this somehow ?
if (field.empty()
&& ((boost::algorithm::contains(fld_type, "geom") ||
boost::algorithm::contains(fld_type, "point") ||
boost::algorithm::contains(fld_type, "linestring") ||
boost::algorithm::contains(fld_type, "polygon"))
||
(boost::algorithm::icontains(fld_name, "geom") ||
boost::algorithm::icontains(fld_name, "point") ||
boost::algorithm::icontains(fld_name, "linestring") ||
boost::algorithm::icontains(fld_name, "polygon")))
)
{
field = std::string(fld_name);
}
else if (boost::algorithm::contains(fld_type, "int"))
{
desc.add_descriptor(mapnik::attribute_descriptor(fld_name, mapnik::Integer));
}
else if (boost::algorithm::contains(fld_type, "text") ||
boost::algorithm::contains(fld_type, "char") ||
boost::algorithm::contains(fld_type, "clob"))
{
desc.add_descriptor(mapnik::attribute_descriptor(fld_name, mapnik::String));
}
else if (boost::algorithm::contains(fld_type, "real") ||
boost::algorithm::contains(fld_type, "float") ||
boost::algorithm::contains(fld_type, "double"))
{
desc.add_descriptor(mapnik::attribute_descriptor(fld_name, mapnik::Double));
}
else if (boost::algorithm::contains(fld_type, "blob"))
{
if (! field.empty())
{
desc.add_descriptor(mapnik::attribute_descriptor(fld_name, mapnik::String));
}
}
else
{
// "Column Affinity" says default to "Numeric" but for now we pass..
//desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double));
#ifdef MAPNIK_LOG
// Do not fail when we specify geometry_field in XML file
if (field.empty())
{
MAPNIK_LOG_DEBUG(sqlite) << "Column '"
<< std::string(fld_name)
<< "' unhandled due to unknown type: "
<< fld_type;
}
#endif
}
}
}
return found_table;
}
};
#endif // MAPNIK_SQLITE_UTILS_HPP
|