statement.cpp 17.9 KB
Newer Older
1
//
msobczak's avatar
msobczak committed
2
// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton
3 4 5 6
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
msobczak's avatar
msobczak committed
7

8
#define SOCI_SOURCE
9 10
#include "statement.h"
#include "session.h"
msobczak's avatar
msobczak committed
11
#include "into-type.h"
12 13
#include "use-type.h"
#include "values.h"
msobczak's avatar
msobczak committed
14
#include <ctime>
15 16 17 18 19 20 21 22

#ifdef _MSC_VER
#pragma warning(disable:4355)
#endif

using namespace soci;
using namespace soci::details;

msobczak's avatar
msobczak committed
23
void statement::exchange(into_type_ptr const & i)
msobczak's avatar
msobczak committed
24 25
{
    impl_->exchange(i);
26 27
}

msobczak's avatar
msobczak committed
28
void statement::exchange(use_type_ptr const & u)
msobczak's avatar
msobczak committed
29 30
{
    impl_->exchange(u);
31 32
}

msobczak's avatar
msobczak committed
33
statement_impl::statement_impl(session & s)
34 35 36 37 38 39 40
    : session_(s), refCount_(1), row_(0),
      fetchSize_(1), initialFetchSize_(1),
      alreadyDescribed_(false)
{
    backEnd_ = s.make_statement_backend();
}

msobczak's avatar
msobczak committed
41
statement_impl::statement_impl(prepare_temp_type const & prep)
42
    : session_(prep.get_prepare_info()->session_),
43 44 45 46
      refCount_(1), row_(0), fetchSize_(1), alreadyDescribed_(false)
{
    backEnd_ = session_.make_statement_backend();

msobczak's avatar
msobczak committed
47
    ref_counted_prepare_info * prepInfo = prep.get_prepare_info();
48 49 50 51 52 53 54 55 56 57

    // take all bind/define info
    intos_.swap(prepInfo->intos_);
    uses_.swap(prepInfo->uses_);

    // allocate handle
    alloc();

    // prepare the statement
    query_ = prepInfo->get_query();
58 59 60 61 62 63 64 65 66
    try
    {
        prepare(query_);
    }
    catch(...)
    {
        clean_up();
        throw;
    }
67 68 69 70 71 72 73 74 75 76 77 78 79 80

    define_and_bind();
}

statement_impl::~statement_impl()
{
    clean_up();
}

void statement_impl::alloc()
{
    backEnd_->alloc();
}

msobczak's avatar
msobczak committed
81
void statement_impl::bind(values & values)
82
{
msobczak's avatar
msobczak committed
83
    std::size_t cnt = 0;
84 85 86

    try
    {
87
        for (std::vector<details::standard_use_type*>::iterator it =
88 89
            values.uses_.begin(); it != values.uses_.end(); ++it)
        {
msobczak's avatar
msobczak committed
90 91 92
            // only bind those variables which are:
            // - either named and actually referenced in the statement,
            // - or positional
93

94
            std::string const& useName = (*it)->get_name();
msobczak's avatar
msobczak committed
95
            if (useName.empty())
96
            {
msobczak's avatar
msobczak committed
97 98 99 100 101 102 103 104 105 106
                // positional use element

                int position = static_cast<int>(uses_.size());
                (*it)->bind(*this, position);
                uses_.push_back(*it);
                indicators_.push_back(values.indicators_[cnt]);
            }
            else
            {
                // named use element - check if it is used
107
                std::string const placeholder = ":" + useName;
msobczak's avatar
msobczak committed
108

109
                std::size_t const pos = query_.find(placeholder);
msobczak's avatar
msobczak committed
110
                if (pos != std::string::npos)
111
                {
112 113 114 115 116 117
                    // Retrieve next char after placeholder
                    // make sure we do not go out of range on the string
                    const char nextChar = (pos + placeholder.size()) < query_.size() ?
                                          query_[pos + placeholder.size()] : '\0';
                    
                    if (nextChar == ' ' || nextChar == ',' || nextChar == ';' ||
118 119
                        nextChar == '\0' || nextChar == ')' || 
                        nextChar == ':') // This last specific for PostgreSQL-style casts.
msobczak's avatar
msobczak committed
120 121 122 123 124 125 126 127 128 129
                    {
                        int position = static_cast<int>(uses_.size());
                        (*it)->bind(*this, position);
                        uses_.push_back(*it);
                        indicators_.push_back(values.indicators_[cnt]);
                    }
                    else
                    {
                        values.add_unused(*it, values.indicators_[cnt]);
                    }
130 131 132 133 134 135 136 137 138 139
                }
                else
                {
                    values.add_unused(*it, values.indicators_[cnt]);
                }
            }

            cnt++;
        }
    }
msobczak's avatar
msobczak committed
140
    catch (...)
141
    {
msobczak's avatar
msobczak committed
142
        for (std::size_t i = ++cnt; i != values.uses_.size(); ++i)
msobczak's avatar
msobczak committed
143
        {
msobczak's avatar
msobczak committed
144
            values.add_unused(values.uses_[i], values.indicators_[i]);
145
        }
msobczak's avatar
msobczak committed
146
        throw;
147 148 149
    }
}

msobczak's avatar
msobczak committed
150
void statement_impl::exchange(into_type_ptr const & i)
151 152 153 154 155
{
    intos_.push_back(i.get());
    i.release();
}

msobczak's avatar
msobczak committed
156
void statement_impl::exchange_for_row(into_type_ptr const & i)
157 158 159 160 161
{
    intosForRow_.push_back(i.get());
    i.release();
}

msobczak's avatar
msobczak committed
162
void statement_impl::exchange_for_rowset(into_type_ptr const & i)
163
{
msobczak's avatar
msobczak committed
164
    if (intos_.empty() == false)
165 166 167 168
    {
        throw soci_error("Explicit into elements not allowed with rowset.");
    }

169
    into_type_base* p = i.get();
170 171 172 173 174 175
    intos_.push_back(p);
    i.release();

    int definePosition = 1;
    p->define(*this, definePosition);
    definePositionForRow_ = definePosition;
msobczak's avatar
msobczak committed
176
}
177

msobczak's avatar
msobczak committed
178
void statement_impl::exchange(use_type_ptr const & u)
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
{
    uses_.push_back(u.get());
    u.release();
}

void statement_impl::clean_up()
{
    // deallocate all bind and define objects
    std::size_t const isize = intos_.size();
    for (std::size_t i = isize; i != 0; --i)
    {
        intos_[i - 1]->clean_up();
        delete intos_[i - 1];
        intos_.resize(i - 1);
    }

    std::size_t const ifrsize = intosForRow_.size();
    for (std::size_t i = ifrsize; i != 0; --i)
    {
        intosForRow_[i - 1]->clean_up();
        delete intosForRow_[i - 1];
        intosForRow_.resize(i - 1);
    }

    std::size_t const usize = uses_.size();
    for (std::size_t i = usize; i != 0; --i)
    {
        uses_[i - 1]->clean_up();
        delete uses_[i - 1];
        uses_.resize(i - 1);
    }

    std::size_t const indsize = indicators_.size();
    for (std::size_t i = 0; i != indsize; ++i)
    {
        delete indicators_[i];
        indicators_[i] = NULL;
    }

    if (backEnd_ != NULL)
    {
        backEnd_->clean_up();
        delete backEnd_;
        backEnd_ = NULL;
    }
}

msobczak's avatar
msobczak committed
226
void statement_impl::prepare(std::string const & query,
227
    statement_type eType)
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
{
    query_ = query;
    session_.log_query(query);

    backEnd_->prepare(query, eType);
}

void statement_impl::define_and_bind()
{
    int definePosition = 1;
    std::size_t const isize = intos_.size();
    for (std::size_t i = 0; i != isize; ++i)
    {
        intos_[i]->define(*this, definePosition);
    }

    // if there are some implicite into elements
    // injected by the row description process,
    // they should be defined in the later phase,
    // starting at the position where the above loop finished
    definePositionForRow_ = definePosition;

    int bindPosition = 1;
    std::size_t const usize = uses_.size();
    for (std::size_t i = 0; i != usize; ++i)
    {
        uses_[i]->bind(*this, bindPosition);
    }
}

void statement_impl::define_for_row()
{
    std::size_t const isize = intosForRow_.size();
    for (std::size_t i = 0; i != isize; ++i)
    {
        intosForRow_[i]->define(*this, definePositionForRow_);
    }
}

void statement_impl::undefine_and_bind()
{
    std::size_t const isize = intos_.size();
    for (std::size_t i = isize; i != 0; --i)
    {
        intos_[i - 1]->clean_up();
    }

    std::size_t const ifrsize = intosForRow_.size();
    for (std::size_t i = ifrsize; i != 0; --i)
    {
        intosForRow_[i - 1]->clean_up();
    }

    std::size_t const usize = uses_.size();
    for (std::size_t i = usize; i != 0; --i)
    {
        uses_[i - 1]->clean_up();
    }
}

bool statement_impl::execute(bool withDataExchange)
{
    initialFetchSize_ = intos_size();
291 292 293 294 295 296 297 298

    if (intos_.empty() == false && initialFetchSize_ == 0)
    {
        // this can happen only with into-vectors elements
        // and is not allowed when calling execute
        throw soci_error("Vectors of size 0 are not allowed.");
    }

299 300
    fetchSize_ = initialFetchSize_;

301 302 303 304 305
    // pre-use should be executed before inspecting the sizes of use
    // elements, as they can be resized in type conversion routines

    pre_use();

306
    std::size_t const bindSize = uses_size();
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

    if (bindSize > 1 && fetchSize_ > 1)
    {
        throw soci_error(
             "Bulk insert/update and bulk select not allowed in same query");
    }

    // looks like a hack and it is - row description should happen
    // *after* the use elements were completely prepared
    // and *before* the into elements are touched, so that the row
    // description process can inject more into elements for
    // implicit data exchange
    if (row_ != NULL && alreadyDescribed_ == false)
    {
        describe();
        define_for_row();
    }

    int num = 0;
    if (withDataExchange)
    {
        num = 1;

        pre_fetch();

        if (static_cast<int>(fetchSize_) > num)
        {
            num = static_cast<int>(fetchSize_);
        }
        if (static_cast<int>(bindSize) > num)
        {
            num = static_cast<int>(bindSize);
        }
    }

342
    statement_backend::exec_fetch_result res = backEnd_->execute(num);
343 344 345

    bool gotData = false;

346
    if (res == statement_backend::ef_success)
347 348 349 350 351 352 353 354 355 356 357 358
    {
        // the "success" means that the statement executed correctly
        // and for select statement this also means that some rows were read

        if (num > 0)
        {
            gotData = true;

            // ensure into vectors have correct size
            resize_intos(static_cast<std::size_t>(num));
        }
    }
359
    else // res == ef_no_data
360 361 362 363 364 365 366 367 368 369 370 371
    {
        // the "no data" means that the end-of-rowset condition was hit
        // but still some rows might have been read (the last bunch of rows)
        // it can also mean that the statement did not produce any results

        gotData = fetchSize_ > 1 ? resize_intos() : false;
    }

    if (num > 0)
    {
        post_fetch(gotData, false);
    }
msobczak's avatar
msobczak committed
372 373
    
    post_use(gotData);
374

375
    session_.set_got_data(gotData);
376 377 378
    return gotData;
}

379 380 381 382 383
long long statement_impl::get_affected_rows()
{
    return backEnd_->get_affected_rows();
}

384 385 386 387
bool statement_impl::fetch()
{
    if (fetchSize_ == 0)
    {
388
        truncate_intos();
389
        session_.set_got_data(false);
390 391 392 393 394 395
        return false;
    }

    bool gotData = false;

    // vectors might have been resized between fetches
396
    std::size_t const newFetchSize = intos_size();
397 398 399 400 401 402 403 404 405 406
    if (newFetchSize > initialFetchSize_)
    {
        // this is not allowed, because most likely caused reallocation
        // of the vector - this would require complete re-bind

        throw soci_error(
            "Increasing the size of the output vector is not supported.");
    }
    else if (newFetchSize == 0)
    {
407
        session_.set_got_data(false);
408 409 410 411 412 413 414 415
        return false;
    }
    else
    {
        // the output vector was downsized or remains the same as before
        fetchSize_ = newFetchSize;
    }

416
    statement_backend::exec_fetch_result const res = backEnd_->fetch(static_cast<int>(fetchSize_));
417
    if (res == statement_backend::ef_success)
418 419 420 421 422 423 424 425 426
    {
        // the "success" means that some number of rows was read
        // and that it is not yet the end-of-rowset (there are more rows)

        gotData = true;

        // ensure into vectors have correct size
        resize_intos(fetchSize_);
    }
427
    else // res == ef_no_data
428 429 430 431 432 433 434 435 436 437 438
    {
        // end-of-rowset condition

        if (fetchSize_ > 1)
        {
            // but still the last bunch of rows might have been read
            gotData = resize_intos();
            fetchSize_ = 0;
        }
        else
        {
439
            truncate_intos();
440 441 442 443 444
            gotData = false;
        }
    }

    post_fetch(gotData, true);
445
    session_.set_got_data(gotData);
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
    return gotData;
}

std::size_t statement_impl::intos_size()
{
    // this function does not need to take into account intosForRow_ elements,
    // since their sizes are always 1 (which is the same and the primary
    // into(row) element, which has injected them)

    std::size_t intos_size = 0;
    std::size_t const isize = intos_.size();
    for (std::size_t i = 0; i != isize; ++i)
    {
        if (i==0)
        {
            intos_size = intos_[i]->size();
        }
        else if (intos_size != intos_[i]->size())
        {
            std::ostringstream msg;
            msg << "Bind variable size mismatch (into["
                << static_cast<unsigned long>(i) << "] has size "
                << static_cast<unsigned long>(intos_[i]->size())
                << ", into[0] has size "
                << static_cast<unsigned long>(intos_size);
            throw soci_error(msg.str());
        }
    }
    return intos_size;
}

std::size_t statement_impl::uses_size()
{
    std::size_t usesSize = 0;
    std::size_t const usize = uses_.size();
    for (std::size_t i = 0; i != usize; ++i)
    {
        if (i==0)
        {
            usesSize = uses_[i]->size();
            if (usesSize == 0)
            {
                 // this can happen only for vectors
                 throw soci_error("Vectors of size 0 are not allowed.");
            }
        }
        else if (usesSize != uses_[i]->size())
        {
            std::ostringstream msg;
            msg << "Bind variable size mismatch (use["
                << static_cast<unsigned long>(i) << "] has size "
                << static_cast<unsigned long>(uses_[i]->size())
                << ", use[0] has size "
                << static_cast<unsigned long>(usesSize);
            throw soci_error(msg.str());
        }
    }
    return usesSize;
}

bool statement_impl::resize_intos(std::size_t upperBound)
{
    // this function does not need to take into account the intosForRow_
    // elements, since they are never used for bulk operations

Mateusz Loskot's avatar
Mateusz Loskot committed
511 512 513 514 515
    int rows = backEnd_->get_number_of_rows();
    if (rows < 0)
    {
        rows = 0;
    }
Mateusz Loskot's avatar
Mateusz Loskot committed
516
    if (upperBound != 0 && upperBound < static_cast<std::size_t>(rows))
517
    {
Mateusz Loskot's avatar
Mateusz Loskot committed
518
        rows = static_cast<int>(upperBound);
519 520 521 522 523
    }

    std::size_t const isize = intos_.size();
    for (std::size_t i = 0; i != isize; ++i)
    {
524
        intos_[i]->resize((std::size_t)rows);
525 526 527 528 529
    }

    return rows > 0 ? true : false;
}

530 531 532 533 534 535 536 537 538
void statement_impl::truncate_intos()
{
    std::size_t const isize = intos_.size();
    for (std::size_t i = 0; i != isize; ++i)
    {
        intos_[i]->resize(0);
    }
}

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
void statement_impl::pre_fetch()
{
    std::size_t const isize = intos_.size();
    for (std::size_t i = 0; i != isize; ++i)
    {
        intos_[i]->pre_fetch();
    }

    std::size_t const ifrsize = intosForRow_.size();
    for (std::size_t i = 0; i != ifrsize; ++i)
    {
        intosForRow_[i]->pre_fetch();
    }
}

void statement_impl::pre_use()
{
    std::size_t const usize = uses_.size();
    for (std::size_t i = 0; i != usize; ++i)
    {
        uses_[i]->pre_use();
    }
}

void statement_impl::post_fetch(bool gotData, bool calledFromFetch)
{
    // first iterate over intosForRow_ elements, since the Row element
    // (which is among the intos_ elements) might depend on the
    // values of those implicitly injected elements

    std::size_t const ifrsize = intosForRow_.size();
    for (std::size_t i = 0; i != ifrsize; ++i)
    {
        intosForRow_[i]->post_fetch(gotData, calledFromFetch);
    }

    std::size_t const isize = intos_.size();
    for (std::size_t i = 0; i != isize; ++i)
    {
        intos_[i]->post_fetch(gotData, calledFromFetch);
    }
}

void statement_impl::post_use(bool gotData)
msobczak's avatar
msobczak committed
583
{
584 585 586 587 588 589 590 591 592 593 594 595 596
    // iterate in reverse order here in case the first item
    // is an UseType<Values> (since it depends on the other UseTypes)
    for (std::size_t i = uses_.size(); i != 0; --i)
    {
        uses_[i-1]->post_use(gotData);
    }
}

namespace soci
{
namespace details
{

597
// Map data_types to stock types for dynamic result set support
598 599

template<>
600
void statement_impl::bind_into<dt_string>()
601 602 603 604 605
{
    into_row<std::string>();
}

template<>
606
void statement_impl::bind_into<dt_double>()
607 608 609 610 611
{
    into_row<double>();
}

template<>
612
void statement_impl::bind_into<dt_integer>()
613 614 615 616
{
    into_row<int>();
}

msobczak's avatar
msobczak committed
617
template<>
618
void statement_impl::bind_into<dt_long_long>()
msobczak's avatar
msobczak committed
619 620 621 622
{
    into_row<long long>();
}

623 624 625 626 627 628
template<>
void statement_impl::bind_into<dt_unsigned_long_long>()
{
    into_row<unsigned long long>();
}

629
template<>
630
void statement_impl::bind_into<dt_date>()
631 632 633 634 635 636
{
    into_row<std::tm>();
}

void statement_impl::describe()
{
637 638
    row_->clean_up();

639
    int const numcols = backEnd_->prepare_for_describe();
640 641
    for (int i = 1; i <= numcols; ++i)
    {
642
        data_type dtype;
643 644 645 646 647 648 649
        std::string columnName;

        backEnd_->describe_column(i, dtype, columnName);

        column_properties props;
        props.set_name(columnName);
        props.set_data_type(dtype);
650

msobczak's avatar
msobczak committed
651
        switch (dtype)
652
        {
653 654
        case dt_string:
            bind_into<dt_string>();
655
            break;
656 657
        case dt_double:
            bind_into<dt_double>();
658
            break;
659 660
        case dt_integer:
            bind_into<dt_integer>();
661
            break;
662 663
        case dt_long_long:
            bind_into<dt_long_long>();
msobczak's avatar
msobczak committed
664
            break;
665 666 667
        case dt_unsigned_long_long:
            bind_into<dt_unsigned_long_long>();
            break;
668 669
        case dt_date:
            bind_into<dt_date>();
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
            break;
        default:
            std::ostringstream msg;
            msg << "db column type " << dtype
                <<" not supported for dynamic selects"<<std::endl;
            throw soci_error(msg.str());
        }
        row_->add_properties(props);
    }

    alreadyDescribed_ = true;
}

} // namespace details
} // namespace soci

msobczak's avatar
msobczak committed
686
void statement_impl::set_row(row * r)
687 688 689 690 691 692 693 694
{
    if (row_ != NULL)
    {
        throw soci_error(
            "Only one Row element allowed in a single statement.");
    }

    row_ = r;
695
    row_->uppercase_column_names(session_.get_uppercase_column_names());
696 697
}

msobczak's avatar
msobczak committed
698
std::string statement_impl::rewrite_for_procedure_call(std::string const & query)
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
{
    return backEnd_->rewrite_for_procedure_call(query);
}

void statement_impl::inc_ref()
{
    ++refCount_;
}

void statement_impl::dec_ref()
{
    if (--refCount_ == 0)
    {
        delete this;
    }
}

standard_into_type_backend *
statement_impl::make_into_type_backend()
{
    return backEnd_->make_into_type_backend();
}

standard_use_type_backend *
statement_impl::make_use_type_backend()
{
    return backEnd_->make_use_type_backend();
}

vector_into_type_backend *
statement_impl::make_vector_into_type_backend()
{
    return backEnd_->make_vector_into_type_backend();
}

vector_use_type_backend *
statement_impl::make_vector_use_type_backend()
{
    return backEnd_->make_vector_use_type_backend();
}