1
0
mirror of https://github.com/VCMP-SqMod/SqMod.git synced 2025-06-25 03:27:12 +02:00

Major plugin refactor and cleanup.

Switched to POCO library for unified platform/library interface.
Deprecated the external module API. It was creating more problems than solving.
Removed most built-in libraries in favor of system libraries for easier maintenance.
Cleaned and secured code with help from static analyzers.
This commit is contained in:
Sandu Liviu Catalin
2021-01-30 08:51:39 +02:00
parent e0e34b4030
commit 4a6bfc086c
6219 changed files with 1209835 additions and 454916 deletions

View File

@ -0,0 +1,373 @@
//
// AbstractBinder.h
//
// Library: Data
// Package: DataCore
// Module: AbstractBinder
//
// Definition of the AbstractBinder class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_AbstractBinder_INCLUDED
#define Data_AbstractBinder_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/Date.h"
#include "Poco/Data/Time.h"
#include "Poco/Data/LOB.h"
#include "Poco/DateTime.h"
#include "Poco/Nullable.h"
#include "Poco/Any.h"
#include "Poco/Dynamic/Var.h"
#include "Poco/UTFString.h"
#include <vector>
#include <deque>
#include <list>
#include <cstddef>
namespace Poco {
namespace Data {
using NullData = NullType;
namespace Keywords {
static const NullData null = NULL_GENERIC;
} // namespace Keywords
class Data_API AbstractBinder
/// Interface for Binding data types to placeholders.
{
public:
using Ptr = SharedPtr<AbstractBinder>;
enum Direction
/// Binding direction for a parameter.
{
PD_IN,
PD_OUT,
PD_IN_OUT
};
AbstractBinder();
/// Creates the AbstractBinder.
virtual ~AbstractBinder();
/// Destroys the AbstractBinder.
virtual void bind(std::size_t pos, const Poco::Int8& val, Direction dir = PD_IN) = 0;
/// Binds an Int8.
virtual void bind(std::size_t pos, const std::vector<Poco::Int8>& val, Direction dir = PD_IN);
/// Binds an Int8 vector.
virtual void bind(std::size_t pos, const std::deque<Poco::Int8>& val, Direction dir = PD_IN);
/// Binds an Int8 deque.
virtual void bind(std::size_t pos, const std::list<Poco::Int8>& val, Direction dir = PD_IN);
/// Binds an Int8 list.
virtual void bind(std::size_t pos, const Poco::UInt8& val, Direction dir = PD_IN) = 0;
/// Binds an UInt8.
virtual void bind(std::size_t pos, const std::vector<Poco::UInt8>& val, Direction dir = PD_IN);
/// Binds an UInt8 vector.
virtual void bind(std::size_t pos, const std::deque<Poco::UInt8>& val, Direction dir = PD_IN);
/// Binds an UInt8 deque.
virtual void bind(std::size_t pos, const std::list<Poco::UInt8>& val, Direction dir = PD_IN);
/// Binds an UInt8 list.
virtual void bind(std::size_t pos, const Poco::Int16& val, Direction dir = PD_IN) = 0;
/// Binds an Int16.
virtual void bind(std::size_t pos, const std::vector<Poco::Int16>& val, Direction dir = PD_IN);
/// Binds an Int16 vector.
virtual void bind(std::size_t pos, const std::deque<Poco::Int16>& val, Direction dir = PD_IN);
/// Binds an Int16 deque.
virtual void bind(std::size_t pos, const std::list<Poco::Int16>& val, Direction dir = PD_IN);
/// Binds an Int16 list.
virtual void bind(std::size_t pos, const Poco::UInt16& val, Direction dir = PD_IN) = 0;
/// Binds an UInt16.
virtual void bind(std::size_t pos, const std::vector<Poco::UInt16>& val, Direction dir = PD_IN);
/// Binds an UInt16 vector.
virtual void bind(std::size_t pos, const std::deque<Poco::UInt16>& val, Direction dir = PD_IN);
/// Binds an UInt16 deque.
virtual void bind(std::size_t pos, const std::list<Poco::UInt16>& val, Direction dir = PD_IN);
/// Binds an UInt16 list.
virtual void bind(std::size_t pos, const Poco::Int32& val, Direction dir = PD_IN) = 0;
/// Binds an Int32.
virtual void bind(std::size_t pos, const std::vector<Poco::Int32>& val, Direction dir = PD_IN);
/// Binds an Int32 vector.
virtual void bind(std::size_t pos, const std::deque<Poco::Int32>& val, Direction dir = PD_IN);
/// Binds an Int32 deque.
virtual void bind(std::size_t pos, const std::list<Poco::Int32>& val, Direction dir = PD_IN);
/// Binds an Int32 list.
virtual void bind(std::size_t pos, const Poco::UInt32& val, Direction dir = PD_IN) = 0;
/// Binds an UInt32.
virtual void bind(std::size_t pos, const std::vector<Poco::UInt32>& val, Direction dir = PD_IN);
/// Binds an UInt32 vector.
virtual void bind(std::size_t pos, const std::deque<Poco::UInt32>& val, Direction dir = PD_IN);
/// Binds an UInt32 deque.
virtual void bind(std::size_t pos, const std::list<Poco::UInt32>& val, Direction dir = PD_IN);
/// Binds an UInt32 list.
virtual void bind(std::size_t pos, const Poco::Int64& val, Direction dir = PD_IN) = 0;
/// Binds an Int64.
virtual void bind(std::size_t pos, const std::vector<Poco::Int64>& val, Direction dir = PD_IN);
/// Binds an Int64 vector.
virtual void bind(std::size_t pos, const std::deque<Poco::Int64>& val, Direction dir = PD_IN);
/// Binds an Int64 deque.
virtual void bind(std::size_t pos, const std::list<Poco::Int64>& val, Direction dir = PD_IN);
/// Binds an Int64 list.
virtual void bind(std::size_t pos, const Poco::UInt64& val, Direction dir = PD_IN) = 0;
/// Binds an UInt64.
virtual void bind(std::size_t pos, const std::vector<Poco::UInt64>& val, Direction dir = PD_IN);
/// Binds an UInt64 vector.
virtual void bind(std::size_t pos, const std::deque<Poco::UInt64>& val, Direction dir = PD_IN);
/// Binds an UInt64 deque.
virtual void bind(std::size_t pos, const std::list<Poco::UInt64>& val, Direction dir = PD_IN);
/// Binds an UInt64 list.
#ifndef POCO_INT64_IS_LONG
virtual void bind(std::size_t pos, const long& val, Direction dir = PD_IN) = 0;
/// Binds a long.
virtual void bind(std::size_t pos, const unsigned long& val, Direction dir = PD_IN) = 0;
/// Binds an unsiged long.
virtual void bind(std::size_t pos, const std::vector<long>& val, Direction dir = PD_IN);
/// Binds a long vector.
virtual void bind(std::size_t pos, const std::deque<long>& val, Direction dir = PD_IN);
/// Binds a long deque.
virtual void bind(std::size_t pos, const std::list<long>& val, Direction dir = PD_IN);
/// Binds a long list.
#endif
virtual void bind(std::size_t pos, const bool& val, Direction dir = PD_IN) = 0;
/// Binds a boolean.
virtual void bind(std::size_t pos, const std::vector<bool>& val, Direction dir = PD_IN);
/// Binds a boolean vector.
virtual void bind(std::size_t pos, const std::deque<bool>& val, Direction dir = PD_IN);
/// Binds a boolean deque.
virtual void bind(std::size_t pos, const std::list<bool>& val, Direction dir = PD_IN);
/// Binds a boolean list.
virtual void bind(std::size_t pos, const float& val, Direction dir = PD_IN) = 0;
/// Binds a float.
virtual void bind(std::size_t pos, const std::vector<float>& val, Direction dir = PD_IN);
/// Binds a float vector.
virtual void bind(std::size_t pos, const std::deque<float>& val, Direction dir = PD_IN);
/// Binds a float deque.
virtual void bind(std::size_t pos, const std::list<float>& val, Direction dir = PD_IN);
/// Binds a float list.
virtual void bind(std::size_t pos, const double& val, Direction dir = PD_IN) = 0;
/// Binds a double.
virtual void bind(std::size_t pos, const std::vector<double>& val, Direction dir = PD_IN);
/// Binds a double vector.
virtual void bind(std::size_t pos, const std::deque<double>& val, Direction dir = PD_IN);
/// Binds a double deque.
virtual void bind(std::size_t pos, const std::list<double>& val, Direction dir = PD_IN);
/// Binds a double list.
virtual void bind(std::size_t pos, const char& val, Direction dir = PD_IN) = 0;
/// Binds a single character.
virtual void bind(std::size_t pos, const std::vector<char>& val, Direction dir = PD_IN);
/// Binds a character vector.
virtual void bind(std::size_t pos, const std::deque<char>& val, Direction dir = PD_IN);
/// Binds a character deque.
virtual void bind(std::size_t pos, const std::list<char>& val, Direction dir = PD_IN);
/// Binds a character list.
virtual void bind(std::size_t pos, const char* const& pVal, Direction dir = PD_IN) = 0;
/// Binds a const char ptr.
virtual void bind(std::size_t pos, const std::string& val, Direction dir = PD_IN) = 0;
/// Binds a string.
virtual void bind(std::size_t pos, const std::vector<std::string>& val, Direction dir = PD_IN);
/// Binds a string vector.
virtual void bind(std::size_t pos, const std::deque<std::string>& val, Direction dir = PD_IN);
/// Binds a string deque.
virtual void bind(std::size_t pos, const std::list<std::string>& val, Direction dir = PD_IN);
/// Binds a string list.
virtual void bind(std::size_t pos, const UTF16String& val, Direction dir = PD_IN);
/// Binds a UTF-16 Unicode string.
virtual void bind(std::size_t pos, const std::vector<UTF16String>& val, Direction dir = PD_IN);
/// Binds a UTF-16 Unicode string vector.
virtual void bind(std::size_t pos, const std::deque<UTF16String>& val, Direction dir = PD_IN);
/// Binds a UTF-16 Unicode string deque.
virtual void bind(std::size_t pos, const std::list<UTF16String>& val, Direction dir = PD_IN);
/// Binds a UTF-16 Unicode string list.
virtual void bind(std::size_t pos, const BLOB& val, Direction dir = PD_IN) = 0;
/// Binds a BLOB.
virtual void bind(std::size_t pos, const CLOB& val, Direction dir = PD_IN) = 0;
/// Binds a CLOB.
virtual void bind(std::size_t pos, const std::vector<BLOB>& val, Direction dir = PD_IN);
/// Binds a BLOB vector.
virtual void bind(std::size_t pos, const std::deque<BLOB>& val, Direction dir = PD_IN);
/// Binds a BLOB deque.
virtual void bind(std::size_t pos, const std::list<BLOB>& val, Direction dir = PD_IN);
/// Binds a BLOB list.
virtual void bind(std::size_t pos, const std::vector<CLOB>& val, Direction dir = PD_IN);
/// Binds a CLOB vector.
virtual void bind(std::size_t pos, const std::deque<CLOB>& val, Direction dir = PD_IN);
/// Binds a CLOB deque.
virtual void bind(std::size_t pos, const std::list<CLOB>& val, Direction dir = PD_IN);
/// Binds a CLOB list.
virtual void bind(std::size_t pos, const DateTime& val, Direction dir = PD_IN) = 0;
/// Binds a DateTime.
virtual void bind(std::size_t pos, const std::vector<DateTime>& val, Direction dir = PD_IN);
/// Binds a DateTime vector.
virtual void bind(std::size_t pos, const std::deque<DateTime>& val, Direction dir = PD_IN);
/// Binds a DateTime deque.
virtual void bind(std::size_t pos, const std::list<DateTime>& val, Direction dir = PD_IN);
/// Binds a DateTime list.
virtual void bind(std::size_t pos, const Date& val, Direction dir = PD_IN) = 0;
/// Binds a Date.
virtual void bind(std::size_t pos, const std::vector<Date>& val, Direction dir = PD_IN);
/// Binds a Date vector.
virtual void bind(std::size_t pos, const std::deque<Date>& val, Direction dir = PD_IN);
/// Binds a Date deque.
virtual void bind(std::size_t pos, const std::list<Date>& val, Direction dir = PD_IN);
/// Binds a Date list.
virtual void bind(std::size_t pos, const Time& val, Direction dir = PD_IN) = 0;
/// Binds a Time.
virtual void bind(std::size_t pos, const std::vector<Time>& val, Direction dir = PD_IN);
/// Binds a Time vector.
virtual void bind(std::size_t pos, const std::deque<Time>& val, Direction dir = PD_IN);
/// Binds a Time deque.
virtual void bind(std::size_t pos, const std::list<Time>& val, Direction dir = PD_IN);
/// Binds a Time list.
virtual void bind(std::size_t pos, const NullData& val, Direction dir = PD_IN) = 0;
/// Binds a null.
virtual void bind(std::size_t pos, const std::vector<NullData>& val, Direction dir = PD_IN);
/// Binds a null vector.
virtual void bind(std::size_t pos, const std::deque<NullData>& val, Direction dir = PD_IN);
/// Binds a null deque.
virtual void bind(std::size_t pos, const std::list<NullData>& val, Direction dir = PD_IN);
/// Binds a null list.
void bind(std::size_t pos, const Any& val, Direction dir = PD_IN);
/// Binds an Any.
void bind(std::size_t pos, const Poco::Dynamic::Var& val, Direction dir = PD_IN);
/// Binds a Var.
virtual void reset();
/// Resets a binder. No-op by default. Implement for binders that cache data.
static bool isOutBound(Direction dir);
/// Returns true if direction is out bound;
static bool isInBound(Direction dir);
/// Returns true if direction is in bound;
};
//
// inlines
//
inline void AbstractBinder::reset()
{
//no-op
}
inline bool AbstractBinder::isOutBound(Direction dir)
{
return PD_OUT == dir || PD_IN_OUT == dir;
}
inline bool AbstractBinder::isInBound(Direction dir)
{
return PD_IN == dir || PD_IN_OUT == dir;
}
} } // namespace Poco::Data
#endif // Data_AbstractBinder_INCLUDED

View File

@ -0,0 +1,144 @@
//
// AbstractBinding.h
//
// Library: Data
// Package: DataCore
// Module: AbstractBinding
//
// Definition of the AbstractBinding class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_AbstractBinding_INCLUDED
#define Data_AbstractBinding_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/AbstractBinder.h"
#include "Poco/Any.h"
#include "Poco/RefCountedObject.h"
#include "Poco/AutoPtr.h"
#include <vector>
#include <list>
#include <deque>
#include <cstddef>
namespace Poco {
namespace Data {
class Data_API AbstractBinding
/// AbstractBinding connects a value with a placeholder via an AbstractBinder interface.
{
public:
using Ptr = SharedPtr<AbstractBinding>;
using BinderPtr = AbstractBinder::Ptr;
enum Direction
{
PD_IN = AbstractBinder::PD_IN,
PD_OUT = AbstractBinder::PD_OUT,
PD_IN_OUT = AbstractBinder::PD_IN_OUT
};
AbstractBinding(const std::string& name = "", Direction direction = PD_IN, Poco::UInt32 bulkSize = 0);
/// Creates the AbstractBinding.
virtual ~AbstractBinding();
/// Destroys the AbstractBinding.
void setBinder(BinderPtr pBinder);
/// Sets the object used for binding; object does NOT take ownership of the pointer.
BinderPtr getBinder() const;
/// Returns the AbstractBinder used for binding data.
virtual std::size_t numOfColumnsHandled() const = 0;
/// Returns the number of columns that the binding handles.
///
/// The trivial case will be one single column but when
/// complex types are used this value can be larger than one.
virtual std::size_t numOfRowsHandled() const = 0;
/// Returns the number of rows that the binding handles.
///
/// The trivial case will be one single row but
/// for collection data types it can be larger.
virtual bool canBind() const = 0;
/// Returns true if we have enough data to bind
virtual void bind(std::size_t pos) = 0;
/// Binds a value to the given column position
virtual void reset() = 0;
/// Allows a binding to be reused.
AbstractBinder::Direction getDirection() const;
/// Returns the binding direction.
const std::string& name() const;
/// Returns the name for this binding.
bool isBulk() const;
/// Returns true if extraction is bulk.
Poco::UInt32 bulkSize() const;
/// Returns the size of the bulk binding.
private:
BinderPtr _pBinder;
std::string _name;
Direction _direction;
Poco::UInt32 _bulkSize;
};
using AbstractBindingVec = std::vector<AbstractBinding::Ptr>;
using AbstractBindingDeq = std::deque<AbstractBinding::Ptr>;
using AbstractBindingLst = std::list<AbstractBinding::Ptr>;
//
// inlines
//
inline AbstractBinder::Ptr AbstractBinding::getBinder() const
{
return _pBinder;
}
inline const std::string& AbstractBinding::name() const
{
return _name;
}
inline AbstractBinder::Direction AbstractBinding::getDirection() const
{
return (AbstractBinder::Direction) _direction;
}
inline bool AbstractBinding::isBulk() const
{
return _bulkSize > 0;
}
inline Poco::UInt32 AbstractBinding::bulkSize() const
{
return _bulkSize;
}
} } // namespace Poco::Data
#endif // Data_AbstractBinding_INCLUDED

View File

@ -0,0 +1,278 @@
//
// AbstractExtraction.h
//
// Library: Data
// Package: DataCore
// Module: AbstractExtraction
//
// Definition of the AbstractExtraction class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_AbstractExtraction_INCLUDED
#define Data_AbstractExtraction_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/AbstractExtractor.h"
#include "Poco/Data/AbstractPreparation.h"
#include "Poco/Data/Limit.h"
#include "Poco/RefCountedObject.h"
#include "Poco/UTFString.h"
#include "Poco/AutoPtr.h"
#include <vector>
#include <deque>
#include <list>
#include <cstddef>
namespace Poco {
namespace Data {
class AbstractPreparator;
class Data_API AbstractExtraction
/// AbstractExtraction is the interface class that connects output positions to concrete values
/// retrieved via an AbstractExtractor.
{
public:
using Ptr = SharedPtr<AbstractExtraction>;
using ExtractorPtr = SharedPtr<AbstractExtractor>;
using PreparatorPtr = SharedPtr<AbstractPreparator>;
AbstractExtraction(Poco::UInt32 limit = Limit::LIMIT_UNLIMITED,
Poco::UInt32 position = 0, bool bulk = false);
/// Creates the AbstractExtraction. A limit value equal to EXTRACT_UNLIMITED (0xffffffffu)
/// means that we extract as much data as possible during one execute.
/// Otherwise the limit value is used to partition data extracting to a limited amount of rows.
virtual ~AbstractExtraction();
/// Destroys the AbstractExtraction.
void setExtractor(ExtractorPtr pExtractor);
/// Sets the class used for extracting the data. Does not take ownership of the pointer.
ExtractorPtr getExtractor() const;
/// Retrieves the extractor object
Poco::UInt32 position() const;
/// Returns the extraction position.
virtual std::size_t numOfColumnsHandled() const = 0;
/// Returns the number of columns that the extraction handles.
///
/// The trivial case will be one single column but when
/// complex types are used this value can be larger than one.
virtual std::size_t numOfRowsHandled() const = 0;
/// Returns the number of rows that the extraction handles.
///
/// The trivial case will be one single row but
/// for collection data types (ie vector) it can be larger.
virtual std::size_t numOfRowsAllowed() const = 0;
/// Returns the upper limit on number of rows that the extraction will handle.
virtual std::size_t extract(std::size_t pos) = 0;
/// Extracts a value from the param, starting at the given column position.
/// Returns the number of rows extracted.
virtual void reset();
/// Resets the extractor so that it can be re-used.
/// Does nothing in this implementation.
/// Implementations should override it for different behavior.
virtual bool canExtract() const;
/// Returns true. Implementations should override it for different behavior.
virtual AbstractPreparation::Ptr createPreparation(PreparatorPtr& pPrep, std::size_t pos) = 0;
/// Creates and returns shared pointer to Preparation object for the extracting object.
void setLimit(Poco::UInt32 limit);
/// Sets the limit.
Poco::UInt32 getLimit() const;
/// Gets the limit.
virtual bool isNull(std::size_t row) const;
/// In implementations, this function returns true if value at row is null,
/// false otherwise.
/// Normal behavior is to replace nulls with default values.
/// However, extraction implementations may remember the underlying database
/// null values and be able to later provide information about them.
/// Here, this function throws NotImplementedException.
bool isBulk() const;
/// Returns true if this is bulk extraction.
void setEmptyStringIsNull(bool emptyStringIsNull);
/// Sets the empty string handling flag.
bool getEmptyStringIsNull() const;
/// Returns the empty string handling flag.
void setForceEmptyString(bool forceEmptyString);
/// Sets the force empty string flag.
bool getForceEmptyString() const;
/// Returns the force empty string flag.
template <typename T>
bool isValueNull(const T& /*str*/, bool deflt)
/// Utility function to determine the nullness of the value.
/// This generic version always returns default value
/// (i.e. does nothing). The std::string overload does
/// the actual work.
///
{
return deflt;
}
bool isValueNull(const std::string& str, bool deflt);
/// Overload for const reference to std::string.
///
/// Returns true when folowing conditions are met:
///
/// - string is empty
/// - getEmptyStringIsNull() returns true
bool isValueNull(const Poco::UTF16String& str, bool deflt);
/// Overload for const reference to UTF16String.
///
/// Returns true when folowing conditions are met:
///
/// - string is empty
/// - getEmptyStringIsNull() returns true
private:
template <typename S>
bool isStringNull(const S& str, bool deflt)
{
if (getForceEmptyString()) return false;
if (getEmptyStringIsNull() && str.empty())
return true;
return deflt;
}
ExtractorPtr _pExtractor;
Poco::UInt32 _limit;
Poco::UInt32 _position;
bool _bulk;
bool _emptyStringIsNull;
bool _forceEmptyString;
};
using AbstractExtractionVec = std::vector<AbstractExtraction::Ptr>;
using AbstractExtractionVecVec = std::vector<AbstractExtractionVec>;
using AbstractExtractionDeq = std::deque<AbstractExtraction::Ptr>;
using AbstractExtractionDeqVec = std::vector<AbstractExtractionDeq>;
using AbstractExtractionLst = std::list<AbstractExtraction::Ptr>;
using AbstractExtractionLstVec = std::vector<AbstractExtractionLst>;
//
// inlines
//
inline void AbstractExtraction::setExtractor(ExtractorPtr pExtractor)
{
_pExtractor = pExtractor;
}
inline AbstractExtraction::ExtractorPtr AbstractExtraction::getExtractor() const
{
return _pExtractor;
}
inline void AbstractExtraction::setLimit(Poco::UInt32 limit)
{
_limit = limit;
}
inline Poco::UInt32 AbstractExtraction::getLimit() const
{
return _limit;
}
inline bool AbstractExtraction::isNull(std::size_t /*row*/) const
{
throw NotImplementedException("Check for null values not implemented.");
}
inline Poco::UInt32 AbstractExtraction::position() const
{
return _position;
}
inline bool AbstractExtraction::isBulk() const
{
return _bulk;
}
inline void AbstractExtraction::reset()
{
}
inline bool AbstractExtraction::canExtract() const
{
return true;
}
inline void AbstractExtraction::setEmptyStringIsNull(bool emptyStringIsNull)
{
_emptyStringIsNull = emptyStringIsNull;
}
inline bool AbstractExtraction::getEmptyStringIsNull() const
{
return _emptyStringIsNull;
}
inline void AbstractExtraction::setForceEmptyString(bool forceEmptyString)
{
_forceEmptyString = forceEmptyString;
}
inline bool AbstractExtraction::getForceEmptyString() const
{
return _forceEmptyString;
}
inline bool AbstractExtraction::isValueNull(const std::string& str, bool deflt)
{
return isStringNull(str, deflt);
}
inline bool AbstractExtraction::isValueNull(const Poco::UTF16String& str, bool deflt)
{
return isStringNull(str, deflt);
}
} } // namespace Poco::Data
#endif // Data_AbstractExtraction_INCLUDED

View File

@ -0,0 +1,351 @@
//
// AbstractExtractor.h
//
// Library: Data
// Package: DataCore
// Module: AbstractExtractor
//
// Definition of the AbstractExtractor class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_AbstractExtractor_INCLUDED
#define Data_AbstractExtractor_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/Constants.h"
#include "Poco/Data/LOB.h"
#include "Poco/UTFString.h"
#include <vector>
#include <deque>
#include <list>
#include <string>
#include <cstddef>
namespace Poco {
class DateTime;
class Any;
namespace Dynamic {
class Var;
}
namespace Data {
class Date;
class Time;
class Data_API AbstractExtractor
/// Interface used to extract data from a single result row.
/// If an extractor receives null it is not allowed to change val!
{
public:
using Ptr = SharedPtr<AbstractExtractor>;
AbstractExtractor();
/// Creates the AbstractExtractor.
virtual ~AbstractExtractor();
/// Destroys the AbstractExtractor.
virtual bool extract(std::size_t pos, Poco::Int8& val) = 0;
/// Extracts an Int8. Returns false if null was received.
virtual bool extract(std::size_t pos, std::vector<Poco::Int8>& val);
/// Extracts an Int8 vector.
virtual bool extract(std::size_t pos, std::deque<Poco::Int8>& val);
/// Extracts an Int8 deque.
virtual bool extract(std::size_t pos, std::list<Poco::Int8>& val);
/// Extracts an Int8 list.
virtual bool extract(std::size_t pos, Poco::UInt8& val) = 0;
/// Extracts an UInt8. Returns false if null was received.
virtual bool extract(std::size_t pos, std::vector<Poco::UInt8>& val);
/// Extracts an UInt8 vector.
virtual bool extract(std::size_t pos, std::deque<Poco::UInt8>& val);
/// Extracts an UInt8 deque.
virtual bool extract(std::size_t pos, std::list<Poco::UInt8>& val);
/// Extracts an UInt8 list.
virtual bool extract(std::size_t pos, Poco::Int16& val) = 0;
/// Extracts an Int16. Returns false if null was received.
virtual bool extract(std::size_t pos, std::vector<Poco::Int16>& val);
/// Extracts an Int16 vector.
virtual bool extract(std::size_t pos, std::deque<Poco::Int16>& val);
/// Extracts an Int16 deque.
virtual bool extract(std::size_t pos, std::list<Poco::Int16>& val);
/// Extracts an Int16 list.
virtual bool extract(std::size_t pos, Poco::UInt16& val) = 0;
/// Extracts an UInt16. Returns false if null was received.
virtual bool extract(std::size_t pos, std::vector<Poco::UInt16>& val);
/// Extracts an UInt16 vector.
virtual bool extract(std::size_t pos, std::deque<Poco::UInt16>& val);
/// Extracts an UInt16 deque.
virtual bool extract(std::size_t pos, std::list<Poco::UInt16>& val);
/// Extracts an UInt16 list.
virtual bool extract(std::size_t pos, Poco::Int32& val) = 0;
/// Extracts an Int32. Returns false if null was received.
virtual bool extract(std::size_t pos, std::vector<Poco::Int32>& val);
/// Extracts an Int32 vector.
virtual bool extract(std::size_t pos, std::deque<Poco::Int32>& val);
/// Extracts an Int32 deque.
virtual bool extract(std::size_t pos, std::list<Poco::Int32>& val);
/// Extracts an Int32 list.
virtual bool extract(std::size_t pos, Poco::UInt32& val) = 0;
/// Extracts an UInt32. Returns false if null was received.
virtual bool extract(std::size_t pos, std::vector<Poco::UInt32>& val);
/// Extracts an UInt32 vector.
virtual bool extract(std::size_t pos, std::deque<Poco::UInt32>& val);
/// Extracts an UInt32 deque.
virtual bool extract(std::size_t pos, std::list<Poco::UInt32>& val);
/// Extracts an UInt32 list.
virtual bool extract(std::size_t pos, Poco::Int64& val) = 0;
/// Extracts an Int64. Returns false if null was received.
virtual bool extract(std::size_t pos, std::vector<Poco::Int64>& val);
/// Extracts an Int64 vector.
virtual bool extract(std::size_t pos, std::deque<Poco::Int64>& val);
/// Extracts an Int64 deque.
virtual bool extract(std::size_t pos, std::list<Poco::Int64>& val);
/// Extracts an Int64 list.
virtual bool extract(std::size_t pos, Poco::UInt64& val) = 0;
/// Extracts an UInt64. Returns false if null was received.
virtual bool extract(std::size_t pos, std::vector<Poco::UInt64>& val);
/// Extracts an UInt64 vector.
virtual bool extract(std::size_t pos, std::deque<Poco::UInt64>& val);
/// Extracts an UInt64 deque.
virtual bool extract(std::size_t pos, std::list<Poco::UInt64>& val);
/// Extracts an UInt64 list.
#ifndef POCO_INT64_IS_LONG
virtual bool extract(std::size_t pos, long& val) = 0;
/// Extracts a long. Returns false if null was received.
virtual bool extract(std::size_t pos, unsigned long& val) = 0;
/// Extracts an unsigned long. Returns false if null was received.
virtual bool extract(std::size_t pos, std::vector<long>& val);
/// Extracts a long vector.
virtual bool extract(std::size_t pos, std::deque<long>& val);
/// Extracts a long deque.
virtual bool extract(std::size_t pos, std::list<long>& val);
/// Extracts a long list.
#endif
virtual bool extract(std::size_t pos, bool& val) = 0;
/// Extracts a boolean. Returns false if null was received.
virtual bool extract(std::size_t pos, std::vector<bool>& val);
/// Extracts a boolean vector.
virtual bool extract(std::size_t pos, std::deque<bool>& val);
/// Extracts a boolean deque.
virtual bool extract(std::size_t pos, std::list<bool>& val);
/// Extracts a boolean list.
virtual bool extract(std::size_t pos, float& val) = 0;
/// Extracts a float. Returns false if null was received.
virtual bool extract(std::size_t pos, std::vector<float>& val);
/// Extracts a float vector.
virtual bool extract(std::size_t pos, std::deque<float>& val);
/// Extracts a float deque.
virtual bool extract(std::size_t pos, std::list<float>& val);
/// Extracts a float list.
virtual bool extract(std::size_t pos, double& val) = 0;
/// Extracts a double. Returns false if null was received.
virtual bool extract(std::size_t pos, std::vector<double>& val);
/// Extracts a double vector.
virtual bool extract(std::size_t pos, std::deque<double>& val);
/// Extracts a double deque.
virtual bool extract(std::size_t pos, std::list<double>& val);
/// Extracts a double list.
virtual bool extract(std::size_t pos, char& val) = 0;
/// Extracts a single character. Returns false if null was received.
virtual bool extract(std::size_t pos, std::vector<char>& val);
/// Extracts a character vector.
virtual bool extract(std::size_t pos, std::deque<char>& val);
/// Extracts a character deque.
virtual bool extract(std::size_t pos, std::list<char>& val);
/// Extracts a character list.
virtual bool extract(std::size_t pos, std::string& val) = 0;
/// Extracts a string. Returns false if null was received.
virtual bool extract(std::size_t pos, std::vector<std::string>& val);
/// Extracts a string vector.
virtual bool extract(std::size_t pos, std::deque<std::string>& val);
/// Extracts a string deque.
virtual bool extract(std::size_t pos, std::list<std::string>& val);
/// Extracts a string list.
virtual bool extract(std::size_t pos, UTF16String& val);
/// Extracts a UTF16String. Returns false if null was received.
virtual bool extract(std::size_t pos, std::vector<UTF16String>& val);
/// Extracts a UTF16String vector.
virtual bool extract(std::size_t pos, std::deque<UTF16String>& val);
/// Extracts a UTF16String deque.
virtual bool extract(std::size_t pos, std::list<UTF16String>& val);
/// Extracts a UTF16String list.
virtual bool extract(std::size_t pos, BLOB& val) = 0;
/// Extracts a BLOB. Returns false if null was received.
virtual bool extract(std::size_t pos, CLOB& val) = 0;
/// Extracts a CLOB. Returns false if null was received.
virtual bool extract(std::size_t pos, std::vector<BLOB>& val);
/// Extracts a BLOB vector.
virtual bool extract(std::size_t pos, std::deque<BLOB>& val);
/// Extracts a BLOB deque.
virtual bool extract(std::size_t pos, std::list<BLOB>& val);
/// Extracts a BLOB list.
virtual bool extract(std::size_t pos, std::vector<CLOB>& val);
/// Extracts a CLOB vector.
virtual bool extract(std::size_t pos, std::deque<CLOB>& val);
/// Extracts a CLOB deque.
virtual bool extract(std::size_t pos, std::list<CLOB>& val);
/// Extracts a CLOB list.
virtual bool extract(std::size_t pos, DateTime& val) = 0;
/// Extracts a DateTime. Returns false if null was received.
virtual bool extract(std::size_t pos, std::vector<DateTime>& val);
/// Extracts a DateTime vector.
virtual bool extract(std::size_t pos, std::deque<DateTime>& val);
/// Extracts a DateTime deque.
virtual bool extract(std::size_t pos, std::list<DateTime>& val);
/// Extracts a DateTime list.
virtual bool extract(std::size_t pos, Date& val) = 0;
/// Extracts a Date. Returns false if null was received.
virtual bool extract(std::size_t pos, std::vector<Date>& val);
/// Extracts a Date vector.
virtual bool extract(std::size_t pos, std::deque<Date>& val);
/// Extracts a Date deque.
virtual bool extract(std::size_t pos, std::list<Date>& val);
/// Extracts a Date list.
virtual bool extract(std::size_t pos, Time& val) = 0;
/// Extracts a Time. Returns false if null was received.
virtual bool extract(std::size_t pos, std::vector<Time>& val);
/// Extracts a Time vector.
virtual bool extract(std::size_t pos, std::deque<Time>& val);
/// Extracts a Time deque.
virtual bool extract(std::size_t pos, std::list<Time>& val);
/// Extracts a Time list.
virtual bool extract(std::size_t pos, Any& val) = 0;
/// Extracts an Any. Returns false if null was received.
virtual bool extract(std::size_t pos, std::vector<Any>& val);
/// Extracts an Any vector.
virtual bool extract(std::size_t pos, std::deque<Any>& val);
/// Extracts an Any deque.
virtual bool extract(std::size_t pos, std::list<Any>& val);
/// Extracts an Any list.
virtual bool extract(std::size_t pos, Poco::Dynamic::Var& val) = 0;
/// Extracts a Var. Returns false if null was received.
virtual bool extract(std::size_t pos, std::vector<Poco::Dynamic::Var>& val);
/// Extracts a Var vector.
virtual bool extract(std::size_t pos, std::deque<Poco::Dynamic::Var>& val);
/// Extracts a Var deque.
virtual bool extract(std::size_t pos, std::list<Poco::Dynamic::Var>& val);
/// Extracts a Var list.
virtual bool isNull(std::size_t col, std::size_t row = POCO_DATA_INVALID_ROW) = 0;
/// Returns true if the value at [col,row] position is null.
virtual void reset();
/// Resets any information internally cached by the extractor.
};
///
/// inlines
///
inline void AbstractExtractor::reset()
{
//default no-op
}
} } // namespace Poco::Data
#endif // Data_AbstractExtractor_INCLUDED

View File

@ -0,0 +1,71 @@
//
// AbstractPreparation.h
//
// Library: Data
// Package: DataCore
// Module: AbstractPreparation
//
// Definition of the AbstractPreparation class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_AbstractPreparation_INCLUDED
#define Data_AbstractPreparation_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/AbstractPreparator.h"
#include "Poco/SharedPtr.h"
#include <cstddef>
namespace Poco {
namespace Data {
class Data_API AbstractPreparation
/// Interface for calling the appropriate AbstractPreparator method
{
public:
using Ptr = SharedPtr<AbstractPreparation>;
using PreparatorPtr = AbstractPreparator::Ptr;
AbstractPreparation(PreparatorPtr pPreparator);
/// Creates the AbstractPreparation.
virtual ~AbstractPreparation();
/// Destroys the AbstractPreparation.
virtual void prepare() = 0;
/// Prepares data.
protected:
AbstractPreparation();
AbstractPreparation(const AbstractPreparation&);
AbstractPreparation& operator = (const AbstractPreparation&);
PreparatorPtr preparation();
/// Returns the preparation object
PreparatorPtr _pPreparator;
};
//
// inlines
//
inline AbstractPreparation::PreparatorPtr AbstractPreparation::preparation()
{
return _pPreparator;
}
} } // namespace Poco::Data
#endif // Data_AbstractPreparation_INCLUDED

View File

@ -0,0 +1,388 @@
//
// AbstractPreparator.h
//
// Library: Data
// Package: DataCore
// Module: AbstractPreparator
//
// Definition of the AbstractPreparator class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_AbstractPreparator_INCLUDED
#define Data_AbstractPreparator_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/RefCountedObject.h"
#include "Poco/Data/LOB.h"
#include "Poco/UTFString.h"
#include <vector>
#include <deque>
#include <list>
#include <cstddef>
namespace Poco {
class DateTime;
class Any;
namespace Dynamic {
class Var;
}
namespace Data {
class Date;
class Time;
class Data_API AbstractPreparator
/// Interface used for database preparation where we first have to register all data types
/// (and memory output locations) before extracting data, e.g. ODBC.
/// Extract works as two-phase extract: first we call prepare once, then extract n-times.
/// There are cases (bulk operations using std::vector storage) when extract is called only once.
/// The value passed to a prepare() call is not used by the prepare, serving only as an indication
/// of the data type being prepared, thus all values are passed as const references.
/// Implementing this interface is not mandatory for a connector. Connectors that only extract data
/// after SQL execution (e.g. SQLite) do not need this functionality at all.
{
public:
using Ptr = SharedPtr<AbstractPreparator>;
AbstractPreparator(Poco::UInt32 length = 1u);
/// Creates the AbstractPreparator.
virtual ~AbstractPreparator();
/// Destroys the AbstractPreparator.
virtual void prepare(std::size_t pos, const Poco::Int8&) = 0;
/// Prepares an Int8.
virtual void prepare(std::size_t pos, const std::vector<Poco::Int8>& val);
/// Prepares an Int8 vector.
virtual void prepare(std::size_t pos, const std::deque<Poco::Int8>& val);
/// Prepares an Int8 deque.
virtual void prepare(std::size_t pos, const std::list<Poco::Int8>& val);
/// Prepares an Int8 list.
virtual void prepare(std::size_t pos, const Poco::UInt8&) = 0;
/// Prepares an UInt8.
virtual void prepare(std::size_t pos, const std::vector<Poco::UInt8>& val);
/// Prepares an UInt8 vector.
virtual void prepare(std::size_t pos, const std::deque<Poco::UInt8>& val);
/// Prepares an UInt8 deque.
virtual void prepare(std::size_t pos, const std::list<Poco::UInt8>& val);
/// Prepares an UInt8 list.
virtual void prepare(std::size_t pos, const Poco::Int16&) = 0;
/// Prepares an Int16.
virtual void prepare(std::size_t pos, const std::vector<Poco::Int16>& val);
/// Prepares an Int16 vector.
virtual void prepare(std::size_t pos, const std::deque<Poco::Int16>& val);
/// Prepares an Int16 deque.
virtual void prepare(std::size_t pos, const std::list<Poco::Int16>& val);
/// Prepares an Int16 list.
virtual void prepare(std::size_t pos, const Poco::UInt16&) = 0;
/// Prepares an UInt16.
virtual void prepare(std::size_t pos, const std::vector<Poco::UInt16>& val);
/// Prepares an UInt16 vector.
virtual void prepare(std::size_t pos, const std::deque<Poco::UInt16>& val);
/// Prepares an UInt16 deque.
virtual void prepare(std::size_t pos, const std::list<Poco::UInt16>& val);
/// Prepares an UInt16 list.
virtual void prepare(std::size_t pos, const Poco::Int32&) = 0;
/// Prepares an Int32.
virtual void prepare(std::size_t pos, const std::vector<Poco::Int32>& val);
/// Prepares an Int32 vector.
virtual void prepare(std::size_t pos, const std::deque<Poco::Int32>& val);
/// Prepares an Int32 deque.
virtual void prepare(std::size_t pos, const std::list<Poco::Int32>& val);
/// Prepares an Int32 list.
virtual void prepare(std::size_t pos, const Poco::UInt32&) = 0;
/// Prepares an UInt32.
virtual void prepare(std::size_t pos, const std::vector<Poco::UInt32>& val);
/// Prepares an UInt32 vector.
virtual void prepare(std::size_t pos, const std::deque<Poco::UInt32>& val);
/// Prepares an UInt32 deque.
virtual void prepare(std::size_t pos, const std::list<Poco::UInt32>& val);
/// Prepares an UInt32 list.
virtual void prepare(std::size_t pos, const Poco::Int64&) = 0;
/// Prepares an Int64.
virtual void prepare(std::size_t pos, const std::vector<Poco::Int64>& val);
/// Prepares an Int64 vector.
virtual void prepare(std::size_t pos, const std::deque<Poco::Int64>& val);
/// Prepares an Int64 deque.
virtual void prepare(std::size_t pos, const std::list<Poco::Int64>& val);
/// Prepares an Int64 list.
virtual void prepare(std::size_t pos, const Poco::UInt64&) = 0;
/// Prepares an UInt64.
virtual void prepare(std::size_t pos, const std::vector<Poco::UInt64>& val);
/// Prepares an UInt64 vector.
virtual void prepare(std::size_t pos, const std::deque<Poco::UInt64>& val);
/// Prepares an UInt64 deque.
virtual void prepare(std::size_t pos, const std::list<Poco::UInt64>& val);
/// Prepares an UInt64 list.
#ifndef POCO_INT64_IS_LONG
virtual void prepare(std::size_t pos, const long&) = 0;
/// Prepares a long.
virtual void prepare(std::size_t pos, const unsigned long&) = 0;
/// Prepares an unsigned long.
virtual void prepare(std::size_t pos, const std::vector<long>& val);
/// Prepares a long vector.
virtual void prepare(std::size_t pos, const std::deque<long>& val);
/// Prepares a long deque.
virtual void prepare(std::size_t pos, const std::list<long>& val);
/// Prepares a long list.
#endif
virtual void prepare(std::size_t pos, const bool&) = 0;
/// Prepares a boolean.
virtual void prepare(std::size_t pos, const std::vector<bool>& val);
/// Prepares a boolean vector.
virtual void prepare(std::size_t pos, const std::deque<bool>& val);
/// Prepares a boolean deque.
virtual void prepare(std::size_t pos, const std::list<bool>& val);
/// Prepares a boolean list.
virtual void prepare(std::size_t pos, const float&) = 0;
/// Prepares a float.
virtual void prepare(std::size_t pos, const std::vector<float>& val);
/// Prepares a float vector.
virtual void prepare(std::size_t pos, const std::deque<float>& val);
/// Prepares a float deque.
virtual void prepare(std::size_t pos, const std::list<float>& val);
/// Prepares a float list.
virtual void prepare(std::size_t pos, const double&) = 0;
/// Prepares a double.
virtual void prepare(std::size_t pos, const std::vector<double>& val);
/// Prepares a double vector.
virtual void prepare(std::size_t pos, const std::deque<double>& val);
/// Prepares a double deque.
virtual void prepare(std::size_t pos, const std::list<double>& val);
/// Prepares a double list.
virtual void prepare(std::size_t pos, const char&) = 0;
/// Prepares a single character.
virtual void prepare(std::size_t pos, const std::vector<char>& val);
/// Prepares a character vector.
virtual void prepare(std::size_t pos, const std::deque<char>& val);
/// Prepares a character deque.
virtual void prepare(std::size_t pos, const std::list<char>& val);
/// Prepares a character list.
virtual void prepare(std::size_t pos, const std::string&) = 0;
/// Prepares a string.
virtual void prepare(std::size_t pos, const std::vector<std::string>& val);
/// Prepares a string vector.
virtual void prepare(std::size_t pos, const std::deque<std::string>& val);
/// Prepares a string deque.
virtual void prepare(std::size_t pos, const std::list<std::string>& val);
/// Prepares a character list.
virtual void prepare(std::size_t pos, const UTF16String&);
/// Prepares a UTF16String.
virtual void prepare(std::size_t pos, const std::vector<UTF16String>& val);
/// Prepares a UTF16String vector.
virtual void prepare(std::size_t pos, const std::deque<UTF16String>& val);
/// Prepares a UTF16String deque.
virtual void prepare(std::size_t pos, const std::list<UTF16String>& val);
/// Prepares a UTF16String list.
virtual void prepare(std::size_t pos, const BLOB&) = 0;
/// Prepares a BLOB.
virtual void prepare(std::size_t pos, const CLOB&) = 0;
/// Prepares a CLOB.
virtual void prepare(std::size_t pos, const std::vector<BLOB>& val);
/// Prepares a BLOB vector.
virtual void prepare(std::size_t pos, const std::deque<BLOB>& val);
/// Prepares a BLOB deque.
virtual void prepare(std::size_t pos, const std::list<BLOB>& val);
/// Prepares a BLOB list.
virtual void prepare(std::size_t pos, const std::vector<CLOB>& val);
/// Prepares a CLOB vector.
virtual void prepare(std::size_t pos, const std::deque<CLOB>& val);
/// Prepares a CLOB deque.
virtual void prepare(std::size_t pos, const std::list<CLOB>& val);
/// Prepares a CLOB list.
virtual void prepare(std::size_t pos, const DateTime&) = 0;
/// Prepares a DateTime.
virtual void prepare(std::size_t pos, const std::vector<DateTime>& val);
/// Prepares a DateTime vector.
virtual void prepare(std::size_t pos, const std::deque<DateTime>& val);
/// Prepares a DateTime deque.
virtual void prepare(std::size_t pos, const std::list<DateTime>& val);
/// Prepares a DateTime list.
virtual void prepare(std::size_t pos, const Date&) = 0;
/// Prepares a Date.
virtual void prepare(std::size_t pos, const std::vector<Date>& val);
/// Prepares a Date vector.
virtual void prepare(std::size_t pos, const std::deque<Date>& val);
/// Prepares a Date deque.
virtual void prepare(std::size_t pos, const std::list<Date>& val);
/// Prepares a Date list.
virtual void prepare(std::size_t pos, const Time&) = 0;
/// Prepares a Time.
virtual void prepare(std::size_t pos, const std::vector<Time>& val);
/// Prepares a Time vector.
virtual void prepare(std::size_t pos, const std::deque<Time>& val);
/// Prepares a Time deque.
virtual void prepare(std::size_t pos, const std::list<Time>& val);
/// Prepares a Time list.
virtual void prepare(std::size_t pos, const Any&) = 0;
/// Prepares an Any.
virtual void prepare(std::size_t pos, const std::vector<Any>& val);
/// Prepares an Any vector.
virtual void prepare(std::size_t pos, const std::deque<Any>& val);
/// Prepares an Any deque.
virtual void prepare(std::size_t pos, const std::list<Any>& val);
/// Prepares an Any list.
virtual void prepare(std::size_t pos, const Poco::Dynamic::Var&) = 0;
/// Prepares a Var.
virtual void prepare(std::size_t pos, const std::vector<Poco::Dynamic::Var>& val);
/// Prepares a Var vector.
virtual void prepare(std::size_t pos, const std::deque<Poco::Dynamic::Var>& val);
/// Prepares a Var deque.
virtual void prepare(std::size_t pos, const std::list<Poco::Dynamic::Var>& val);
/// Prepares a Var list.
void setLength(Poco::UInt32 length);
/// Sets the length of prepared data.
/// Needed only for data lengths greater than 1 (i.e. for
/// bulk operations).
Poco::UInt32 getLength() const;
/// Returns the length of prepared data. Defaults to 1.
/// The length is greater than one for bulk operations.
void setBulk(bool bulkPrep = true);
/// Sets bulk operation flag (always false at object creation time)
bool isBulk() const;
/// Returns bulk operation flag.
private:
Poco::UInt32 _length;
bool _bulk;
};
///
/// inlines
///
inline void AbstractPreparator::setLength(Poco::UInt32 length)
{
_length = length;
}
inline Poco::UInt32 AbstractPreparator::getLength() const
{
return _length;
}
inline void AbstractPreparator::setBulk(bool bulkPrep)
{
_bulk = bulkPrep;
}
inline bool AbstractPreparator::isBulk() const
{
return _bulk;
}
} } // namespace Poco::Data
#endif // Data_AbstractPreparator_INCLUDED

View File

@ -0,0 +1,315 @@
//
// AbstractSessionImpl.h
//
// Library: Data
// Package: DataCore
// Module: AbstractSessionImpl
//
// Definition of the AbstractSessionImpl class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_AbstractSessionImpl_INCLUDED
#define Data_AbstractSessionImpl_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/SessionImpl.h"
#include "Poco/Data/DataException.h"
#include <map>
namespace Poco {
namespace Data {
template <class C>
class AbstractSessionImpl: public SessionImpl
/// A partial implementation of SessionImpl, providing
/// features and properties management.
///
/// To implement a certain feature or property, a subclass
/// must provide setter and getter methods and register
/// them with addFeature() or addProperty().
{
public:
typedef void (C::*FeatureSetter)(const std::string&, bool);
/// The setter method for a feature.
typedef bool (C::*FeatureGetter)(const std::string&) const;
/// The getter method for a feature.
typedef void (C::*PropertySetter)(const std::string&, const Poco::Any&);
/// The setter method for a property.
typedef Poco::Any (C::*PropertyGetter)(const std::string&) const;
/// The getter method for a property.
AbstractSessionImpl(const std::string& connectionString,
std::size_t timeout = LOGIN_TIMEOUT_DEFAULT): SessionImpl(connectionString, timeout),
_storage(std::string("deque")),
_bulk(false),
_emptyStringIsNull(false),
_forceEmptyString(false)
/// Creates the AbstractSessionImpl.
///
/// Adds "storage" property and sets the default internal storage container
/// type to std::deque.
/// The storage is created by statements automatically whenever a query
/// returning results is executed but external storage is provided by the user.
/// Storage type can be reconfigured at runtime both globally (for the
/// duration of the session) and locally (for a single statement execution only).
/// See StatementImpl for details on how this property is used at runtime.
///
/// Adds "handle" property which, if set by the back end, returns native handle
/// for the back end DB.
///
/// Adds "bulk" feature and sets it to false.
/// Bulk feature determines whether the session is capable of bulk operations.
/// Connectors that are capable of it must set this feature prior to attempting
/// bulk operations.
///
/// Adds "emptyStringIsNull" feature and sets it to false. This feature should be
/// set to true in order to modify the behavior of the databases that distinguish
/// between zero-length character strings as nulls. Setting this feature to true
/// shall disregard any difference between empty character strings and nulls,
/// causing the framework to treat them the same (i.e. behave like Oracle).
///
/// Adds "forceEmptyString" feature and sets it to false. This feature should be set
/// to true in order to force the databases that do not distinguish empty strings from
/// nulls (e.g. Oracle) to always report empty string.
///
/// The "emptyStringIsNull" and "forceEmptyString" features are mutually exclusive.
/// While these features can not both be true at the same time, they can both be false,
/// resulting in default underlying database behavior.
///
{
addProperty("storage",
&AbstractSessionImpl<C>::setStorage,
&AbstractSessionImpl<C>::getStorage);
addProperty("handle",
&AbstractSessionImpl<C>::setHandle,
&AbstractSessionImpl<C>::getHandle);
addFeature("bulk",
&AbstractSessionImpl<C>::setBulk,
&AbstractSessionImpl<C>::getBulk);
addFeature("emptyStringIsNull",
&AbstractSessionImpl<C>::setEmptyStringIsNull,
&AbstractSessionImpl<C>::getEmptyStringIsNull);
addFeature("forceEmptyString",
&AbstractSessionImpl<C>::setForceEmptyString,
&AbstractSessionImpl<C>::getForceEmptyString);
}
~AbstractSessionImpl()
/// Destroys the AbstractSessionImpl.
{
}
void setFeature(const std::string& name, bool state)
/// Looks a feature up in the features map
/// and calls the feature's setter, if there is one.
{
typename FeatureMap::const_iterator it = _features.find(name);
if (it != _features.end())
{
if (it->second.setter)
(static_cast<C*>(this)->*it->second.setter)(name, state);
else
throw NotImplementedException("set", name);
}
else throw NotSupportedException(name);
}
bool getFeature(const std::string& name)
/// Looks a feature up in the features map
/// and calls the feature's getter, if there is one.
{
typename FeatureMap::const_iterator it = _features.find(name);
if (it != _features.end())
{
if (it->second.getter)
return (static_cast<C*>(this)->*it->second.getter)(name);
else
throw NotImplementedException("get", name);
}
else throw NotSupportedException(name);
}
void setProperty(const std::string& name, const Poco::Any& value)
/// Looks a property up in the properties map
/// and calls the property's setter, if there is one.
{
typename PropertyMap::const_iterator it = _properties.find(name);
if (it != _properties.end())
{
if (it->second.setter)
(static_cast<C*>(this)->*it->second.setter)(name, value);
else
throw NotImplementedException("set", name);
}
else throw NotSupportedException(name);
}
Poco::Any getProperty(const std::string& name)
/// Looks a property up in the properties map
/// and calls the property's getter, if there is one.
{
typename PropertyMap::const_iterator it = _properties.find(name);
if (it != _properties.end())
{
if (it->second.getter)
return (static_cast<C*>(this)->*it->second.getter)(name);
else
throw NotImplementedException("set", name);
}
else throw NotSupportedException(name);
}
void setStorage(const std::string& value)
/// Sets the storage type.
{
_storage = value;
}
void setStorage(const std::string& name, const Poco::Any& value)
/// Sets the storage type.
{
_storage = Poco::RefAnyCast<std::string>(value);
}
Poco::Any getStorage(const std::string& name="") const
/// Returns the storage type
{
return _storage;
}
void setHandle(const std::string& name, const Poco::Any& handle)
/// Sets the native session handle.
{
_handle = handle;
}
Poco::Any getHandle(const std::string& name="") const
/// Returns the native session handle.
{
return _handle;
}
void setBulk(const std::string& name, bool bulk)
/// Sets the execution type.
{
_bulk = bulk;
}
bool getBulk(const std::string& name="") const
/// Returns the execution type
{
return _bulk;
}
void setEmptyStringIsNull(const std::string& name, bool emptyStringIsNull)
/// Sets the behavior regarding empty variable length strings.
/// Those are treated as NULL by Oracle and as empty string by
/// most other databases.
/// When this feature is true, empty strings are treated as NULL.
{
if (emptyStringIsNull && _forceEmptyString)
throw InvalidAccessException("Features mutually exclusive");
_emptyStringIsNull = emptyStringIsNull;
}
bool getEmptyStringIsNull(const std::string& name="") const
/// Returns the setting for the behavior regarding empty variable
/// length strings. See setEmptyStringIsNull(const std::string&, bool)
/// and this class documentation for feature rationale and details.
{
return _emptyStringIsNull;
}
void setForceEmptyString(const std::string& name, bool forceEmptyString)
/// Sets the behavior regarding empty variable length strings.
/// Those are treated as NULL by Oracle and as empty string by
/// most other databases.
/// When this feature is true, both empty strings and NULL values
/// are reported as empty strings.
{
if (forceEmptyString && _emptyStringIsNull)
throw InvalidAccessException("Features mutually exclusive");
_forceEmptyString = forceEmptyString;
}
bool getForceEmptyString(const std::string& name="") const
/// Returns the setting for the behavior regarding empty variable
/// length strings. See setForceEmptyString(const std::string&, bool)
/// and this class documentation for feature rationale and details.
{
return _forceEmptyString;
}
protected:
void addFeature(const std::string& name, FeatureSetter setter, FeatureGetter getter)
/// Adds a feature to the map of supported features.
///
/// The setter or getter can be null, in case setting or getting a feature
/// is not supported.
{
Feature feature;
feature.setter = setter;
feature.getter = getter;
_features[name] = feature;
}
void addProperty(const std::string& name, PropertySetter setter, PropertyGetter getter)
/// Adds a property to the map of supported properties.
///
/// The setter or getter can be null, in case setting or getting a property
/// is not supported.
{
Property property;
property.setter = setter;
property.getter = getter;
_properties[name] = property;
}
private:
struct Feature
{
FeatureSetter setter;
FeatureGetter getter;
};
struct Property
{
PropertySetter setter;
PropertyGetter getter;
};
using FeatureMap = std::map<std::string, Feature>;
using PropertyMap = std::map<std::string, Property>;
FeatureMap _features;
PropertyMap _properties;
std::string _storage;
bool _bulk;
bool _emptyStringIsNull;
bool _forceEmptyString;
Poco::Any _handle;
};
} } // namespace Poco::Data
#endif // Data_AbstractSessionImpl_INCLUDED

View File

@ -0,0 +1,222 @@
//
// ArchiveStrategy.h
//
// Library: Data
// Package: Logging
// Module: ArchiveStrategy
//
// Definition of the ArchiveStrategy class and subclasses.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_ArchiveStrategy_INCLUDED
#define Data_ArchiveStrategy_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/Session.h"
#include "Poco/DateTime.h"
#include "Poco/Timespan.h"
#include "Poco/Dynamic/Var.h"
#include "Poco/SharedPtr.h"
namespace Poco {
namespace Data {
class Data_API ArchiveStrategy
/// The ArchiveStrategy is used by SQLChannel to archive log rows.
{
public:
static const std::string DEFAULT_ARCHIVE_DESTINATION;
ArchiveStrategy(const std::string& connector,
const std::string& connect,
const std::string& source,
const std::string& destination = DEFAULT_ARCHIVE_DESTINATION);
/// Creates archive strategy.
virtual ~ArchiveStrategy();
/// Destroys archive strategy.
void open();
/// Opens the session.
virtual void archive() = 0;
/// Archives the rows.
const std::string& getSource() const;
/// Returns the name of the source table containing rows to be archived.
void setSource(const std::string& source);
/// Sets the name of the source table.
const std::string& getDestination() const;
/// Returns the name of the destination table for rows to be archived.
void setDestination(const std::string& destination);
/// Sets the name of the destination table.
virtual const std::string& getThreshold() const = 0;
/// Returns the archive threshold.
virtual void setThreshold(const std::string& threshold) = 0;
/// Sets the archive threshold.
protected:
using SessionPtr = Poco::SharedPtr<Session>;
using StatementPtr = Poco::SharedPtr<Statement>;
Session& session();
void setCopyStatement();
void setDeleteStatement();
void setCountStatement();
Statement& getCopyStatement();
Statement& getDeleteStatement();
Statement& getCountStatement();
private:
ArchiveStrategy();
ArchiveStrategy(const ArchiveStrategy&);
ArchiveStrategy& operator = (const ArchiveStrategy&);
std::string _connector;
std::string _connect;
SessionPtr _pSession;
StatementPtr _pCopyStatement;
StatementPtr _pDeleteStatement;
StatementPtr _pCountStatement;
std::string _source;
std::string _destination;
};
//
// inlines
//
inline const std::string& ArchiveStrategy::getSource() const
{
return _source;
}
inline void ArchiveStrategy::setSource(const std::string& source)
{
_source = source;
}
inline void ArchiveStrategy::setDestination(const std::string& destination)
{
_destination = destination;
}
inline const std::string& ArchiveStrategy::getDestination() const
{
return _destination;
}
inline Session& ArchiveStrategy::session()
{
return *_pSession;
}
inline void ArchiveStrategy::setCopyStatement()
{
_pCopyStatement = new Statement(*_pSession);
}
inline void ArchiveStrategy::setDeleteStatement()
{
_pDeleteStatement = new Statement(*_pSession);
}
inline void ArchiveStrategy::setCountStatement()
{
_pCountStatement = new Statement(*_pSession);
}
inline Statement& ArchiveStrategy::getCopyStatement()
{
return *_pCopyStatement;
}
inline Statement& ArchiveStrategy::getDeleteStatement()
{
return *_pDeleteStatement;
}
inline Statement& ArchiveStrategy::getCountStatement()
{
return *_pCountStatement;
}
//
// ArchiveByAgeStrategy
//
class Data_API ArchiveByAgeStrategy: public ArchiveStrategy
/// Archives rows scheduled for archiving.
{
public:
ArchiveByAgeStrategy(const std::string& connector,
const std::string& connect,
const std::string& sourceTable,
const std::string& destinationTable = DEFAULT_ARCHIVE_DESTINATION);
~ArchiveByAgeStrategy();
void archive();
const std::string& getThreshold() const;
/// Returns the archive threshold.
void setThreshold(const std::string& threshold);
/// Sets the archive threshold.
private:
ArchiveByAgeStrategy();
ArchiveByAgeStrategy(const ArchiveByAgeStrategy&);
ArchiveByAgeStrategy& operator = (const ArchiveByAgeStrategy&);
void initStatements();
Timespan _maxAge;
std::string _ageString;
DateTime _archiveDateTime;
Poco::Dynamic::Var _archiveCount;
};
//
// inlines
//
inline const std::string& ArchiveByAgeStrategy::getThreshold() const
{
return _ageString;
}
} } // namespace Poco::Data
#endif // Data_ArchiveStrategy_INCLUDED

View File

@ -0,0 +1,35 @@
//
// AutoTransaction.h
//
// Library: Data
// Package: DataCore
// Module: AutoTransaction
//
// Forward header for the Transaction class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_AutoTransaction_INCLUDED
#define Data_AutoTransaction_INCLUDED
#include "Poco/Data/Transaction.h"
namespace Poco {
namespace Data {
using AutoTransaction = Transaction;
} } // namespace Poco::Data
#endif // Data_AutoTransaction_INCLUDED

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,96 @@
//
// BulkExtraction.h
//
// Library: Data
// Package: DataCore
// Module: Bulk
//
// Definition of the BulkExtraction class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_Bulk_INCLUDED
#define Data_Bulk_INCLUDED
#include "Poco/Void.h"
#include "Poco/Data/Limit.h"
namespace Poco {
namespace Data {
class Data_API Bulk
{
public:
Bulk(const Limit& limit);
/// Creates the Bulk.
Bulk(Poco::UInt32 value);
/// Creates the Bulk.
~Bulk();
/// Destroys the bulk.
const Limit& limit() const;
/// Returns the limit asociated with this bulk object.
Poco::UInt32 size() const;
/// Returns the value of the limit asociated with
/// this bulk object.
private:
Bulk();
Limit _limit;
};
///
/// inlines
///
inline const Limit& Bulk::limit() const
{
return _limit;
}
inline Poco::UInt32 Bulk::size() const
{
return _limit.value();
}
namespace Keywords {
inline Bulk bulk(const Limit& limit = Limit(Limit::LIMIT_UNLIMITED, false, false))
/// Convenience function for creation of bulk.
{
return Bulk(limit);
}
inline void bulk(Void)
/// Dummy bulk function. Used for bulk binding creation
/// (see BulkBinding) and bulk extraction signalling to Statement.
{
}
} // namespace Keywords
typedef void (*BulkFnType)(Void);
} } // namespace Poco::Data
#endif // Data_Bulk_INCLUDED

View File

@ -0,0 +1,148 @@
//
// BulkBinding.h
//
// Library: Data
// Package: DataCore
// Module: BulkBinding
//
// Definition of the BulkBinding class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_BulkBinding_INCLUDED
#define Data_BulkBinding_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/AbstractBinding.h"
#include "Poco/Data/DataException.h"
#include "Poco/Data/TypeHandler.h"
#include "Poco/Data/Bulk.h"
#include <vector>
#include <deque>
#include <list>
#include <cstddef>
namespace Poco {
namespace Data {
template <class T>
class BulkBinding: public AbstractBinding
/// A BulkBinding maps a value to a column.
/// Bulk binding support is provided only for std::vector.
{
public:
BulkBinding(const T& val, Poco::UInt32 bulkSize, const std::string& name = "", Direction direction = PD_IN):
AbstractBinding(name, direction, bulkSize),
_val(val),
_bound(false)
/// Creates the BulkBinding.
{
if (0 == _val.size())
throw BindingException("Zero size containers not allowed.");
}
~BulkBinding()
/// Destroys the BulkBinding.
{
}
std::size_t numOfColumnsHandled() const
{
return 1;
}
std::size_t numOfRowsHandled() const
{
return _val.size();
}
bool canBind() const
{
return !_bound;
}
void bind(std::size_t pos)
{
poco_assert_dbg(!getBinder().isNull());
TypeHandler<T>::bind(pos, _val, getBinder(), getDirection());
_bound = true;
}
void reset ()
{
_bound = false;
getBinder()->reset();
}
private:
const T& _val;
bool _bound;
};
namespace Keywords {
template <typename T>
AbstractBinding::Ptr use(const std::vector<T>& t, BulkFnType, const std::string& name = "")
/// Convenience function for a more compact BulkBinding creation for std::vector.
{
return new BulkBinding<std::vector<T>>(t, static_cast<Poco::UInt32>(t.size()), name);
}
template <typename T>
AbstractBinding::Ptr in(const std::vector<T>& t, BulkFnType, const std::string& name = "")
/// Convenience function for a more compact BulkBinding creation for std::vector.
{
return new BulkBinding<std::vector<T>>(t, static_cast<Poco::UInt32>(t.size()), name);
}
template <typename T>
AbstractBinding::Ptr use(const std::deque<T>& t, BulkFnType, const std::string& name = "")
/// Convenience function for a more compact BulkBinding creation for std::deque.
{
return new BulkBinding<std::deque<T>>(t, static_cast<Poco::UInt32>(t.size()), name);
}
template <typename T>
AbstractBinding::Ptr in(const std::deque<T>& t, BulkFnType, const std::string& name = "")
/// Convenience function for a more compact BulkBinding creation for std::deque.
{
return new BulkBinding<std::deque<T>>(t, static_cast<Poco::UInt32>(t.size()), name);
}
template <typename T>
AbstractBinding::Ptr use(const std::list<T>& t, BulkFnType, const std::string& name = "")
/// Convenience function for a more compact BulkBinding creation for std::list.
{
return new BulkBinding<std::list<T>>(t, static_cast<Poco::UInt32>(t.size()), name);
}
template <typename T>
AbstractBinding::Ptr in(const std::list<T>& t, BulkFnType, const std::string& name = "")
/// Convenience function for a more compact BulkBinding creation for std::list.
{
return new BulkBinding<std::list<T>>(t, static_cast<Poco::UInt32>(t.size()), name);
}
} // namespace Keywords
} } // namespace Poco::Data
#endif // Data_BulkBinding_INCLUDED

View File

@ -0,0 +1,276 @@
//
// BulkExtraction.h
//
// Library: Data
// Package: DataCore
// Module: BulkExtraction
//
// Definition of the BulkExtraction class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_BulkExtraction_INCLUDED
#define Data_BulkExtraction_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/AbstractExtraction.h"
#include "Poco/Data/Bulk.h"
#include "Poco/Data/Preparation.h"
#include <vector>
namespace Poco {
namespace Data {
template <class C>
class BulkExtraction: public AbstractExtraction
/// Specialization for bulk extraction of values from a query result set.
/// Bulk extraction support is provided only for following STL containers:
/// - std::vector
/// - std::deque
/// - std::list
{
public:
using ValType = C;
using CValType = typename C::value_type;
using ValPtr = SharedPtr<ValType>;
using Type = BulkExtraction<ValType>;
using Ptr = SharedPtr<Type>;
BulkExtraction(C& result, Poco::UInt32 limit, const Position& pos = Position(0)):
AbstractExtraction(limit, pos.value(), true),
_rResult(result),
_default()
{
if (static_cast<Poco::UInt32>(result.size()) != limit)
result.resize(limit);
}
BulkExtraction(C& result, const CValType& def, Poco::UInt32 limit, const Position& pos = Position(0)):
AbstractExtraction(limit, pos.value(), true),
_rResult(result),
_default(def)
{
if (static_cast<Poco::UInt32>(result.size()) != limit)
result.resize(limit);
}
virtual ~BulkExtraction()
{
}
std::size_t numOfColumnsHandled() const
{
return TypeHandler<C>::size();
}
std::size_t numOfRowsHandled() const
{
return _rResult.size();
}
std::size_t numOfRowsAllowed() const
{
return getLimit();
}
bool isNull(std::size_t row) const
{
try
{
return _nulls.at(row);
}
catch (std::out_of_range& ex)
{
throw RangeException(ex.what());
}
}
std::size_t extract(std::size_t col)
{
AbstractExtractor::Ptr pExt = getExtractor();
TypeHandler<C>::extract(col, _rResult, _default, pExt);
typename C::iterator it = _rResult.begin();
typename C::iterator end = _rResult.end();
for (int row = 0; it !=end; ++it, ++row)
{
_nulls.push_back(isValueNull(*it, pExt->isNull(col, row)));
}
return _rResult.size();
}
virtual void reset()
{
}
AbstractPreparation::Ptr createPreparation(AbstractPreparator::Ptr& pPrep, std::size_t col)
{
Poco::UInt32 limit = getLimit();
if (limit != _rResult.size()) _rResult.resize(limit);
pPrep->setLength(limit);
pPrep->setBulk(true);
return new Preparation<C>(pPrep, col, _rResult);
}
protected:
const C& result() const
{
return _rResult;
}
private:
C& _rResult;
CValType _default;
std::deque<bool> _nulls;
};
template <class C>
class InternalBulkExtraction: public BulkExtraction<C>
/// Container Data Type specialization extension for extraction of values from a query result set.
///
/// This class is intended for PocoData internal use - it is used by StatementImpl
/// to automaticaly create internal BulkExtraction in cases when statement returns data and no external storage
/// was supplied. It is later used by RecordSet to retrieve the fetched data after statement execution.
/// It takes ownership of the Column pointer supplied as constructor argument. Column object, in turn
/// owns the data container pointer.
///
/// InternalBulkExtraction objects can not be copied or assigned.
{
public:
using ValType = C;
using CValType = typename C::value_type;
using ValPtr = SharedPtr<ValType>;
using Type = InternalBulkExtraction<ValType>;
using Ptr = SharedPtr<Type>;
InternalBulkExtraction(C& result,
Column<C>* pColumn,
Poco::UInt32 limit,
const Position& pos = Position(0)):
BulkExtraction<C>(result, CValType(), limit, pos),
_pColumn(pColumn)
/// Creates InternalBulkExtraction.
{
}
~InternalBulkExtraction()
/// Destroys InternalBulkExtraction.
{
delete _pColumn;
}
void reset()
{
_pColumn->reset();
}
const CValType& value(int index) const
{
try
{
return BulkExtraction<C>::result().at(index);
}
catch (std::out_of_range& ex)
{
throw RangeException(ex.what());
}
}
bool isNull(std::size_t row) const
{
return BulkExtraction<C>::isNull(row);
}
const Column<C>& column() const
{
return *_pColumn;
}
private:
InternalBulkExtraction();
InternalBulkExtraction(const InternalBulkExtraction&);
InternalBulkExtraction& operator = (const InternalBulkExtraction&);
Column<C>* _pColumn;
};
namespace Keywords {
template <typename T>
AbstractExtraction::Ptr into(std::vector<T>& t, const Bulk& bulk, const Position& pos = Position(0))
/// Convenience function to allow for a more compact creation of an extraction object
/// with std::vector bulk extraction support.
{
return new BulkExtraction<std::vector<T>>(t, bulk.size(), pos);
}
template <typename T>
AbstractExtraction::Ptr into(std::vector<T>& t, BulkFnType, const Position& pos = Position(0))
/// Convenience function to allow for a more compact creation of an extraction object
/// with std::vector bulk extraction support.
{
Poco::UInt32 size = static_cast<Poco::UInt32>(t.size());
if (0 == size) throw InvalidArgumentException("Zero length not allowed.");
return new BulkExtraction<std::vector<T>>(t, size, pos);
}
template <typename T>
AbstractExtraction::Ptr into(std::deque<T>& t, const Bulk& bulk, const Position& pos = Position(0))
/// Convenience function to allow for a more compact creation of an extraction object
/// with std::deque bulk extraction support.
{
return new BulkExtraction<std::deque<T>>(t, bulk.size(), pos);
}
template <typename T>
AbstractExtraction::Ptr into(std::deque<T>& t, BulkFnType, const Position& pos = Position(0))
/// Convenience function to allow for a more compact creation of an extraction object
/// with std::deque bulk extraction support.
{
Poco::UInt32 size = static_cast<Poco::UInt32>(t.size());
if (0 == size) throw InvalidArgumentException("Zero length not allowed.");
return new BulkExtraction<std::deque<T>>(t, size, pos);
}
template <typename T>
AbstractExtraction::Ptr into(std::list<T>& t, const Bulk& bulk, const Position& pos = Position(0))
/// Convenience function to allow for a more compact creation of an extraction object
/// with std::list bulk extraction support.
{
return new BulkExtraction<std::list<T>>(t, bulk.size(), pos);
}
template <typename T>
AbstractExtraction::Ptr into(std::list<T>& t, BulkFnType, const Position& pos = Position(0))
/// Convenience function to allow for a more compact creation of an extraction object
/// with std::list bulk extraction support.
{
Poco::UInt32 size = static_cast<Poco::UInt32>(t.size());
if (0 == size) throw InvalidArgumentException("Zero length not allowed.");
return new BulkExtraction<std::list<T>>(t, size, pos);
}
} // namespace Keywords
} } // namespace Poco::Data
#endif // Data_BulkExtraction_INCLUDED

View File

@ -0,0 +1,505 @@
//
// Column.h
//
// Library: Data
// Package: DataCore
// Module: Column
//
// Definition of the Column class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_Column_INCLUDED
#define Data_Column_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/MetaColumn.h"
#include "Poco/SharedPtr.h"
#include "Poco/RefCountedObject.h"
#include <vector>
#include <list>
#include <deque>
namespace Poco {
namespace Data {
template <class C>
class Column
/// Column class is column data container.
/// Data (a pointer to underlying STL container) is assigned to the class
/// at construction time. Construction with null pointer is not allowed.
/// This class owns the data assigned to it and deletes the storage on destruction.
{
public:
using Container = C;
using ContainerPtr = Poco::SharedPtr<C>;
using Iterator = typename C::const_iterator;
using RIterator = typename C::const_reverse_iterator;
using Size = typename C::size_type;
using Type = typename C::value_type;
Column(const MetaColumn& metaColumn, Container* pData):
_metaColumn(metaColumn),
_pData(pData)
/// Creates the Column.
{
if (!_pData)
throw NullPointerException("Container pointer must point to valid storage.");
}
Column(const Column& col):
_metaColumn(col._metaColumn),
_pData(col._pData)
/// Creates the Column.
{
}
Column(Column&& col) noexcept:
_metaColumn(std::move(col._metaColumn)),
_pData(std::move(col._pData))
/// Creates the Column.
{
}
~Column()
/// Destroys the Column.
{
}
Column& operator = (const Column& col)
/// Assignment operator.
{
Column tmp(col);
swap(tmp);
return *this;
}
Column& operator = (Column&& col) noexcept
/// Assignment operator.
{
_metaColumn = std::move(col._metaColumn);
_pData = std::move(col._pData);
return *this;
}
void swap(Column& other)
/// Swaps the column with another one.
{
using std::swap;
swap(_metaColumn, other._metaColumn);
swap(_pData, other._pData);
}
Container& data()
/// Returns reference to contained data.
{
return *_pData;
}
const Type& value(std::size_t row) const
/// Returns the field value in specified row.
{
try
{
return _pData->at(row);
}
catch (std::out_of_range& ex)
{
throw RangeException(ex.what());
}
}
const Type& operator [] (std::size_t row) const
/// Returns the field value in specified row.
{
return value(row);
}
Size rowCount() const
/// Returns number of rows.
{
return _pData->size();
}
void reset()
/// Clears and shrinks the storage.
{
Container().swap(*_pData);
}
const std::string& name() const
/// Returns column name.
{
return _metaColumn.name();
}
std::size_t length() const
/// Returns column maximum length.
{
return _metaColumn.length();
}
std::size_t precision() const
/// Returns column precision.
/// Valid for floating point fields only (zero for other data types).
{
return _metaColumn.precision();
}
std::size_t position() const
/// Returns column position.
{
return _metaColumn.position();
}
MetaColumn::ColumnDataType type() const
/// Returns column type.
{
return _metaColumn.type();
}
Iterator begin() const
/// Returns iterator pointing to the beginning of data storage vector.
{
return _pData->begin();
}
Iterator end() const
/// Returns iterator pointing to the end of data storage vector.
{
return _pData->end();
}
private:
Column();
MetaColumn _metaColumn;
ContainerPtr _pData;
};
template <>
class Column<std::vector<bool>>
/// The std::vector<bool> specialization for the Column class.
///
/// This specialization is necessary due to the nature of std::vector<bool>.
/// For details, see the standard library implementation of vector<bool>
/// or
/// S. Meyers: "Effective STL" (Copyright Addison-Wesley 2001),
/// Item 18: "Avoid using vector<bool>."
///
/// The workaround employed here is using deque<bool> as an
/// internal "companion" container kept in sync with the vector<bool>
/// column data.
{
public:
using Container = std::vector<bool>;
using ContainerPtr = Poco::SharedPtr<Container>;
using Iterator = Container::const_iterator;
using RIterator = Container::const_reverse_iterator;
using Size = Container::size_type;
Column(const MetaColumn& metaColumn, Container* pData):
_metaColumn(metaColumn),
_pData(pData)
/// Creates the Column.
{
poco_check_ptr (_pData);
_deque.assign(_pData->begin(), _pData->end());
}
Column(const Column& col):
_metaColumn(col._metaColumn),
_pData(col._pData)
/// Creates the Column.
{
_deque.assign(_pData->begin(), _pData->end());
}
~Column()
/// Destroys the Column.
{
}
Column& operator = (const Column& col)
/// Assignment operator.
{
Column tmp(col);
swap(tmp);
return *this;
}
void swap(Column& other)
/// Swaps the column with another one.
{
using std::swap;
swap(_metaColumn, other._metaColumn);
swap(_pData, other._pData);
swap(_deque, other._deque);
}
Container& data()
/// Returns reference to contained data.
{
return *_pData;
}
const bool& value(std::size_t row) const
/// Returns the field value in specified row.
{
if (_deque.size() < _pData->size())
_deque.resize(_pData->size());
try
{
return _deque.at(row) = _pData->at(row);
}
catch (std::out_of_range& ex)
{
throw RangeException(ex.what());
}
}
const bool& operator [] (std::size_t row) const
/// Returns the field value in specified row.
{
return value(row);
}
Size rowCount() const
/// Returns number of rows.
{
return _pData->size();
}
void reset()
/// Clears and shrinks the storage.
{
Container().swap(*_pData);
_deque.clear();
}
const std::string& name() const
/// Returns column name.
{
return _metaColumn.name();
}
std::size_t length() const
/// Returns column maximum length.
{
return _metaColumn.length();
}
std::size_t precision() const
/// Returns column precision.
/// Valid for floating point fields only (zero for other data types).
{
return _metaColumn.precision();
}
std::size_t position() const
/// Returns column position.
{
return _metaColumn.position();
}
MetaColumn::ColumnDataType type() const
/// Returns column type.
{
return _metaColumn.type();
}
Iterator begin() const
/// Returns iterator pointing to the beginning of data storage vector.
{
return _pData->begin();
}
Iterator end() const
/// Returns iterator pointing to the end of data storage vector.
{
return _pData->end();
}
private:
Column();
MetaColumn _metaColumn;
ContainerPtr _pData;
mutable std::deque<bool> _deque;
};
template <class T>
class Column<std::list<T>>
/// Column specialization for std::list
{
public:
using Container = std::list<T>;
using ContainerPtr = Poco::SharedPtr<Container>;
using Iterator = typename Container::const_iterator;
using RIterator = typename Container::const_reverse_iterator;
using Size = typename Container::size_type;
Column(const MetaColumn& metaColumn, std::list<T>* pData):
_metaColumn(metaColumn),
_pData(pData)
/// Creates the Column.
{
poco_check_ptr (_pData);
}
Column(const Column& col):
_metaColumn(col._metaColumn),
_pData(col._pData)
/// Creates the Column.
{
}
~Column()
/// Destroys the Column.
{
}
Column& operator = (const Column& col)
/// Assignment operator.
{
Column tmp(col);
swap(tmp);
return *this;
}
void swap(Column& other)
/// Swaps the column with another one.
{
using std::swap;
swap(_metaColumn, other._metaColumn);
swap(_pData, other._pData);
}
Container& data()
/// Returns reference to contained data.
{
return *_pData;
}
const T& value(std::size_t row) const
/// Returns the field value in specified row.
/// This is the std::list specialization and std::list
/// is not the optimal solution for cases where random
/// access is needed.
/// However, to allow for compatibility with other
/// containers, this functionality is provided here.
/// To alleviate the problem, an effort is made
/// to start iteration from beginning or end,
/// depending on the position requested.
{
if (row <= (std::size_t) (_pData->size() / 2))
{
Iterator it = _pData->begin();
Iterator end = _pData->end();
for (int i = 0; it != end; ++it, ++i)
if (i == row) return *it;
}
else
{
row = _pData->size() - row;
RIterator it = _pData->rbegin();
RIterator end = _pData->rend();
for (int i = 1; it != end; ++it, ++i)
if (i == row) return *it;
}
throw RangeException("Invalid row number.");
}
const T& operator [] (std::size_t row) const
/// Returns the field value in specified row.
{
return value(row);
}
Size rowCount() const
/// Returns number of rows.
{
return _pData->size();
}
void reset()
/// Clears the storage.
{
_pData->clear();
}
const std::string& name() const
/// Returns column name.
{
return _metaColumn.name();
}
std::size_t length() const
/// Returns column maximum length.
{
return _metaColumn.length();
}
std::size_t precision() const
/// Returns column precision.
/// Valid for floating point fields only (zero for other data types).
{
return _metaColumn.precision();
}
std::size_t position() const
/// Returns column position.
{
return _metaColumn.position();
}
MetaColumn::ColumnDataType type() const
/// Returns column type.
{
return _metaColumn.type();
}
Iterator begin() const
/// Returns iterator pointing to the beginning of data storage vector.
{
return _pData->begin();
}
Iterator end() const
/// Returns iterator pointing to the end of data storage vector.
{
return _pData->end();
}
private:
Column();
MetaColumn _metaColumn;
ContainerPtr _pData;
};
template <typename C>
inline void swap(Column<C>& c1, Column<C>& c2)
{
c1.swap(c2);
}
} } // namespace Poco::Data
#endif // Data_Column_INCLUDED

View File

@ -0,0 +1,56 @@
//
// Connector.h
//
// Library: Data
// Package: DataCore
// Module: Connector
//
// Definition of the Connector class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_Connector_INCLUDED
#define Data_Connector_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/SessionImpl.h"
#include "Poco/AutoPtr.h"
namespace Poco {
namespace Data {
class Data_API Connector
/// A Connector creates SessionImpl objects.
///
/// Every connector library (like the SQLite or the ODBC connector)
/// provides a subclass of this class, an instance of which is
/// registered with the SessionFactory.
{
public:
Connector();
/// Creates the Connector.
virtual ~Connector();
/// Destroys the Connector.
virtual const std::string& name() const = 0;
/// Returns the name associated with this connector.
virtual Poco::AutoPtr<SessionImpl> createSession(const std::string& connectionString,
std::size_t timeout = SessionImpl::LOGIN_TIMEOUT_DEFAULT) = 0;
/// Create a SessionImpl object and initialize it with the given connectionString.
};
} } // namespace Poco::Data
#endif // Data_Connector_INCLUDED

View File

@ -0,0 +1,36 @@
//
// Data.h
//
// Library: Data
// Package: DataCore
// Module: Constants
//
// Constant definitions for the Poco Data library.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_Constants_INCLUDED
#define Data_Constants_INCLUDED
#undef max
#include <limits>
#include <cstddef>
namespace Poco {
namespace Data {
static const std::size_t POCO_DATA_INVALID_ROW = std::numeric_limits<std::size_t>::max();
} } // namespace Poco::Data
#endif // Data_Constants_INCLUDED

View File

@ -0,0 +1,62 @@
//
// Data.h
//
// Library: Data
// Package: DataCore
// Module: Data
//
// Basic definitions for the Poco Data library.
// This file must be the first file included by every other Data
// header file.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_Data_INCLUDED
#define Data_Data_INCLUDED
#include "Poco/Foundation.h"
//
// The following block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the Data_EXPORTS
// symbol defined on the command line. this symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// Data_API functions as being imported from a DLL, wheras this DLL sees symbols
// defined with this macro as being exported.
//
#if defined(_WIN32) && defined(POCO_DLL)
#if defined(Data_EXPORTS)
#define Data_API __declspec(dllexport)
#else
#define Data_API __declspec(dllimport)
#endif
#endif
#if !defined(Data_API)
#if !defined(POCO_NO_GCC_API_ATTRIBUTE) && defined (__GNUC__) && (__GNUC__ >= 4)
#define Data_API __attribute__ ((visibility ("default")))
#else
#define Data_API
#endif
#endif
//
// Automatically link Data library.
//
#if defined(_MSC_VER)
#if !defined(POCO_NO_AUTOMATIC_LIBS) && !defined(Data_EXPORTS)
#pragma comment(lib, "PocoData" POCO_LIB_SUFFIX)
#endif
#endif
#endif // Data_Data_INCLUDED

View File

@ -0,0 +1,50 @@
//
// DataException.h
//
// Library: Data
// Package: DataCore
// Module: DataException
//
// Definition of the DataException class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_DataException_INCLUDED
#define Data_DataException_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Exception.h"
namespace Poco {
namespace Data {
POCO_DECLARE_EXCEPTION(Data_API, DataException, Poco::IOException)
POCO_DECLARE_EXCEPTION(Data_API, RowDataMissingException, DataException)
POCO_DECLARE_EXCEPTION(Data_API, UnknownDataBaseException, DataException)
POCO_DECLARE_EXCEPTION(Data_API, UnknownTypeException, DataException)
POCO_DECLARE_EXCEPTION(Data_API, ExecutionException, DataException)
POCO_DECLARE_EXCEPTION(Data_API, BindingException, DataException)
POCO_DECLARE_EXCEPTION(Data_API, ExtractException, DataException)
POCO_DECLARE_EXCEPTION(Data_API, LimitException, DataException)
POCO_DECLARE_EXCEPTION(Data_API, NotSupportedException, DataException)
POCO_DECLARE_EXCEPTION(Data_API, SessionUnavailableException, DataException)
POCO_DECLARE_EXCEPTION(Data_API, SessionPoolExhaustedException, DataException)
POCO_DECLARE_EXCEPTION(Data_API, SessionPoolExistsException, DataException)
POCO_DECLARE_EXCEPTION(Data_API, NoDataException, DataException)
POCO_DECLARE_EXCEPTION(Data_API, LengthExceededException, DataException)
POCO_DECLARE_EXCEPTION(Data_API, ConnectionFailedException, DataException)
POCO_DECLARE_EXCEPTION(Data_API, NotConnectedException, DataException)
} } // namespace Poco::Data
#endif // Data_DataException_INCLUDED

View File

@ -0,0 +1,225 @@
//
// Date.h
//
// Library: Data
// Package: DataCore
// Module: Date
//
// Definition of the Date class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_Date_INCLUDED
#define Data_Date_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Dynamic/VarHolder.h"
#include "Poco/Exception.h"
namespace Poco {
class DateTime;
namespace Dynamic {
class Var;
}
namespace Data {
class Time;
class Data_API Date
/// Date class wraps a DateTime and exposes date related interface.
/// The purpose of this class is binding/extraction support for date fields.
{
public:
Date();
/// Creates the Date
Date(int year, int month, int day);
/// Creates the Date
Date(const DateTime& dt);
/// Creates the Date from DateTime
~Date();
/// Destroys the Date.
int year() const;
/// Returns the year.
int month() const;
/// Returns the month.
int day() const;
/// Returns the day.
void assign(int year, int month, int day);
/// Assigns date.
Date& operator = (const Date& d);
/// Assignment operator for Date.
Date& operator = (const DateTime& dt);
/// Assignment operator for DateTime.
Date& operator = (const Poco::Dynamic::Var& var);
/// Assignment operator for Var.
bool operator == (const Date& date) const;
/// Equality operator.
bool operator != (const Date& date) const;
/// Inequality operator.
bool operator < (const Date& date) const;
/// Less then operator.
bool operator > (const Date& date) const;
/// Greater then operator.
private:
int _year;
int _month;
int _day;
};
//
// inlines
//
inline int Date::year() const
{
return _year;
}
inline int Date::month() const
{
return _month;
}
inline int Date::day() const
{
return _day;
}
inline Date& Date::operator = (const Date& d)
{
assign(d.year(), d.month(), d.day());
return *this;
}
inline Date& Date::operator = (const DateTime& dt)
{
assign(dt.year(), dt.month(), dt.day());
return *this;
}
inline bool Date::operator == (const Date& date) const
{
return _year == date.year() &&
_month == date.month() &&
_day == date.day();
}
inline bool Date::operator != (const Date& date) const
{
return !(*this == date);
}
inline bool Date::operator > (const Date& date) const
{
return !(*this == date) && !(*this < date);
}
} } // namespace Poco::Data
//
// VarHolderImpl<Date>
//
namespace Poco {
namespace Dynamic {
template <>
class VarHolderImpl<Poco::Data::Date>: public VarHolder
{
public:
VarHolderImpl(const Poco::Data::Date& val): _val(val)
{
}
~VarHolderImpl()
{
}
const std::type_info& type() const
{
return typeid(Poco::Data::Date);
}
void convert(Poco::Timestamp& val) const
{
DateTime dt;
dt.assign(_val.year(), _val.month(), _val.day());
val = dt.timestamp();
}
void convert(Poco::DateTime& val) const
{
val.assign(_val.year(), _val.month(), _val.day());
}
void convert(Poco::LocalDateTime& val) const
{
val.assign(_val.year(), _val.month(), _val.day());
}
void convert(std::string& val) const
{
DateTime dt(_val.year(), _val.month(), _val.day());
val = DateTimeFormatter::format(dt, "%Y/%m/%d");
}
VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const
{
return cloneHolder(pVarHolder, _val);
}
const Poco::Data::Date& value() const
{
return _val;
}
private:
VarHolderImpl();
Poco::Data::Date _val;
};
} } // namespace Poco::Dynamic
#endif // Data_Date_INCLUDED

View File

@ -0,0 +1,47 @@
//
// DynamicDateTime.h
//
// Library: Data
// Package: DataCore
// Module: DynamicDateTime
//
// Definition of the Date and Time cast operators for Poco::Dynamic::Var.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_DynamicDateTime_INCLUDED
#define Data_DynamicDateTime_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/Date.h"
#include "Poco/Data/Time.h"
#include "Poco/Dynamic/Var.h"
namespace Poco {
namespace Data {
class Date;
class Time;
} } // namespace Poco::Data
namespace Poco {
namespace Dynamic {
template <> Data_API Var::operator Poco::Data::Date () const;
template <> Data_API Var::operator Poco::Data::Time () const;
} } // namespace Poco::Dynamic
#endif // Data_DynamicDateTime_INCLUDED

View File

@ -0,0 +1,45 @@
//
// DynamicLOB.h
//
// Library: Data
// Package: DataCore
// Module: DynamicLOB
//
// Definition of the Poco::Dynamic::Var LOB cast operators.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_DynamicLOB_INCLUDED
#define Data_DynamicLOB_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/LOB.h"
#include "Poco/Dynamic/Var.h"
namespace Poco {
namespace Data {
template <typename T> class LOB;
using BLOB = LOB<unsigned char>;
using CLOB = LOB<char>;
} } // namespace Poco::Data
namespace Poco {
namespace Dynamic {
template <> Data_API Var::operator Poco::Data::CLOB () const;
template <> Data_API Var::operator Poco::Data::BLOB () const;
} } // namespace Poco::Dynamic
#endif // Data_DynamicLOB_INCLUDED

View File

@ -0,0 +1,868 @@
//
// Extraction.h
//
// Library: Data
// Package: DataCore
// Module: Extraction
//
// Definition of the Extraction class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_Extraction_INCLUDED
#define Data_Extraction_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/AbstractExtraction.h"
#include "Poco/Data/Preparation.h"
#include "Poco/Data/TypeHandler.h"
#include "Poco/Data/Column.h"
#include "Poco/Data/Position.h"
#include "Poco/Data/DataException.h"
#include <set>
#include <vector>
#include <list>
#include <deque>
#include <map>
#include <cstddef>
namespace Poco {
namespace Data {
template <class T>
class Extraction: public AbstractExtraction
/// Concrete Data Type specific extraction of values from a query result set.
{
public:
using ValType = T;
using ValPtr = SharedPtr<ValType>;
using Type = Extraction<ValType>;
using Ptr = SharedPtr<Type>;
Extraction(T& result, const Position& pos = Position(0)):
AbstractExtraction(Limit::LIMIT_UNLIMITED, pos.value()),
_rResult(result),
_default(),
_extracted(false),
_null(false)
/// Creates an Extraction object at specified position.
/// Uses an empty object T as default value.
{
}
Extraction(T& result, const T& def, const Position& pos = Position(0)):
AbstractExtraction(Limit::LIMIT_UNLIMITED, pos.value()),
_rResult(result),
_default(def),
_extracted(false),
_null(false)
/// Creates an Extraction object at specified position.
/// Uses the provided def object as default value.
{
}
~Extraction()
/// Destroys the Extraction object.
{
}
std::size_t numOfColumnsHandled() const
{
return TypeHandler<T>::size();
}
std::size_t numOfRowsHandled() const
{
return _extracted ? 1u : 0;
}
std::size_t numOfRowsAllowed() const
{
return 1u;
}
bool isNull(std::size_t /*row*/ = 0) const
{
return _null;
}
std::size_t extract(std::size_t pos)
{
if (_extracted) throw ExtractException("value already extracted");
_extracted = true;
AbstractExtractor::Ptr pExt = getExtractor();
TypeHandler<T>::extract(pos, _rResult, _default, pExt);
_null = isValueNull<T>(_rResult, pExt->isNull(pos));
return 1u;
}
void reset()
{
_extracted = false;
}
bool canExtract() const
{
return !_extracted;
}
AbstractPreparation::Ptr createPreparation(AbstractPreparator::Ptr& pPrep, std::size_t pos)
{
return new Preparation<T>(pPrep, pos, _rResult);
}
private:
T& _rResult;
T _default;
bool _extracted;
bool _null;
};
template <class T>
class Extraction<std::vector<T>>: public AbstractExtraction
/// Vector Data Type specialization for extraction of values from a query result set.
{
public:
using ValType = std::vector<T>;
using ValPtr = SharedPtr<ValType>;
using Type = Extraction<ValType>;
using Ptr = SharedPtr<Type>;
Extraction(std::vector<T>& result, const Position& pos = Position(0)):
AbstractExtraction(Limit::LIMIT_UNLIMITED, pos.value()),
_rResult(result),
_default()
{
_rResult.clear();
}
Extraction(std::vector<T>& result, const T& def, const Position& pos = Position(0)):
AbstractExtraction(Limit::LIMIT_UNLIMITED, pos.value()),
_rResult(result),
_default(def)
{
_rResult.clear();
}
virtual ~Extraction()
{
}
std::size_t numOfColumnsHandled() const
{
return TypeHandler<T>::size();
}
std::size_t numOfRowsHandled() const
{
return static_cast<std::size_t>(_rResult.size());
}
std::size_t numOfRowsAllowed() const
{
return getLimit();
}
bool isNull(std::size_t row) const
{
try
{
return _nulls.at(row);
}
catch (std::out_of_range& ex)
{
throw RangeException(ex.what());
}
}
std::size_t extract(std::size_t pos)
{
AbstractExtractor::Ptr pExt = getExtractor();
_rResult.push_back(_default);
TypeHandler<T>::extract(pos, _rResult.back(), _default, pExt);
_nulls.push_back(isValueNull(_rResult.back(), pExt->isNull(pos)));
return 1u;
}
AbstractPreparation::Ptr createPreparation(AbstractPreparator::Ptr& pPrep, std::size_t pos)
{
return new Preparation<T>(pPrep, pos, _default);
}
void reset()
{
_nulls.clear();
}
protected:
const std::vector<T>& result() const
{
return _rResult;
}
private:
std::vector<T>& _rResult;
T _default;
std::deque<bool> _nulls;
};
template <>
class Extraction<std::vector<bool>>: public AbstractExtraction
/// Vector bool specialization for extraction of values from a query result set.
{
public:
using ValType = std::vector<bool>;
using ValPtr = SharedPtr<ValType>;
using Type = Extraction<ValType>;
using Ptr = SharedPtr<Type>;
Extraction(std::vector<bool>& result, const Position& pos = Position(0)):
AbstractExtraction(Limit::LIMIT_UNLIMITED, pos.value()),
_rResult(result),
_default()
{
_rResult.clear();
}
Extraction(std::vector<bool>& result, const bool& def, const Position& pos = Position(0)):
AbstractExtraction(Limit::LIMIT_UNLIMITED, pos.value()),
_rResult(result),
_default(def)
{
_rResult.clear();
}
virtual ~Extraction()
{
}
std::size_t numOfColumnsHandled() const
{
return TypeHandler<bool>::size();
}
std::size_t numOfRowsHandled() const
{
return static_cast<std::size_t>(_rResult.size());
}
std::size_t numOfRowsAllowed() const
{
return getLimit();
}
bool isNull(std::size_t row) const
{
try
{
return _nulls.at(row);
}
catch (std::out_of_range& ex)
{
throw RangeException(ex.what());
}
}
std::size_t extract(std::size_t pos)
{
AbstractExtractor::Ptr pExt = getExtractor();
bool tmp = _default;
TypeHandler<bool>::extract(pos, tmp, _default, pExt);
_rResult.push_back(tmp);
_nulls.push_back(pExt->isNull(pos));
return 1u;
}
AbstractPreparation::Ptr createPreparation(AbstractPreparator::Ptr& pPrep, std::size_t pos)
{
return new Preparation<bool>(pPrep, pos, _default);
}
void reset()
{
_nulls.clear();
}
protected:
const std::vector<bool>& result() const
{
return _rResult;
}
private:
std::vector<bool>& _rResult;
bool _default;
std::deque<bool> _nulls;
};
template <class T>
class Extraction<std::list<T>>: public AbstractExtraction
/// List Data Type specialization for extraction of values from a query result set.
{
public:
using ValType = std::list<T>;
using ValPtr = SharedPtr<ValType>;
using Type = Extraction<ValType>;
using Ptr = SharedPtr<Type>;
Extraction(std::list<T>& result, const Position& pos = Position(0)):
AbstractExtraction(Limit::LIMIT_UNLIMITED, pos.value()),
_rResult(result),
_default()
{
_rResult.clear();
}
Extraction(std::list<T>& result, const T& def, const Position& pos = Position(0)):
AbstractExtraction(Limit::LIMIT_UNLIMITED, pos.value()),
_rResult(result),
_default(def)
{
_rResult.clear();
}
virtual ~Extraction()
{
}
std::size_t numOfColumnsHandled() const
{
return TypeHandler<T>::size();
}
std::size_t numOfRowsHandled() const
{
return _rResult.size();
}
std::size_t numOfRowsAllowed() const
{
return getLimit();
}
bool isNull(std::size_t row) const
{
try
{
return _nulls.at(row);
}
catch (std::out_of_range& ex)
{
throw RangeException(ex.what());
}
}
std::size_t extract(std::size_t pos)
{
AbstractExtractor::Ptr pExt = getExtractor();
_rResult.push_back(_default);
TypeHandler<T>::extract(pos, _rResult.back(), _default, pExt);
_nulls.push_back(isValueNull(_rResult.back(), pExt->isNull(pos)));
return 1u;
}
AbstractPreparation::Ptr createPreparation(AbstractPreparator::Ptr& pPrep, std::size_t pos)
{
return new Preparation<T>(pPrep, pos, _default);
}
void reset()
{
_nulls.clear();
}
protected:
const std::list<T>& result() const
{
return _rResult;
}
private:
std::list<T>& _rResult;
T _default;
std::deque<bool> _nulls;
};
template <class T>
class Extraction<std::deque<T>>: public AbstractExtraction
/// Deque Data Type specialization for extraction of values from a query result set.
{
public:
using ValType = std::deque<T>;
using ValPtr = SharedPtr<ValType>;
using Type = Extraction<ValType>;
using Ptr = SharedPtr<Type>;
Extraction(std::deque<T>& result, const Position& pos = Position(0)):
AbstractExtraction(Limit::LIMIT_UNLIMITED, pos.value()),
_rResult(result),
_default()
{
_rResult.clear();
}
Extraction(std::deque<T>& result, const T& def, const Position& pos = Position(0)):
AbstractExtraction(Limit::LIMIT_UNLIMITED, pos.value()),
_rResult(result),
_default(def)
{
_rResult.clear();
}
virtual ~Extraction()
{
}
std::size_t numOfColumnsHandled() const
{
return TypeHandler<T>::size();
}
std::size_t numOfRowsHandled() const
{
return _rResult.size();
}
std::size_t numOfRowsAllowed() const
{
return getLimit();
}
bool isNull(std::size_t row) const
{
try
{
return _nulls.at(row);
}
catch (std::out_of_range& ex)
{
throw RangeException(ex.what());
}
}
std::size_t extract(std::size_t pos)
{
AbstractExtractor::Ptr pExt = getExtractor();
_rResult.push_back(_default);
TypeHandler<T>::extract(pos, _rResult.back(), _default, pExt);
_nulls.push_back(isValueNull(_rResult.back(), pExt->isNull(pos)));
return 1u;
}
AbstractPreparation::Ptr createPreparation(AbstractPreparator::Ptr& pPrep, std::size_t pos)
{
return new Preparation<T>(pPrep, pos, _default);
}
void reset()
{
_nulls.clear();
}
protected:
const std::deque<T>& result() const
{
return _rResult;
}
private:
std::deque<T>& _rResult;
T _default;
std::deque<bool> _nulls;
};
template <class C>
class InternalExtraction: public Extraction<C>
/// Container Data Type specialization extension for extraction of values from a query result set.
///
/// This class is intended for PocoData internal use - it is used by StatementImpl
/// to automaticaly create internal Extraction in cases when statement returns data and no external storage
/// was supplied. It is later used by RecordSet to retrieve the fetched data after statement execution.
/// It takes ownership of the Column pointer supplied as constructor argument. Column object, in turn
/// owns the data container pointer.
///
/// InternalExtraction objects can not be copied or assigned.
{
public:
using ValType = typename C::value_type;
using ValPtr = SharedPtr<ValType>;
using Type = Extraction<ValType>;
using Ptr = SharedPtr<Type>;
InternalExtraction(C& result, Column<C>* pColumn, const Position& pos = Position(0)):
Extraction<C>(result, ValType(), pos),
_pColumn(pColumn)
/// Creates InternalExtraction.
{
}
~InternalExtraction()
/// Destroys InternalExtraction.
{
delete _pColumn;
}
void reset()
{
Extraction<C>::reset();
_pColumn->reset();
}
const ValType& value(int index) const
{
try
{
return Extraction<C>::result().at(index);
}
catch (std::out_of_range& ex)
{
throw RangeException(ex.what());
}
}
bool isNull(std::size_t row) const
{
return Extraction<C>::isNull(row);
}
const Column<C>& column() const
{
return *_pColumn;
}
private:
InternalExtraction();
InternalExtraction(const InternalExtraction&);
InternalExtraction& operator = (const InternalExtraction&);
Column<C>* _pColumn;
};
template <class T>
class Extraction<std::set<T>>: public AbstractExtraction
/// Set Data Type specialization for extraction of values from a query result set.
{
public:
using ValType = std::set<T>;
using ValPtr = SharedPtr<ValType>;
using Type = Extraction<ValType>;
using Ptr = SharedPtr<Type>;
using Iterator = typename ValType::iterator;
Extraction(std::set<T>& result, const Position& pos = Position(0)):
AbstractExtraction(Limit::LIMIT_UNLIMITED, pos.value()),
_rResult(result),
_default()
{
_rResult.clear();
}
Extraction(std::set<T>& result, const T& def, const Position& pos = Position(0)):
AbstractExtraction(Limit::LIMIT_UNLIMITED, pos.value()),
_rResult(result),
_default(def)
{
_rResult.clear();
}
~Extraction()
{
}
std::size_t numOfColumnsHandled() const
{
return TypeHandler<T>::size();
}
std::size_t numOfRowsHandled() const
{
return static_cast<std::size_t>(_rResult.size());
}
std::size_t numOfRowsAllowed() const
{
return getLimit();
}
std::size_t extract(std::size_t pos)
{
T tmp;
TypeHandler<T>::extract(pos, tmp, _default, getExtractor());
_rResult.insert(tmp);
return 1u;
}
AbstractPreparation::Ptr createPreparation(AbstractPreparator::Ptr& pPrep, std::size_t pos)
{
return new Preparation<T>(pPrep, pos, _default);
}
private:
std::set<T>& _rResult;
T _default;
};
template <class T>
class Extraction<std::multiset<T>>: public AbstractExtraction
/// Multiset Data Type specialization for extraction of values from a query result set.
{
public:
using ValType = std::multiset<T>;
using ValPtr = SharedPtr<ValType>;
using Type = Extraction<ValType>;
using Ptr = SharedPtr<Type>;
Extraction(std::multiset<T>& result, const Position& pos = Position(0)):
AbstractExtraction(Limit::LIMIT_UNLIMITED, pos.value()),
_rResult(result),
_default()
{
_rResult.clear();
}
Extraction(std::multiset<T>& result, const T& def, const Position& pos = Position(0)):
AbstractExtraction(Limit::LIMIT_UNLIMITED, pos.value()),
_rResult(result),
_default(def)
{
_rResult.clear();
}
~Extraction()
{
}
std::size_t numOfColumnsHandled() const
{
return TypeHandler<T>::size();
}
std::size_t numOfRowsHandled() const
{
return static_cast<std::size_t>(_rResult.size());
}
std::size_t numOfRowsAllowed() const
{
return getLimit();
}
std::size_t extract(std::size_t pos)
{
T tmp;
TypeHandler<T>::extract(pos, tmp, _default, getExtractor());
_rResult.insert(tmp);
return 1u;
}
AbstractPreparation::Ptr createPreparation(AbstractPreparator::Ptr& pPrep, std::size_t pos)
{
return new Preparation<T>(pPrep, pos, _default);
}
private:
std::multiset<T>& _rResult;
T _default;
};
template <class K, class V>
class Extraction<std::map<K, V>>: public AbstractExtraction
/// Map Data Type specialization for extraction of values from a query result set.
{
public:
using ValType = std::map<K, V>;
using ValPtr = SharedPtr<ValType>;
using Type = Extraction<ValType>;
using Ptr = SharedPtr<Type>;
Extraction(std::map<K, V>& result, const Position& pos = Position(0)):
AbstractExtraction(Limit::LIMIT_UNLIMITED, pos.value()),
_rResult(result),
_default()
{
_rResult.clear();
}
Extraction(std::map<K, V>& result, const V& def, const Position& pos = Position(0)):
AbstractExtraction(Limit::LIMIT_UNLIMITED, pos.value()),
_rResult(result),
_default(def)
{
_rResult.clear();
}
~Extraction()
{
}
std::size_t numOfColumnsHandled() const
{
return TypeHandler<V>::size();
}
std::size_t numOfRowsHandled() const
{
return static_cast<std::size_t>(_rResult.size());
}
std::size_t numOfRowsAllowed() const
{
return getLimit();
}
std::size_t extract(std::size_t pos)
{
V tmp;
TypeHandler<V>::extract(pos, tmp, _default, getExtractor());
_rResult.insert(std::make_pair(tmp(), tmp));
return 1u;
}
AbstractPreparation::Ptr createPreparation(AbstractPreparator::Ptr& pPrep, std::size_t pos)
{
return new Preparation<V>(pPrep, pos, _default);
}
private:
std::map<K, V>& _rResult;
V _default;
};
template <class K, class V>
class Extraction<std::multimap<K, V>>: public AbstractExtraction
/// Multimap Data Type specialization for extraction of values from a query result set.
{
public:
using ValType = std::multimap<K, V>;
using ValPtr = SharedPtr<ValType>;
using Type = Extraction<ValType>;
using Ptr = SharedPtr<Type>;
Extraction(std::multimap<K, V>& result, const Position& pos = Position(0)):
AbstractExtraction(Limit::LIMIT_UNLIMITED, pos.value()),
_rResult(result),
_default()
{
_rResult.clear();
}
Extraction(std::multimap<K, V>& result, const V& def, const Position& pos = Position(0)):
AbstractExtraction(Limit::LIMIT_UNLIMITED, pos.value()),
_rResult(result),
_default(def)
{
_rResult.clear();
}
~Extraction()
{
}
std::size_t numOfColumnsHandled() const
{
return TypeHandler<V>::size();
}
std::size_t numOfRowsHandled() const
{
return static_cast<std::size_t>(_rResult.size());
}
std::size_t numOfRowsAllowed() const
{
return getLimit();
}
std::size_t extract(std::size_t pos)
{
V tmp;
TypeHandler<V>::extract(pos, tmp, _default, getExtractor());
_rResult.insert(std::make_pair(tmp(), tmp));
return 1u;
}
AbstractPreparation::Ptr createPreparation(AbstractPreparator::Ptr& pPrep, std::size_t pos)
{
return new Preparation<V>(pPrep, pos, _default);
}
private:
std::multimap<K, V>& _rResult;
V _default;
};
namespace Keywords {
template <typename T>
inline AbstractExtraction::Ptr into(T& t)
/// Convenience function to allow for a more compact creation of an extraction object.
{
return new Extraction<T>(t);
}
template <typename T>
inline AbstractExtraction::Ptr into(T& t, const Position& pos)
/// Convenience function to allow for a more compact creation of an extraction object
/// with multiple recordset support.
{
return new Extraction<T>(t, pos);
}
template <typename T>
inline AbstractExtraction::Ptr into(T& t, const Position& pos, const T& def)
/// Convenience function to allow for a more compact creation of an extraction object
/// with multiple recordset support and the given default
{
return new Extraction<T>(t, def, pos);
}
inline AbstractExtractionVecVec& into(AbstractExtractionVecVec& evv)
/// Convenience dummy function (for syntax purposes only).
{
return evv;
}
inline AbstractExtractionVec& into(AbstractExtractionVec& ev)
/// Convenience dummy function (for syntax purposes only).
{
return ev;
}
} // namespace Keywords
} } // namespace Poco::Data
#endif // Data_Extraction_INCLUDED

317
vendor/POCO/Data/include/Poco/Data/LOB.h vendored Normal file
View File

@ -0,0 +1,317 @@
//
// LOB.h
//
// Library: Data
// Package: DataCore
// Module: LOB
//
// Definition of the LOB class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_LOB_INCLUDED
#define Data_LOB_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/SharedPtr.h"
#include "Poco/Dynamic/VarHolder.h"
#include "Poco/Exception.h"
#include <vector>
#include <algorithm>
namespace Poco {
namespace Data {
template <typename T>
class LOB
/// Representation of a Large OBject.
///
/// A LOB can hold arbitrary data.
/// The maximum size depends on the underlying database.
///
/// The LOBInputStream and LOBOutputStream classes provide
/// a convenient way to access the data in a LOB.
{
public:
using Iterator = typename std::vector<T>::const_iterator;
using ValueType = T;
using Container = std::vector<T>;
using ContentPtr = Poco::SharedPtr<Container>;
LOB(): _pContent(new std::vector<T>())
/// Creates an empty LOB.
{
}
LOB(const std::vector<T>& content):
_pContent(new std::vector<T>(content))
/// Creates the LOB, content is deep-copied.
{
}
LOB(const T* const pContent, std::size_t size):
_pContent(new std::vector<T>(pContent, pContent + size))
/// Creates the LOB by deep-copying pContent.
{
}
LOB(const std::basic_string<T>& content):
_pContent(new std::vector<T>(content.begin(), content.end()))
/// Creates a LOB from a string.
{
}
LOB(const LOB& other): _pContent(other._pContent)
/// Creates a LOB by copying another one.
{
}
LOB(LOB&& other) noexcept: _pContent(std::move(other._pContent))
{
}
~LOB()
/// Destroys the LOB.
{
}
LOB& operator = (const LOB& other)
/// Assignment operator.
{
LOB tmp(other);
swap(tmp);
return *this;
}
LOB& operator = (LOB&& other) noexcept
{
_pContent = std::move(other._pContent);
return *this;
}
bool operator == (const LOB& other) const
/// Compares for equality LOB by value.
{
return *_pContent == *other._pContent;
}
bool operator != (const LOB& other) const
/// Compares for inequality LOB by value.
{
return *_pContent != *other._pContent;
}
void swap(LOB& other)
/// Swaps the LOB with another one.
{
using std::swap;
swap(_pContent, other._pContent);
}
const std::vector<T>& content() const
/// Returns the content.
{
return *_pContent;
}
const T* rawContent() const
/// Returns the raw content.
///
/// If the LOB is empty, returns NULL.
{
if (_pContent->empty())
return 0;
else
return &(*_pContent)[0];
}
void assignVal(std::size_t count, const T& val)
/// Assigns raw content to internal storage.
{
ContentPtr tmp = new Container(count, val);
_pContent.swap(tmp);
}
void assignRaw(const T* ptr, std::size_t count)
/// Assigns raw content to internal storage.
{
poco_assert_dbg (ptr);
LOB tmp(ptr, count);
swap(tmp);
}
void appendRaw(const T* pChar, std::size_t count)
/// Assigns raw content to internal storage.
{
poco_assert_dbg (pChar);
_pContent->insert(_pContent->end(), pChar, pChar+count);
}
void clear(bool doCompact = false)
/// Clears the content of the blob.
/// If doCompact is true, trims the excess capacity.
{
_pContent->clear();
if (doCompact) compact();
}
void compact()
/// Trims the internal storage excess capacity.
{
std::vector<T>(*_pContent).swap(*_pContent);
}
Iterator begin() const
{
return _pContent->begin();
}
Iterator end() const
{
return _pContent->end();
}
std::size_t size() const
/// Returns the size of the LOB in bytes.
{
return static_cast<std::size_t>(_pContent->size());
}
private:
ContentPtr _pContent;
};
using BLOB = LOB<unsigned char>;
using CLOB = LOB<char>;
//
// inlines
//
template <typename T>
inline void swap(LOB<T>& b1, LOB<T>& b2)
{
b1.swap(b2);
}
} } // namespace Poco::Data
namespace std
{
template<>
inline void swap<Poco::Data::BLOB>(Poco::Data::BLOB& b1, Poco::Data::BLOB& b2) noexcept
/// Full template specalization of std:::swap for BLOB
{
b1.swap(b2);
}
template<>
inline void swap<Poco::Data::CLOB>(Poco::Data::CLOB& c1, Poco::Data::CLOB& c2) noexcept
/// Full template specalization of std:::swap for CLOB
{
c1.swap(c2);
}
}
//
// VarHolderImpl<LOB>
//
namespace Poco {
namespace Dynamic {
template <>
class VarHolderImpl<Poco::Data::BLOB>: public VarHolder
{
public:
VarHolderImpl(const Poco::Data::BLOB& val): _val(val)
{
}
~VarHolderImpl()
{
}
const std::type_info& type() const
{
return typeid(Poco::Data::BLOB);
}
void convert(std::string& val) const
{
val.assign(_val.begin(), _val.end());
}
VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const
{
return cloneHolder(pVarHolder, _val);
}
const Poco::Data::BLOB& value() const
{
return _val;
}
private:
VarHolderImpl();
Poco::Data::BLOB _val;
};
template <>
class VarHolderImpl<Poco::Data::CLOB>: public VarHolder
{
public:
VarHolderImpl(const Poco::Data::CLOB& val): _val(val)
{
}
~VarHolderImpl()
{
}
const std::type_info& type() const
{
return typeid(Poco::Data::CLOB);
}
void convert(std::string& val) const
{
val.assign(_val.begin(), _val.end());
}
VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const
{
return cloneHolder(pVarHolder, _val);
}
const Poco::Data::CLOB& value() const
{
return _val;
}
private:
VarHolderImpl();
Poco::Data::CLOB _val;
};
} } // namespace Poco::Dynamic
#endif // Data_LOB_INCLUDED

View File

@ -0,0 +1,150 @@
//
// LOBStream.h
//
// Library: Data
// Package: DataCore
// Module: LOBStream
//
// Definition of the LOBStream class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_LOBStream_INCLUDED
#define Data_LOBStream_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/UnbufferedStreamBuf.h"
#include "Poco/Data/LOB.h"
#include <istream>
#include <ostream>
namespace Poco {
namespace Data {
template <typename T>
class LOBStreamBuf: public BasicUnbufferedStreamBuf<T, std::char_traits<T>>
/// This is the streambuf class used for reading from and writing to a LOB.
{
public:
LOBStreamBuf(LOB<T>& lob): _lob(lob), _it(_lob.begin())
/// Creates LOBStreamBuf.
{
}
~LOBStreamBuf()
/// Destroys LOBStreamBuf.
{
}
protected:
using TraitsType = std::char_traits<T>;
using BaseType = BasicUnbufferedStreamBuf<T, TraitsType>;
typename BaseType::int_type readFromDevice()
{
if (_it != _lob.end())
return BaseType::charToInt(*_it++);
else
return -1;
}
typename BaseType::int_type writeToDevice(T c)
{
_lob.appendRaw(&c, 1);
return 1;
}
private:
LOB<T>& _lob;
typename LOB<T>::Iterator _it;
};
template <typename T>
class LOBIOS: public virtual std::ios
/// The base class for LOBInputStream and
/// LOBOutputStream.
///
/// This class is needed to ensure the correct initialization
/// order of the stream buffer and base classes.
{
public:
LOBIOS(LOB<T>& lob, openmode mode): _buf(lob)
/// Creates the LOBIOS with the given LOB.
{
poco_ios_init(&_buf);
}
~LOBIOS()
/// Destroys the LOBIOS.
{
}
LOBStreamBuf<T>* rdbuf()
/// Returns a pointer to the internal LOBStreamBuf.
{
return &_buf;
}
protected:
LOBStreamBuf<T> _buf;
};
template <typename T>
class LOBOutputStream: public LOBIOS<T>, public std::basic_ostream<T, std::char_traits<T>>
/// An output stream for writing to a LOB.
{
public:
LOBOutputStream(LOB<T>& lob):
LOBIOS<T>(lob, std::ios::out),
std::ostream(LOBIOS<T>::rdbuf())
/// Creates the LOBOutputStream with the given LOB.
{
}
~LOBOutputStream()
/// Destroys the LOBOutputStream.
{
}
};
template <typename T>
class LOBInputStream: public LOBIOS<T>, public std::basic_istream<T, std::char_traits<T>>
/// An input stream for reading from a LOB.
{
public:
LOBInputStream(LOB<T>& lob):
LOBIOS<T>(lob, std::ios::in),
std::istream(LOBIOS<T>::rdbuf())
/// Creates the LOBInputStream with the given LOB.
{
}
~LOBInputStream()
/// Destroys the LOBInputStream.
{
}
};
using BLOBOutputStream = LOBOutputStream<unsigned char>;
using CLOBOutputStream = LOBOutputStream<char>;
using BLOBInputStream = LOBInputStream<unsigned char>;
using CLOBInputStream = LOBInputStream<char>;
} } // namespace Poco::Data
#endif // Data_LOBStream_INCLUDED

View File

@ -0,0 +1,113 @@
//
// Limit.h
//
// Library: Data
// Package: DataCore
// Module: Limit
//
// Definition of the Limit class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_Limit_INCLUDED
#define Data_Limit_INCLUDED
#include "Poco/Data/Data.h"
namespace Poco {
namespace Data {
class Data_API Limit
/// Limit stores information how many rows a query should return.
{
public:
using SizeT = Poco::UInt32;
enum Type
{
LIMIT_UNLIMITED = ~((SizeT) 0)
};
Limit(SizeT value, bool hardLimit = false, bool isLowerLimit = false);
/// Creates the Limit.
///
/// Value contains the upper row hint, if hardLimit is set to true, the limit acts as a hard
/// border, ie. every query must return exactly value rows, returning more than value objects will throw an exception!
/// LowerLimits always act as hard-limits!
///
/// A value of LIMIT_UNLIMITED disables the limit.
~Limit();
/// Destroys the Limit.
SizeT value() const;
/// Returns the value of the limit
bool isHardLimit() const;
/// Returns true if the limit is a hard limit.
bool isLowerLimit() const;
/// Returns true if the limit is a lower limit, otherwise it is an upperLimit
bool operator == (const Limit& other) const;
/// Equality operator.
bool operator != (const Limit& other) const;
/// Inequality operator.
private:
SizeT _value;
bool _hardLimit;
bool _isLowerLimit;
};
//
// inlines
//
inline Poco::UInt32 Limit::value() const
{
return _value;
}
inline bool Limit::isHardLimit() const
{
return _hardLimit;
}
inline bool Limit::isLowerLimit() const
{
return _isLowerLimit;
}
inline bool Limit::operator == (const Limit& other) const
{
return other._value == _value &&
other._hardLimit == _hardLimit &&
other._isLowerLimit == _isLowerLimit;
}
inline bool Limit::operator != (const Limit& other) const
{
return other._value != _value ||
other._hardLimit != _hardLimit ||
other._isLowerLimit != _isLowerLimit;
}
} } // namespace Poco::Data
#endif // Data_Limit_INCLUDED

View File

@ -0,0 +1,203 @@
//
// MetaColumn.h
//
// Library: Data
// Package: DataCore
// Module: MetaColumn
//
// Definition of the MetaColumn class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_MetaColumn_INCLUDED
#define Data_MetaColumn_INCLUDED
#include "Poco/Data/Data.h"
#include <cstddef>
namespace Poco {
namespace Data {
class Data_API MetaColumn
/// MetaColumn class contains column metadata information.
{
public:
enum ColumnDataType
{
FDT_BOOL,
FDT_INT8,
FDT_UINT8,
FDT_INT16,
FDT_UINT16,
FDT_INT32,
FDT_UINT32,
FDT_INT64,
FDT_UINT64,
FDT_FLOAT,
FDT_DOUBLE,
FDT_STRING,
FDT_WSTRING,
FDT_BLOB,
FDT_CLOB,
FDT_DATE,
FDT_TIME,
FDT_TIMESTAMP,
FDT_UNKNOWN
};
MetaColumn();
/// Creates the MetaColumn.
explicit MetaColumn(std::size_t position,
const std::string& name = "",
ColumnDataType type = FDT_UNKNOWN,
std::size_t length = 0,
std::size_t precision = 0,
bool nullable = false);
/// Creates the MetaColumn.
MetaColumn(const MetaColumn& other);
/// Copy constructor.
MetaColumn(MetaColumn&& other) noexcept;
/// Move constructor.
MetaColumn& operator = (const MetaColumn& other);
/// Assignment operator.
MetaColumn& operator = (MetaColumn&& other) noexcept;
/// Assignment operator.
void swap(MetaColumn& other);
/// Swaps the contents with another instance.
~MetaColumn();
/// Destroys the MetaColumn.
const std::string& name() const;
/// Returns column name.
std::size_t length() const;
/// Returns column maximum length.
std::size_t precision() const;
/// Returns column precision.
/// Valid for floating point fields only
/// (zero for other data types).
std::size_t position() const;
/// Returns column position.
ColumnDataType type() const;
/// Returns column type.
bool isNullable() const;
/// Returns true if column allows null values, false otherwise.
protected:
void setName(const std::string& name);
/// Sets the column name.
void setLength(std::size_t length);
/// Sets the column length.
void setPrecision(std::size_t precision);
/// Sets the column precision.
void setType(ColumnDataType type);
/// Sets the column data type.
void setNullable(bool nullable);
/// Sets the column nullability.
private:
std::string _name;
std::size_t _length;
std::size_t _precision;
std::size_t _position;
ColumnDataType _type;
bool _nullable;
};
///
/// inlines
///
inline const std::string& MetaColumn::name() const
{
return _name;
}
inline std::size_t MetaColumn::length() const
{
return _length;
}
inline std::size_t MetaColumn::precision() const
{
return _precision;
}
inline std::size_t MetaColumn::position() const
{
return _position;
}
inline MetaColumn::ColumnDataType MetaColumn::type() const
{
return _type;
}
inline bool MetaColumn::isNullable() const
{
return _nullable;
}
inline void MetaColumn::setName(const std::string& name)
{
_name = name;
}
inline void MetaColumn::setLength(std::size_t length)
{
_length = length;
}
inline void MetaColumn::setPrecision(std::size_t precision)
{
_precision = precision;
}
inline void MetaColumn::setType(ColumnDataType type)
{
_type = type;
}
inline void MetaColumn::setNullable(bool nullable)
{
_nullable = nullable;
}
} } // namespace Poco::Data
#endif // Data_MetaColumn_INCLUDED

View File

@ -0,0 +1,99 @@
//
// PooledSessionHolder.h
//
// Library: Data
// Package: SessionPooling
// Module: PooledSessionHolder
//
// Definition of the PooledSessionHolder class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_PooledSessionHolder_INCLUDED
#define Data_PooledSessionHolder_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/SessionImpl.h"
#include "Poco/AutoPtr.h"
#include "Poco/Timestamp.h"
#include "Poco/Mutex.h"
namespace Poco {
namespace Data {
class SessionPool;
class Data_API PooledSessionHolder: public Poco::RefCountedObject
/// This class is used by SessionPool to manage SessionImpl objects.
{
public:
PooledSessionHolder(SessionPool& owner, SessionImpl* pSessionImpl);
/// Creates the PooledSessionHolder.
~PooledSessionHolder();
/// Destroys the PooledSessionHolder.
SessionImpl* session();
/// Returns a pointer to the SessionImpl.
SessionPool& owner();
/// Returns a reference to the SessionHolder's owner.
void access();
/// Updates the last access timestamp.
int idle() const;
/// Returns the number of seconds the session has not been used.
private:
SessionPool& _owner;
Poco::AutoPtr<SessionImpl> _pImpl;
Poco::Timestamp _lastUsed;
mutable Poco::FastMutex _mutex;
};
//
// inlines
//
inline SessionImpl* PooledSessionHolder::session()
{
return _pImpl;
}
inline SessionPool& PooledSessionHolder::owner()
{
return _owner;
}
inline void PooledSessionHolder::access()
{
Poco::FastMutex::ScopedLock lock(_mutex);
_lastUsed.update();
}
inline int PooledSessionHolder::idle() const
{
Poco::FastMutex::ScopedLock lock(_mutex);
return (int) (_lastUsed.elapsed()/Poco::Timestamp::resolution());
}
} } // namespace Poco::Data
#endif // Data_PooledSessionHolder_INCLUDED

View File

@ -0,0 +1,99 @@
//
// PooledSessionImpl.h
//
// Library: Data
// Package: SessionPooling
// Module: PooledSessionImpl
//
// Definition of the PooledSessionImpl class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_PooledSessionImpl_INCLUDED
#define Data_PooledSessionImpl_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/SessionImpl.h"
#include "Poco/Data/PooledSessionHolder.h"
#include "Poco/Data/StatementImpl.h"
#include "Poco/AutoPtr.h"
namespace Poco {
namespace Data {
class SessionPool;
class Data_API PooledSessionImpl: public SessionImpl
/// PooledSessionImpl is a decorator created by
/// SessionPool that adds session pool
/// management to SessionImpl objects.
{
public:
PooledSessionImpl(PooledSessionHolder* pHolder);
/// Creates the PooledSessionImpl.
~PooledSessionImpl();
/// Destroys the PooledSessionImpl.
StatementImpl::Ptr createStatementImpl();
void begin();
void commit();
void rollback();
void open(const std::string& connect = "");
void close();
void reset();
bool isConnected() const;
bool isGood() const;
void setConnectionTimeout(std::size_t timeout);
std::size_t getConnectionTimeout() const;
bool canTransact() const;
bool isTransaction() const;
void setTransactionIsolation(Poco::UInt32);
Poco::UInt32 getTransactionIsolation() const;
bool hasTransactionIsolation(Poco::UInt32) const;
bool isTransactionIsolation(Poco::UInt32) const;
const std::string& connectorName() const;
void setFeature(const std::string& name, bool state);
bool getFeature(const std::string& name);
void setProperty(const std::string& name, const Poco::Any& value);
Poco::Any getProperty(const std::string& name);
protected:
SessionImpl* access() const;
/// Updates the last access timestamp,
/// verifies validity of the session
/// and returns the session if it is valid.
///
/// Throws an SessionUnavailableException if the
/// session is no longer valid.
SessionImpl* impl() const;
/// Returns a pointer to the SessionImpl.
private:
mutable Poco::AutoPtr<PooledSessionHolder> _pHolder;
};
//
// inlines
//
inline SessionImpl* PooledSessionImpl::impl() const
{
return _pHolder->session();
}
} } // namespace Poco::Data
#endif // Data_PooledSessionImpl_INCLUDED

View File

@ -0,0 +1,75 @@
//
// PositionExtraction.h
//
// Library: Data
// Package: DataCore
// Module: Position
//
// Definition of the PositionExtraction class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_Position_INCLUDED
#define Data_Position_INCLUDED
#include "Poco/Data/Limit.h"
namespace Poco {
namespace Data {
class Data_API Position
/// Utility class wrapping unsigned integer. Used to
/// indicate the recordset position in batch SQL statements.
{
public:
Position(Poco::UInt32 value);
/// Creates the Position.
~Position();
/// Destroys the Position.
Poco::UInt32 value() const;
/// Returns the position value.
private:
Position();
Poco::UInt32 _value;
};
///
/// inlines
///
inline Poco::UInt32 Position::value() const
{
return _value;
}
namespace Keywords {
template <typename T>
inline Position from(const T& value)
/// Convenience function for creation of position.
{
return Position(value);
}
} // namespace Keywords
} } // namespace Poco::Data
#endif // Data_Position_INCLUDED

View File

@ -0,0 +1,161 @@
//
// Preparation.h
//
// Library: Data
// Package: DataCore
// Module: Preparation
//
// Definition of the Preparation class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_Preparation_INCLUDED
#define Data_Preparation_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/AbstractPreparation.h"
#include "Poco/Data/TypeHandler.h"
#include <cstddef>
#include <vector>
namespace Poco {
namespace Data {
template<typename T>
class Preparation: public AbstractPreparation
/// Class for calling the appropriate AbstractPreparator method.
{
public:
Preparation(AbstractPreparator::Ptr& pPreparator, std::size_t pos, T& val):
AbstractPreparation(pPreparator),
_pos(pos),
_val(val)
/// Creates the Preparation.
{
}
~Preparation()
/// Destroys the Preparation.
{
}
void prepare()
/// Prepares data.
{
TypeHandler<T>::prepare(_pos, _val, preparation());
}
private:
std::size_t _pos;
T& _val;
};
template<typename T>
class Preparation<std::vector<T>>: public AbstractPreparation
/// Preparation specialization for std::vector.
/// This specialization is needed for bulk operations to enforce
/// the whole vector preparation, rather than only individual contained values.
{
public:
Preparation(AbstractPreparator::Ptr pPreparator, std::size_t pos, std::vector<T>& val = std::vector<T>()):
AbstractPreparation(pPreparator),
_pos(pos),
_val(val)
/// Creates the Preparation.
{
}
~Preparation()
/// Destroys the Preparation.
{
}
void prepare()
/// Prepares data.
{
TypeHandler<std::vector<T>>::prepare(_pos, _val, preparation());
}
private:
std::size_t _pos;
std::vector<T>& _val;
};
template<typename T>
class Preparation<std::deque<T>>: public AbstractPreparation
/// Preparation specialization for std::deque.
/// This specialization is needed for bulk operations to enforce
/// the whole deque preparation, rather than only individual contained values.
{
public:
Preparation(AbstractPreparator::Ptr pPreparator, std::size_t pos, std::deque<T>& val = std::deque<T>()):
AbstractPreparation(pPreparator),
_pos(pos),
_val(val)
/// Creates the Preparation.
{
}
~Preparation()
/// Destroys the Preparation.
{
}
void prepare()
/// Prepares data.
{
TypeHandler<std::deque<T>>::prepare(_pos, _val, preparation());
}
private:
std::size_t _pos;
std::deque<T>& _val;
};
template<typename T>
class Preparation<std::list<T>>: public AbstractPreparation
/// Preparation specialization for std::list.
/// This specialization is needed for bulk operations to enforce
/// the whole list preparation, rather than only individual contained values.
{
public:
Preparation(AbstractPreparator::Ptr pPreparator, std::size_t pos, std::list<T>& val = std::list<T>()):
AbstractPreparation(pPreparator),
_pos(pos),
_val(val)
/// Creates the Preparation.
{
}
~Preparation()
/// Destroys the Preparation.
{
}
void prepare()
/// Prepares data.
{
TypeHandler<std::list<T>>::prepare(_pos, _val, preparation());
}
private:
std::size_t _pos;
std::list<T>& _val;
};
} } // namespace Poco::Data
#endif // Data_Preparation_INCLUDED

View File

@ -0,0 +1,104 @@
//
// Range.h
//
// Library: Data
// Package: DataCore
// Module: Range
//
// Definition of the Range class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_Range_INCLUDED
#define Data_Range_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/Limit.h"
namespace Poco {
namespace Data {
class Data_API Range
/// Range stores information how many rows a query should return.
{
public:
Range(Limit::SizeT lowValue, Limit::SizeT upValue, bool hardLimit);
/// Creates the Range. lowValue must be smaller equal than upValue
~Range();
/// Destroys the Limit.
const Limit& lower() const;
/// Returns the lower limit
const Limit& upper() const;
/// Returns the upper limit
private:
Limit _lower;
Limit _upper;
};
//
// inlines
//
inline const Limit& Range::lower() const
{
return _lower;
}
inline const Limit& Range::upper() const
{
return _upper;
}
namespace Keywords {
template <typename T>
Limit limit(T lim, bool hard = false)
/// Creates an upperLimit
{
return Limit(static_cast<Limit::SizeT>(lim), hard, false);
}
template <typename T>
Limit upperLimit(T lim, bool hard = false)
{
return limit(lim, hard);
}
template <typename T>
Limit lowerLimit(T lim)
{
return Limit(static_cast<Limit::SizeT>(lim), true, true);
}
template <typename T>
Range range(T low, T upp, bool hard = false)
{
return Range(static_cast<Limit::SizeT>(low), static_cast<Limit::SizeT>(upp), hard);
}
} // namespace Keywords
} } // namespace Poco::Data
#endif // Data_Range_INCLUDED

View File

@ -0,0 +1,669 @@
//
// RecordSet.h
//
// Library: Data
// Package: DataCore
// Module: RecordSet
//
// Definition of the RecordSet class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_RecordSet_INCLUDED
#define Data_RecordSet_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/Session.h"
#include "Poco/Data/Extraction.h"
#include "Poco/Data/BulkExtraction.h"
#include "Poco/Data/Statement.h"
#include "Poco/Data/RowIterator.h"
#include "Poco/Data/RowFilter.h"
#include "Poco/Data/LOB.h"
#include "Poco/String.h"
#include "Poco/Dynamic/Var.h"
#include "Poco/Exception.h"
#include "Poco/AutoPtr.h"
#include <ostream>
#include <limits>
namespace Poco {
namespace Data {
class RowFilter;
class Data_API RecordSet: private Statement
/// RecordSet provides access to data returned from a query.
/// Data access indices (row and column) are 0-based, as usual in C++.
///
/// Recordset provides navigation methods to iterate through the
/// recordset, retrieval methods to extract data, and methods
/// to get metadata (type, etc.) about columns.
///
/// To work with a RecordSet, first create a Statement, execute it, and
/// create the RecordSet from the Statement, as follows:
///
/// Statement select(session);
/// select << "SELECT * FROM Person";
/// select.execute();
/// RecordSet rs(select);
///
/// The shorter way to do the above is following:
///
/// RecordSet rs(session, "SELECT * FROM Person"[, new SimpleRowFormatter]);
///
/// The third (optional) argument passed to the Recordset constructor is a RowFormatter
/// implementation. The formatter is used in conjunction with << operator for recordset
/// data formating.
///
/// The number of rows in the RecordSet can be limited by specifying
/// a limit for the Statement.
{
public:
using RowMap = std::map<std::size_t, Row*>;
using ConstIterator = const RowIterator;
using Iterator = RowIterator;
using Statement::isNull;
using Statement::subTotalRowCount;
static const std::size_t UNKNOWN_TOTAL_ROW_COUNT;
explicit RecordSet(const Statement& rStatement,
RowFormatter::Ptr pRowFormatter = 0);
/// Creates the RecordSet.
RecordSet(Session& rSession,
const std::string& query,
RowFormatter::Ptr pRowFormatter = 0);
/// Creates the RecordSet.
RecordSet(Session& rSession,
const std::string& query,
const RowFormatter& rowFormatter);
/// Creates the RecordSet.
template <class RF>
RecordSet(Session& rSession, const std::string& query, const RF& rowFormatter):
Statement((rSession << query, Keywords::now)),
_currentRow(0),
_pBegin(new RowIterator(this, 0 == rowsExtracted())),
_pEnd(new RowIterator(this, true)),
_totalRowCount(UNKNOWN_TOTAL_ROW_COUNT)
/// Creates the RecordSet.
{
setRowFormatter(Keywords::format(rowFormatter));
}
RecordSet(const RecordSet& other);
/// Copy-creates the recordset.
RecordSet(RecordSet&& other) noexcept;
/// Move-creates the recordset.
~RecordSet();
/// Destroys the RecordSet.
void setRowFormatter(RowFormatter::Ptr pRowFormatter);
/// Assigns the row formatter to the statement and all recordset rows.
RecordSet& operator = (const Statement& stmt);
/// Assignment operator.
RecordSet& operator = (const RecordSet& other);
/// Assignment operator.
RecordSet& operator = (RecordSet&& other) noexcept;
/// Move assignment.
std::size_t rowCount() const;
/// Returns the number of rows in the RecordSet.
/// The number of rows reported is dependent on filtering.
/// Due to the need for filter conditions checking,
/// this function may suffer significant performance penalty
/// for large recordsets, so it should be used judiciously.
/// Use totalRowCount() to obtain the total number of rows.
std::size_t extractedRowCount() const;
/// Returns the number of rows extracted during the last statement
/// execution.
/// The number of rows reported is independent of filtering.
std::size_t totalRowCount() const;
//@ deprecated
/// Replaced with subTotalRowCount() and getTotalRowCount().
std::size_t getTotalRowCount() const;
/// Returns the total number of rows in the RecordSet.
/// The number of rows reported is independent of filtering.
/// If the total row count has not been set externally
/// (either explicitly or implicitly through SQL), the value
/// returned shall only be accurate if the statement limit
/// is less or equal to the total row count.
void setTotalRowCount(std::size_t totalRowCount);
/// Explicitly sets the total row count.
void setTotalRowCount(const std::string& sql);
/// Implicitly sets the total row count.
/// The supplied sql must return exactly one column
/// and one row. The returned value must be an unsigned
/// integer. The value is set as the total number of rows.
std::size_t columnCount() const;
/// Returns the number of columns in the recordset.
template <class C>
const Column<C>& column(const std::string& name) const
/// Returns the reference to the first Column with the specified name.
{
if (isBulkExtraction())
{
using E = InternalBulkExtraction<C>;
return columnImpl<C,E>(name);
}
else
{
using E = InternalExtraction<C>;
return columnImpl<C,E>(name);
}
}
template <class C>
const Column<C>& column(std::size_t pos) const
/// Returns the reference to column at specified position.
{
if (isBulkExtraction())
{
using E = InternalBulkExtraction<C>;
return columnImpl<C,E>(pos);
}
else
{
using E = InternalExtraction<C>;
return columnImpl<C,E>(pos);
}
}
Row& row(std::size_t pos);
/// Returns reference to row at position pos.
/// Rows are lazy-created and cached.
template <class T>
const T& value(std::size_t col, std::size_t row, bool useFilter = true) const
/// Returns the reference to data value at [col, row] location.
{
if (useFilter && isFiltered() && !isAllowed(row))
throw InvalidAccessException("Row not allowed");
switch (storage())
{
case STORAGE_VECTOR:
{
using C = typename std::vector<T>;
return column<C>(col).value(row);
}
case STORAGE_LIST:
{
using C = typename std::list<T>;
return column<C>(col).value(row);
}
case STORAGE_DEQUE:
case STORAGE_UNKNOWN:
{
using C = typename std::deque<T>;
return column<C>(col).value(row);
}
default:
throw IllegalStateException("Invalid storage setting.");
}
}
template <class T>
const T& value(const std::string& name, std::size_t row, bool useFilter = true) const
/// Returns the reference to data value at named column, row location.
{
if (useFilter && isFiltered() && !isAllowed(row))
throw InvalidAccessException("Row not allowed");
switch (storage())
{
case STORAGE_VECTOR:
{
using C = typename std::vector<T>;
return column<C>(name).value(row);
}
case STORAGE_LIST:
{
using C = typename std::list<T>;
return column<C>(name).value(row);
}
case STORAGE_DEQUE:
case STORAGE_UNKNOWN:
{
using C = typename std::deque<T>;
return column<C>(name).value(row);
}
default:
throw IllegalStateException("Invalid storage setting.");
}
}
Poco::Dynamic::Var value(std::size_t col, std::size_t row, bool checkFiltering = true) const;
/// Returns the data value at column, row location.
Poco::Dynamic::Var value(const std::string& name, std::size_t row, bool checkFiltering = true) const;
/// Returns the data value at named column, row location.
template <typename T>
Poco::Dynamic::Var nvl(const std::string& name, const T& deflt = T()) const
/// Returns the value in the named column of the current row
/// if the value is not NULL, or deflt otherwise.
{
if (isNull(name))
return Poco::Dynamic::Var(deflt);
else
return value(name, _currentRow);
}
template <typename T>
Poco::Dynamic::Var nvl(std::size_t index, const T& deflt = T()) const
/// Returns the value in the given column of the current row
/// if the value is not NULL, or deflt otherwise.
{
if (isNull(index, _currentRow))
return Poco::Dynamic::Var(deflt);
else
return value(index, _currentRow);
}
ConstIterator& begin() const;
/// Returns the const row iterator.
ConstIterator& end() const;
/// Returns the const row iterator.
Iterator begin();
/// Returns the row iterator.
Iterator end();
/// Returns the row iterator.
bool moveFirst();
/// Moves the row cursor to the first row.
///
/// Returns true if there is at least one row in the RecordSet,
/// false otherwise.
bool moveNext();
/// Moves the row cursor to the next row.
///
/// Returns true if the row is available, or false
/// if the end of the record set has been reached and
/// no more rows are available.
bool movePrevious();
/// Moves the row cursor to the previous row.
///
/// Returns true if the row is available, or false
/// if there are no more rows available.
bool moveLast();
/// Moves the row cursor to the last row.
///
/// Returns true if there is at least one row in the RecordSet,
/// false otherwise.
using Statement::reset;
/// Don't hide base class method.
void reset(const Statement& stmt);
/// Resets the RecordSet and assigns a new statement.
/// Should be called after the given statement has been reset,
/// assigned a new SQL statement, and executed.
///
/// Does not remove the associated RowFilter or RowFormatter.
Poco::Dynamic::Var value(const std::string& name);
/// Returns the value in the named column of the current row.
Poco::Dynamic::Var value(std::size_t index);
/// Returns the value in the given column of the current row.
Poco::Dynamic::Var operator [] (const std::string& name);
/// Returns the value in the named column of the current row.
Poco::Dynamic::Var operator [] (std::size_t index);
/// Returns the value in the named column of the current row.
MetaColumn::ColumnDataType columnType(std::size_t pos) const;
/// Returns the type for the column at specified position.
MetaColumn::ColumnDataType columnType(const std::string& name) const;
/// Returns the type for the column with specified name.
const std::string& columnName(std::size_t pos) const;
/// Returns column name for the column at specified position.
std::size_t columnLength(std::size_t pos) const;
/// Returns column maximum length for the column at specified position.
std::size_t columnLength(const std::string& name) const;
/// Returns column maximum length for the column with specified name.
std::size_t columnPrecision(std::size_t pos) const;
/// Returns column precision for the column at specified position.
/// Valid for floating point fields only (zero for other data types).
std::size_t columnPrecision(const std::string& name) const;
/// Returns column precision for the column with specified name.
/// Valid for floating point fields only (zero for other data types).
bool isNull(const std::string& name) const;
/// Returns true if column value of the current row is null.
std::ostream& copyNames(std::ostream& os) const;
/// Copies the column names to the target output stream.
/// Copied string is formatted by the current RowFormatter.
void formatNames() const;
/// Formats names using the current RowFormatter.
std::ostream& copyValues(std::ostream& os,
std::size_t offset = 0,
std::size_t length = RowIterator::POSITION_END) const;
/// Copies the data values to the supplied output stream.
/// The data set to be copied is starting at the specified offset
/// from the recordset beginning. The number of rows to be copied
/// is specified by length argument.
/// An invalid combination of offset/length arguments shall
/// cause RangeException to be thrown.
/// Copied string is formatted by the current RowFormatter.
void formatValues(std::size_t offset, std::size_t length) const;
/// Formats values using the current RowFormatter.
/// The data set to be formatted is starting at the specified offset
/// from the recordset beginning. The number of rows to be copied
/// is specified by length argument.
/// An invalid combination of offset/length arguments shall
/// cause RangeException to be thrown.
std::ostream& copy(std::ostream& os,
std::size_t offset = 0,
std::size_t length = RowIterator::POSITION_END) const;
/// Copies the column names and values to the target output stream.
/// Copied strings are formatted by the current RowFormatter.
bool isFiltered() const;
/// Returns true if recordset is filtered.
private:
RecordSet();
template<class C, class E>
std::size_t columnPosition(const std::string& name) const
/// Returns the position of the column with specified name.
{
using T = typename C::value_type;
using ExtractionVecPtr = const E*;
bool typeFound = false;
const AbstractExtractionVec& rExtractions = extractions();
AbstractExtractionVec::const_iterator it = rExtractions.begin();
AbstractExtractionVec::const_iterator end = rExtractions.end();
for (; it != end; ++it)
{
ExtractionVecPtr pExtraction = dynamic_cast<ExtractionVecPtr>(it->get());
if (pExtraction)
{
typeFound = true;
const Column<C>& col = pExtraction->column();
if (0 == Poco::icompare(name, col.name()))
return col.position();
}
}
if (typeFound)
throw NotFoundException(Poco::format("Column name: %s", name));
else
throw NotFoundException(Poco::format("Column type: %s, name: %s", std::string(typeid(T).name()), name));
}
template <class C, class E>
const Column<C>& columnImpl(const std::string& name) const
/// Returns the reference to the first Column with the specified name.
{
return columnImpl<C,E>(columnPosition<C,E>(name));
}
template <class C, class E>
const Column<C>& columnImpl(std::size_t pos) const
/// Returns the reference to column at specified position.
{
using T = typename C::value_type;
using ExtractionVecPtr = const E*;
const AbstractExtractionVec& rExtractions = extractions();
std::size_t s = rExtractions.size();
if (0 == s || pos >= s)
throw RangeException(Poco::format("Invalid column index: %z", pos));
ExtractionVecPtr pExtraction = dynamic_cast<ExtractionVecPtr>(rExtractions[pos].get());
if (pExtraction)
{
return pExtraction->column();
}
else
{
throw Poco::BadCastException(Poco::format("Type cast failed!\nColumn: %z\nTarget type:\t%s",
pos,
std::string(typeid(T).name())));
}
}
bool isAllowed(std::size_t row) const;
/// Returns true if the specified row is allowed by the
/// currently active filter.
void filter(const Poco::AutoPtr<RowFilter>& pFilter);
/// Sets the filter for the RecordSet.
const Poco::AutoPtr<RowFilter>& getFilter() const;
/// Returns the filter associated with the RecordSet.
std::size_t _currentRow;
RowIterator* _pBegin;
RowIterator* _pEnd;
RowMap _rowMap;
Poco::AutoPtr<RowFilter> _pFilter;
std::size_t _totalRowCount;
friend class RowIterator;
friend class RowFilter;
};
///
/// inlines
///
inline Data_API std::ostream& operator << (std::ostream &os, const RecordSet& rs)
{
return rs.copy(os);
}
inline std::size_t RecordSet::getTotalRowCount() const
{
if (UNKNOWN_TOTAL_ROW_COUNT == _totalRowCount)
return subTotalRowCount();
else
return _totalRowCount;
}
inline std::size_t RecordSet::totalRowCount() const
{
return getTotalRowCount();
}
inline void RecordSet::setTotalRowCount(std::size_t totalRowCount)
{
_totalRowCount = totalRowCount;
}
inline std::size_t RecordSet::extractedRowCount() const
{
return rowsExtracted();
}
inline std::size_t RecordSet::columnCount() const
{
return static_cast<std::size_t>(extractions().size());
}
inline RecordSet& RecordSet::operator = (const Statement& stmt)
{
reset(stmt);
return *this;
}
inline RecordSet& RecordSet::operator = (const RecordSet& other)
{
reset(other);
return *this;
}
inline Poco::Dynamic::Var RecordSet::value(const std::string& name)
{
return value(name, _currentRow);
}
inline Poco::Dynamic::Var RecordSet::value(std::size_t index)
{
return value(index, _currentRow);
}
inline Poco::Dynamic::Var RecordSet::operator [] (const std::string& name)
{
return value(name, _currentRow);
}
inline Poco::Dynamic::Var RecordSet::operator [] (std::size_t index)
{
return value(index, _currentRow);
}
inline MetaColumn::ColumnDataType RecordSet::columnType(std::size_t pos)const
{
return metaColumn(static_cast<UInt32>(pos)).type();
}
inline MetaColumn::ColumnDataType RecordSet::columnType(const std::string& name)const
{
return metaColumn(name).type();
}
inline const std::string& RecordSet::columnName(std::size_t pos) const
{
return metaColumn(static_cast<UInt32>(pos)).name();
}
inline std::size_t RecordSet::columnLength(std::size_t pos) const
{
return metaColumn(static_cast<UInt32>(pos)).length();
}
inline std::size_t RecordSet::columnLength(const std::string& name)const
{
return metaColumn(name).length();
}
inline std::size_t RecordSet::columnPrecision(std::size_t pos) const
{
return metaColumn(static_cast<UInt32>(pos)).precision();
}
inline std::size_t RecordSet::columnPrecision(const std::string& name)const
{
return metaColumn(name).precision();
}
inline bool RecordSet::isNull(const std::string& name) const
{
return isNull(metaColumn(name).position(), _currentRow);
}
inline RecordSet::ConstIterator& RecordSet::begin() const
{
return *_pBegin;
}
inline RecordSet::ConstIterator& RecordSet::end() const
{
return *_pEnd;
}
inline RecordSet::Iterator RecordSet::begin()
{
return *_pBegin;
}
inline RecordSet::Iterator RecordSet::end()
{
return *_pEnd;
}
inline const Poco::AutoPtr<RowFilter>& RecordSet::getFilter() const
{
return _pFilter;
}
inline void RecordSet::formatNames() const
{
(*_pBegin)->formatNames();
}
} } // namespace Poco::Data
#endif // Data_RecordSet_INCLUDED

312
vendor/POCO/Data/include/Poco/Data/Row.h vendored Normal file
View File

@ -0,0 +1,312 @@
//
// Row.h
//
// Library: Data
// Package: DataCore
// Module: Row
//
// Definition of the Row class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_Row_INCLUDED
#define Data_Row_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/RowFormatter.h"
#include "Poco/Dynamic/Var.h"
#include "Poco/Tuple.h"
#include "Poco/SharedPtr.h"
#include <vector>
#include <string>
#include <ostream>
namespace Poco {
namespace Data {
class RecordSet;
class Data_API Row
/// Row class provides a data type for RecordSet iteration purposes.
/// Dereferencing a RowIterator returns Row.
/// Rows are sortable. The sortability is maintained at all times (i.e. there
/// is always at least one column specified as a sorting criteria) .
/// The default and minimal sorting criteria is the first field (position 0).
/// The default sorting criteria can be replaced with any other field by
/// calling replaceSortField() member function.
/// Additional fields can be added to sorting criteria, in which case the
/// field precedence corresponds to addition order (i.e. later added fields
/// have lower sorting precedence).
/// These features make Row suitable for use with standard sorted
/// containers and algorithms. The main constraint is that all the rows from
/// a set that is being sorted must have the same sorting criteria (i.e., the same
/// set of fields must be in sorting criteria in the same order). Since rows don't
/// know about each other, it is the programmer's responsibility to ensure this
/// constraint is satisfied.
/// Field names are a shared pointer to a vector of strings. For efficiency sake,
/// a constructor taking a shared pointer to names vector argument is provided.
/// The stream operator is provided for Row data type as a free-standing function.
{
public:
using NameVec = RowFormatter::NameVec;
using NameVecPtr = RowFormatter::NameVecPtr;
using ValueVec = RowFormatter::ValueVec;
enum ComparisonType
{
COMPARE_AS_EMPTY,
COMPARE_AS_INTEGER,
COMPARE_AS_FLOAT,
COMPARE_AS_STRING
};
using SortTuple = Tuple<std::size_t, ComparisonType>;
using SortMap = std::vector<SortTuple>;
/// The type for map holding fields used for sorting criteria.
/// Fields are added sequentially and have precedence that
/// corresponds to field adding sequence order (rather than field's
/// position in the row).
/// This requirement rules out use of std::map due to its sorted nature.
using SortMapPtr = SharedPtr<SortMap>;
Row();
/// Creates the Row.
Row(NameVecPtr pNames,
const RowFormatter::Ptr& pFormatter = 0);
/// Creates the Row.
Row(NameVecPtr pNames,
const SortMapPtr& pSortMap,
const RowFormatter::Ptr& pFormatter = 0);
/// Creates the Row.
~Row();
/// Destroys the Row.
Poco::Dynamic::Var& get(std::size_t col);
/// Returns the reference to data value at column location.
Poco::Dynamic::Var& operator [] (std::size_t col);
/// Returns the reference to data value at column location.
Poco::Dynamic::Var& operator [] (const std::string& name);
/// Returns the reference to data value at named column location.
template <typename T>
void append(const std::string& name, const T& val)
/// Appends the value to the row.
{
if (!_pNames) _pNames = new NameVec;
_values.push_back(val);
_pNames->push_back(name);
if (1 == _values.size()) addSortField(0);
}
template <typename T>
void set(std::size_t pos, const T& val)
/// Assigns the value to the row.
{
try
{
_values.at(pos) = val;
}
catch (std::out_of_range&)
{
throw RangeException("Invalid column number.");
}
}
template <typename T>
void set(const std::string& name, const T& val)
/// Assigns the value to the row.
{
NameVec::iterator it = _pNames->begin();
NameVec::iterator end = _pNames->end();
for (int i = 0; it != end; ++it, ++i)
{
if (*it == name)
return set(i, val);
}
std::ostringstream os;
os << "Column with name " << name << " not found.";
throw NotFoundException(os.str());
}
std::size_t fieldCount() const;
/// Returns the number of fields in this row.
void reset();
/// Resets the row by clearing all field names and values.
void separator(const std::string& sep);
/// Sets the separator.
void addSortField(std::size_t pos);
/// Adds the field used for sorting.
void addSortField(const std::string& name);
/// Adds the field used for sorting.
void removeSortField(std::size_t pos);
/// Removes the field used for sorting.
void removeSortField(const std::string& name);
/// Removes the field used for sorting.
void replaceSortField(std::size_t oldPos, std::size_t newPos);
/// Replaces the field used for sorting.
void replaceSortField(const std::string& oldName, const std::string& newName);
/// Replaces the field used for sorting.
void resetSort();
/// Resets the sorting criteria to field 0 only.
const std::string& namesToString() const;
/// Converts the column names to string.
void formatNames() const;
/// Fomats the column names.
const std::string& valuesToString() const;
/// Converts the row values to string and returns the formated string.
void formatValues() const;
/// Fomats the row values.
bool operator == (const Row& other) const;
/// Equality operator.
bool operator != (const Row& other) const;
/// Inequality operator.
bool operator < (const Row& other) const;
/// Less-than operator.
const NameVecPtr names() const;
/// Returns the shared pointer to names vector.
const ValueVec& values() const;
/// Returns the const reference to values vector.
void setFormatter(const RowFormatter::Ptr& pFormatter = 0);
/// Sets the formatter for this row and takes the
/// shared ownership of it.
const RowFormatter& getFormatter() const;
/// Returns the reference to the formatter.
void setSortMap(const SortMapPtr& pSortMap = 0);
/// Adds the sorting fields entry and takes the
/// shared ownership of it.
const SortMapPtr& getSortMap() const;
/// Returns the reference to the sorting fields.
private:
void init(const SortMapPtr& pSortMap, const RowFormatter::Ptr& pFormatter);
ValueVec& values();
/// Returns the reference to values vector.
std::size_t getPosition(const std::string& name);
bool isEqualSize(const Row& other) const;
bool isEqualType(const Row& other) const;
NameVecPtr _pNames;
ValueVec _values;
SortMapPtr _pSortMap;
mutable RowFormatter::Ptr _pFormatter;
mutable std::string _nameStr;
mutable std::string _valueStr;
};
Data_API std::ostream& operator << (std::ostream &os, const Row& row);
///
/// inlines
///
inline std::size_t Row::fieldCount() const
{
return static_cast<std::size_t>(_values.size());
}
inline void Row::reset()
{
_pNames->clear();
_values.clear();
}
inline const Row::NameVecPtr Row::names() const
{
return _pNames;
}
inline const Row::ValueVec& Row::values() const
{
return _values;
}
inline Row::ValueVec& Row::values()
{
return _values;
}
inline Poco::Dynamic::Var& Row::operator [] (std::size_t col)
{
return get(col);
}
inline Poco::Dynamic::Var& Row::operator [] (const std::string& name)
{
return get(getPosition(name));
}
inline const RowFormatter& Row::getFormatter() const
{
return *_pFormatter;
}
inline const Row::SortMapPtr& Row::getSortMap() const
{
return _pSortMap;
}
inline const std::string& Row::valuesToString() const
{
return _pFormatter->formatValues(values(), _valueStr);
}
inline void Row::formatValues() const
{
return _pFormatter->formatValues(values());
}
} } // namespace Poco::Data
#endif // Data_Row_INCLUDED

View File

@ -0,0 +1,276 @@
//
// RowFilter.h
//
// Library: Data
// Package: DataCore
// Module: RowFilter
//
// Definition of the RowFilter class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_RowFilter_INCLUDED
#define Data_RowFilter_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Dynamic/Var.h"
#include "Poco/Tuple.h"
#include "Poco/String.h"
#include "Poco/RefCountedObject.h"
#include "Poco/AutoPtr.h"
#include <map>
#include <list>
#include <utility>
namespace Poco {
namespace Data {
class RecordSet;
class Data_API RowFilter: public RefCountedObject
/// RowFilter class provides row filtering functionality.
/// A filter contains a set of criteria (field name, value and
/// logical operation) for row filtering.
/// Additionally, a row filter contains a map of pointers to other
/// filters with related logical operations between filters.
/// RowFilter is typically added to recordset in order to filter
/// its content. Since the recordset own iteration is dependent upon
/// filtering, whenever the filtering criteria is changed,
/// the filter automatically notifies all associated recordsets
/// by rewinding them to the first position.
{
public:
enum Comparison
{
VALUE_LESS_THAN,
VALUE_LESS_THAN_OR_EQUAL,
VALUE_EQUAL,
VALUE_GREATER_THAN,
VALUE_GREATER_THAN_OR_EQUAL,
VALUE_NOT_EQUAL,
VALUE_IS_NULL
};
enum LogicOperator
{
OP_AND,
OP_OR,
OP_NOT
};
typedef bool (*CompT)(const Poco::Dynamic::Var&, const Poco::Dynamic::Var&);
using Ptr = AutoPtr<RowFilter>;
using Comparisons = std::map<std::string, Comparison>;
using ComparisonEntry = Tuple<Poco::Dynamic::Var, Comparison, LogicOperator>;
using ComparisonMap = std::multimap<std::string, ComparisonEntry>;
using FilterMap = std::map<AutoPtr<RowFilter>, LogicOperator>;
RowFilter(RecordSet* pRecordSet);
/// Creates the top-level RowFilter and associates it with the recordset.
RowFilter(Ptr pParent, LogicOperator op = OP_OR);
/// Creates child RowFilter and associates it with the parent filter.
~RowFilter();
/// Destroys the RowFilter.
void addFilter(Ptr pFilter, LogicOperator comparison);
/// Appends another filter to this one.
void removeFilter(Ptr pFilter);
/// Removes filter from this filter.
bool has(Ptr pFilter) const;
/// Returns true if this filter is parent of pFilter;
template <typename T>
void add(const std::string& name, Comparison comparison, const T& value, LogicOperator op = OP_OR)
/// Adds value to the filter.
{
rewindRecordSet();
_comparisonMap.insert(ComparisonMap::value_type(toUpper(name),
ComparisonEntry(value, comparison, op)));
}
template <typename T>
void add(const std::string& name, const std::string& comp, const T& value, LogicOperator op = OP_OR)
/// Adds value to the filter.
{
add(name, getComparison(comp), value, op);
}
template <typename T>
void addAnd(const std::string& name, const std::string& comp, const T& value)
/// Adds logically AND-ed value to the filter.
{
add(name, getComparison(comp), value, OP_AND);
}
template <typename T>
void addOr(const std::string& name, const std::string& comp, const T& value)
/// Adds logically OR-ed value to the filter.
{
add(name, getComparison(comp), value, OP_OR);
}
int remove(const std::string& name);
/// Removes named comparisons from the filter.
/// All comparisons with specified name are removed.
/// Returns the number of comparisons removed.
void toggleNot();
/// Togless the NOT operator for this filter;
bool isNot() const;
/// Returns true if filter is NOT-ed, false otherwise.
bool isEmpty() const;
/// Returns true if there is not filtering criteria specified.
bool isAllowed(std::size_t row) const;
/// Returns true if name and value are allowed.
bool exists(const std::string& name) const;
/// Returns true if name is known to this row filter.
private:
RowFilter();
RowFilter(const RowFilter&);
RowFilter& operator=(const RowFilter&);
void init();
static bool equal(const Poco::Dynamic::Var& p1, const Poco::Dynamic::Var& p2);
static bool notEqual(const Poco::Dynamic::Var& p1, const Poco::Dynamic::Var& p2);
static bool less(const Poco::Dynamic::Var& p1, const Poco::Dynamic::Var& p2);
static bool greater(const Poco::Dynamic::Var& p1, const Poco::Dynamic::Var& p2);
static bool lessOrEqual(const Poco::Dynamic::Var& p1, const Poco::Dynamic::Var& p2);
static bool greaterOrEqual(const Poco::Dynamic::Var& p1, const Poco::Dynamic::Var& p2);
static bool logicalAnd(const Poco::Dynamic::Var& p1, const Poco::Dynamic::Var& p2);
static bool logicalOr(const Poco::Dynamic::Var& p1, const Poco::Dynamic::Var& p2);
static bool isNull(const Poco::Dynamic::Var& p1, const Poco::Dynamic::Var&);
static void doCompare(Poco::Dynamic::Var& ret,
Poco::Dynamic::Var& val,
CompT comp,
const ComparisonEntry& ce);
RecordSet& recordSet() const;
Comparison getComparison(const std::string& comp) const;
void rewindRecordSet();
Comparisons _comparisons;
ComparisonMap _comparisonMap;
mutable RecordSet* _pRecordSet;
Ptr _pParent;
FilterMap _filterMap;
bool _not;
friend class RecordSet;
};
///
/// inlines
///
inline bool RowFilter::has(Ptr pFilter) const
{
return _filterMap.find(pFilter) != _filterMap.end();
}
inline bool RowFilter::isEmpty() const
{
return _comparisonMap.size() == 0;
}
inline bool RowFilter::exists(const std::string& name) const
{
return _comparisonMap.find(name) != _comparisonMap.end();
}
inline void RowFilter::toggleNot()
{
_not = !_not;
}
inline bool RowFilter::isNot() const
{
return _not;
}
inline bool RowFilter::equal(const Poco::Dynamic::Var& p1, const Poco::Dynamic::Var& p2)
{
return p1 == p2;
}
inline bool RowFilter::notEqual(const Poco::Dynamic::Var& p1, const Poco::Dynamic::Var& p2)
{
return p1 != p2;
}
inline bool RowFilter::less(const Poco::Dynamic::Var& p1, const Poco::Dynamic::Var& p2)
{
return p1 < p2;
}
inline bool RowFilter::greater(const Poco::Dynamic::Var& p1, const Poco::Dynamic::Var& p2)
{
return p1 > p2;
}
inline bool RowFilter::lessOrEqual(const Poco::Dynamic::Var& p1, const Poco::Dynamic::Var& p2)
{
return p1 <= p2;
}
inline bool RowFilter::greaterOrEqual(const Poco::Dynamic::Var& p1, const Poco::Dynamic::Var& p2)
{
return p1 >= p2;
}
inline bool RowFilter::logicalAnd(const Poco::Dynamic::Var& p1, const Poco::Dynamic::Var& p2)
{
return p1 && p2;
}
inline bool RowFilter::logicalOr(const Poco::Dynamic::Var& p1, const Poco::Dynamic::Var& p2)
{
return p1 || p2;
}
inline bool RowFilter::isNull(const Poco::Dynamic::Var& p1, const Poco::Dynamic::Var&)
{
return p1.isEmpty();
}
} } // namespace Poco::Data
#endif // Data_RowFilter_INCLUDED

View File

@ -0,0 +1,231 @@
//
// RowFormatter.h
//
// Library: Data
// Package: DataCore
// Module: RowFormatter
//
// Definition of the RowFormatter class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_RowFormatter_INCLUDED
#define Data_RowFormatter_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/SharedPtr.h"
#include "Poco/RefCountedObject.h"
#include "Poco/Dynamic/Var.h"
#include <sstream>
#include <vector>
namespace Poco {
namespace Data {
class Data_API RowFormatter
/// Row formatter is an abstract class providing definition for row formatting functionality.
/// For custom formatting strategies, inherit from this class and override formatNames()
/// and formatValues() member functions.
///
/// Row formatter can be either passed to the RecordSet at construction time,
/// like in the following example:
///
/// RecordSet rs(session. "SELECT * FROM Table", new MyRowFormater);
///
/// or it can be supplied to the statement as in the following example:
///
/// MyRowFormatter rf
/// session << "SELECT * FROM Table", format(rf);
///
/// If no formatter is externally supplied to the statement, the SimpleRowFormatter is used.
/// Statement always has the ownership of the row formatter and shares
/// it with rows through RecordSet.
///
/// To accomodate for various formatting needs, a formatter can operate in two modes:
///
/// - progressive: formatted individual row strings are gemerated and returned from each
/// call to formatValues;
/// std::string& formatNames(const NameVecPtr, std::string&) and
/// std::string& formatValues(const ValueVec&, std::string&) member calls should be
/// used in this case; this is the default mode
///
/// - bulk: formatted resulting string is accumulated internally and obtained at
/// the end of iteration via toString() member function;
/// void formatNames(const NameVecPtr) and
/// void formatValues(const ValueVec&) member calls should be used in this case
///
/// When formatter is used in conjunction with Row/RecordSet, the formatting members corresponding
/// to the formater mode are expected to be implemented. If a call is propagated to this parent
/// class, the functions do nothing or silently return empty string respectively.
///
{
public:
using Ptr = SharedPtr<RowFormatter>;
using NameVec = std::vector<std::string>;
using NameVecPtr = SharedPtr<std::vector<std::string>>;
using ValueVec = std::vector<Poco::Dynamic::Var>;
static const int INVALID_ROW_COUNT = -1;
enum Mode
{
FORMAT_PROGRESSIVE,
FORMAT_BULK
};
RowFormatter(const std::string& prefix = "",
const std::string& postfix = "",
Mode mode = FORMAT_PROGRESSIVE);
/// Creates the RowFormatter and sets the prefix and postfix to specified values.
virtual ~RowFormatter();
/// Destroys the RowFormatter.
virtual std::string& formatNames(const NameVecPtr pNames, std::string& formattedNames);
/// Should be implemented to format the row fields names and return the formatted string.
/// The default implementation clears the names string and returns it.
virtual void formatNames(const NameVecPtr pNames);
/// Should be implemented to format the row fields names.
/// The default implementation does nothing.
virtual std::string& formatValues(const ValueVec& vals, std::string& formattedValues);
/// Should be implemented to format the row fields values and return the formatted string.
/// The default implementation clears the values string and returns it.
virtual void formatValues(const ValueVec& vals);
/// Should be implemented to format the row fields values.
/// The default implementation does nothing.
virtual const std::string& toString();
/// Throws NotImplementedException. Formatters operating in bulk mode should
/// implement this member function to return valid pointer to the formatted result.
virtual int rowCount() const;
/// Returns INVALID_ROW_COUNT. Must be implemented by inheriting classes
/// which maintain count of processed rows.
int getTotalRowCount() const;
/// Returns zero. Must be implemented by inheriting classes.
/// Typically, total row count shall be set up front through
/// setTotalRowCount() call.
void setTotalRowCount(int count);
/// Sets total row count.
virtual const std::string& prefix() const;
/// Returns prefix string;
virtual const std::string& postfix() const;
/// Returns postfix string;
void reset();
/// Resets the formatter by setting prefix and postfix
/// to empty strings and row count to INVALID_ROW_COUNT.
Mode getMode() const;
/// Returns the formater mode.
void setMode(Mode mode);
/// Sets the fromatter mode.
protected:
void setPrefix(const std::string& prefix);
/// Sets the prefix for the formatter.
void setPostfix(const std::string& postfix);
/// Sets the postfix for the formatter
private:
mutable std::string _prefix;
mutable std::string _postfix;
Mode _mode;
int _totalRowCount;
};
///
/// inlines
///
inline int RowFormatter::rowCount() const
{
return INVALID_ROW_COUNT;
}
inline int RowFormatter::getTotalRowCount() const
{
return _totalRowCount;
}
inline void RowFormatter::setTotalRowCount(int count)
{
_totalRowCount = count;
}
inline void RowFormatter::setPrefix(const std::string& prefix)
{
_prefix = prefix;
}
inline void RowFormatter::setPostfix(const std::string& postfix)
{
_postfix = postfix;
}
inline const std::string& RowFormatter::prefix() const
{
return _prefix;
}
inline const std::string& RowFormatter::postfix() const
{
return _postfix;
}
inline RowFormatter::Mode RowFormatter::getMode() const
{
return _mode;
}
inline void RowFormatter::setMode(Mode mode)
{
_mode = mode;
}
namespace Keywords {
template <typename T>
inline RowFormatter::Ptr format(const T& formatter)
/// Utility function used to pass formatter to the statement.
{
return new T(formatter);
}
} // namespace Keywords
} } // namespace Poco::Data
#endif // Data_RowFormatter_INCLUDED

View File

@ -0,0 +1,155 @@
//
// RowIterator.h
//
// Library: Data
// Package: DataCore
// Module: RowIterator
//
// Definition of the RowIterator class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_RowIterator_INCLUDED
#define Data_RowIterator_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/Row.h"
#include "Poco/Dynamic/Var.h"
#include <iterator>
#include <algorithm>
namespace Poco {
namespace Data {
class RecordSet;
class Data_API RowIterator
/// RowIterator class.
{
public:
using iterator_category = std::bidirectional_iterator_tag;
using value_type = Row;
using difference_type = std::ptrdiff_t;
using pointer = Row*;
using reference = Row&;
static const std::size_t POSITION_END;
/// End position indicator.
RowIterator(RecordSet* pRecordSet, bool positionEnd);
/// Creates the RowIterator and positions it at the end of
/// the recordset if positionEnd is true. Otherwise, it is
/// positioned at the beginning.
RowIterator(const RowIterator& other);
/// Creates a copy of other RowIterator.
RowIterator(RowIterator&& other) noexcept;
/// Move constructor.
~RowIterator();
/// Destroys the RowIterator.
RowIterator& operator = (const RowIterator& other);
/// Assigns the other RowIterator.
RowIterator& operator = (RowIterator&& other) noexcept;
/// Move assignment.
bool operator == (const RowIterator& other) const;
/// Equality operator.
bool operator != (const RowIterator& other) const;
/// Inequality operator.
Row& operator * () const;
/// Returns reference to the current row.
Row* operator -> () const;
/// Returns pointer to the current row.
const RowIterator& operator ++ () const;
/// Advances by one position and returns current position.
RowIterator operator ++ (int) const;
/// Advances by one position and returns copy of the iterator with
/// previous current position.
const RowIterator& operator -- () const;
/// Goes back by one position and returns copy of the iterator with
/// previous current position.
RowIterator operator -- (int) const;
/// Goes back by one position and returns previous current position.
RowIterator operator + (std::size_t diff) const;
/// Returns a copy the RowIterator advanced by diff positions.
RowIterator operator - (std::size_t diff) const;
/// Returns a copy the RowIterator backed by diff positions.
/// Throws RangeException if diff is larger than current position.
void swap(RowIterator& other);
/// Swaps the RowIterator with another one.
private:
RowIterator();
void increment() const;
/// Increments the iterator position by one.
/// Throws RangeException if position is out of range.
void decrement() const;
/// Decrements the iterator position by one.
/// Throws RangeException if position is out of range.
void setPosition(std::size_t pos) const;
/// Sets the iterator position.
/// Throws RangeException if position is out of range.
RecordSet* _pRecordSet;
mutable std::size_t _position;
};
///
/// inlines
///
inline bool RowIterator::operator == (const RowIterator& other) const
{
return _pRecordSet == other._pRecordSet && _position == other._position;
}
inline bool RowIterator::operator != (const RowIterator& other) const
{
return _pRecordSet != other._pRecordSet || _position != other._position;
}
} } // namespace Poco::Data
namespace std
{
template<>
inline void swap<Poco::Data::RowIterator>(Poco::Data::RowIterator& s1, Poco::Data::RowIterator& s2) noexcept
/// Full template specalization of std:::swap for RowIterator
{
s1.swap(s2);
}
}
#endif // Data_RowIterator_INCLUDED

View File

@ -0,0 +1,217 @@
//
// SQLChannel.h
//
// Library: Data
// Package: Logging
// Module: SQLChannel
//
// Definition of the SQLChannel class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_SQLChannel_INCLUDED
#define Data_SQLChannel_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/Connector.h"
#include "Poco/Data/Session.h"
#include "Poco/Data/Statement.h"
#include "Poco/Data/ArchiveStrategy.h"
#include "Poco/Channel.h"
#include "Poco/Message.h"
#include "Poco/AutoPtr.h"
#include "Poco/String.h"
namespace Poco {
namespace Data {
class Data_API SQLChannel: public Poco::Channel
/// This Channel implements logging to a SQL database.
/// The channel is dependent on the schema. The DDL for
/// table creation (subject to target DDL dialect dependent
/// modifications) is:
///
/// "CREATE TABLE T_POCO_LOG (Source VARCHAR,
/// Name VARCHAR,
/// ProcessId INTEGER,
/// Thread VARCHAR,
/// ThreadId INTEGER,
/// Priority INTEGER,
/// Text VARCHAR,
/// DateTime DATE)"
///
/// The table name is configurable through "table" property.
/// Other than DateTime filed name used for optional time-based archiving purposes, currently the
/// field names are not mandated. However, it is recomended to use names as specified above.
///
/// To provide as non-intrusive operation as possbile, the log entries are cached and
/// inserted into the target database asynchronously by default. The blocking, however, will occur
/// before the next entry insertion with default timeout of 1 second. The default settings can be
/// overriden (see async, timeout and throw properties for details).
/// If throw property is false, insertion timeouts are ignored, otherwise a TimeoutException is thrown.
/// To force insertion of every entry, set timeout to 0. This setting, however, introduces
/// a risk of long blocking periods in case of remote server communication delays.
{
public:
using Ptr = Poco::AutoPtr<SQLChannel>;
SQLChannel();
/// Creates SQLChannel.
SQLChannel(const std::string& connector,
const std::string& connect,
const std::string& name = "-");
/// Creates a SQLChannel with the given connector, connect string, timeout, table and name.
/// The connector must be already registered.
void open();
/// Opens the SQLChannel.
void close();
/// Closes the SQLChannel.
void log(const Message& msg);
/// Writes the log message to the database.
void setProperty(const std::string& name, const std::string& value);
/// Sets the property with the given value.
///
/// The following properties are supported:
/// * name: The name used to identify the source of log messages.
/// Defaults to "-".
///
/// * connector: The target data storage connector name.
///
/// * connect: The target data storage connection string.
///
/// * table: Destination log table name. Defaults to "T_POCO_LOG".
/// Table must exist in the target database.
///
/// * keep: Max row age for the log table. To disable archiving,
/// set this property to empty string or "forever".
///
/// * archive: Archive table name. Defaults to "T_POCO_LOG_ARCHIVE".
/// Table must exist in the target database. To disable archiving,
/// set this property to empty string.
///
/// * async: Indicates asynchronous execution. When excuting asynchronously,
/// messages are sent to the target using asyncronous execution.
/// However, prior to the next message being processed and sent to
/// the target, the previous operation must have been either completed
/// or timed out (see timeout and throw properties for details on
/// how abnormal conditos are handled).
///
/// * timeout: Timeout (ms) to wait for previous log operation completion.
/// Values "0" and "" mean no timeout. Only valid when logging
/// is asynchronous, otherwise ignored.
///
/// * throw: Boolean value indicating whether to throw in case of timeout.
/// Setting this property to false may result in log entries being lost.
/// True values are (case insensitive) "true", "t", "yes", "y".
/// Anything else yields false.
std::string getProperty(const std::string& name) const;
/// Returns the value of the property with the given name.
std::size_t wait();
/// Waits for the completion of the previous operation and returns
/// the result. If chanel is in synchronous mode, returns 0 immediately.
static void registerChannel();
/// Registers the channel with the global LoggingFactory.
static const std::string PROP_CONNECT;
static const std::string PROP_CONNECTOR;
static const std::string PROP_NAME;
static const std::string PROP_TABLE;
static const std::string PROP_ARCHIVE_TABLE;
static const std::string PROP_MAX_AGE;
static const std::string PROP_ASYNC;
static const std::string PROP_TIMEOUT;
static const std::string PROP_THROW;
protected:
~SQLChannel();
private:
using SessionPtr = Poco::SharedPtr<Session>;
using StatementPtr = Poco::SharedPtr<Statement>;
using Priority = Poco::Message::Priority;
using StrategyPtr = Poco::SharedPtr<ArchiveStrategy>;
void initLogStatement();
/// Initiallizes the log statement.
void initArchiveStatements();
/// Initiallizes the archive statement.
void logAsync(const Message& msg);
/// Waits for previous operation completion and
/// calls logSync(). If the previous operation times out,
/// and _throw is true, TimeoutException is thrown, oterwise
/// the timeout is ignored and log entry is lost.
void logSync(const Message& msg);
/// Inserts the message in the target database.
bool isTrue(const std::string& value) const;
/// Returns true is value is "true", "t", "yes" or "y".
/// Case insensitive.
std::string _connector;
std::string _connect;
SessionPtr _pSession;
StatementPtr _pLogStatement;
std::string _name;
std::string _table;
int _timeout;
bool _throw;
bool _async;
// members for log entry cache (needed for async mode)
std::string _source;
long _pid;
std::string _thread;
long _tid;
int _priority;
std::string _text;
DateTime _dateTime;
StrategyPtr _pArchiveStrategy;
};
//
// inlines
//
inline std::size_t SQLChannel::wait()
{
if (_async && _pLogStatement)
return _pLogStatement->wait(_timeout);
return 0;
}
inline bool SQLChannel::isTrue(const std::string& value) const
{
return ((0 == icompare(value, "true")) ||
(0 == icompare(value, "t")) ||
(0 == icompare(value, "yes")) ||
(0 == icompare(value, "y")));
}
} } // namespace Poco::Data
#endif // Data_SQLChannel_INCLUDED

View File

@ -0,0 +1,509 @@
//
// Session.h
//
// Library: Data
// Package: DataCore
// Module: Session
//
// Definition of the Session class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_Session_INCLUDED
#define Data_Session_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/SessionImpl.h"
#include "Poco/Data/Statement.h"
#include "Poco/Data/StatementCreator.h"
#include "Poco/Data/Binding.h"
#include "Poco/SharedPtr.h"
#include "Poco/AutoPtr.h"
#include "Poco/Any.h"
#include <algorithm>
namespace Poco {
namespace Data {
class StatementImpl;
class Data_API Session
/// A Session holds a connection to a Database and creates Statement objects.
///
/// Sessions are always created via the SessionFactory:
///
/// Session ses(SessionFactory::instance().create(connectorKey, connectionString));
///
/// where the first param presents the type of session one wants to create (e.g., for SQLite one would choose "SQLite",
/// for ODBC the key is "ODBC") and the second param is the connection string that the session implementation
/// requires to connect to the database. The format of the connection string is specific to the actual connector.
///
/// A simpler form to create the session is to pass the connector key and connection string directly to
/// the Session constructor.
///
/// A concrete example to open an SQLite database stored in the file "dummy.db" would be
///
/// Session ses("SQLite", "dummy.db");
///
/// Via a Session one can create two different types of statements. First, statements that should only be executed once and immediately, and
/// second, statements that should be executed multiple times, using a separate execute() call.
/// The simple one is immediate execution:
///
/// ses << "CREATE TABLE Dummy (data INTEGER(10))", now;
///
/// The now at the end of the statement is required, otherwise the statement
/// would not be executed.
///
/// If one wants to reuse a Statement (and avoid the overhead of repeatedly parsing an SQL statement)
/// one uses an explicit Statement object and its execute() method:
///
/// int i = 0;
/// Statement stmt = (ses << "INSERT INTO Dummy VALUES(:data)", use(i));
///
/// for (i = 0; i < 100; ++i)
/// {
/// stmt.execute();
/// }
///
/// The above example assigns the variable i to the ":data" placeholder in the SQL query. The query is parsed and compiled exactly
/// once, but executed 100 times. At the end the values 0 to 99 will be present in the Table "DUMMY".
///
/// A faster implementaton of the above code will simply create a vector of int
/// and use the vector as parameter to the use clause (you could also use set or multiset instead):
///
/// std::vector<int> data;
/// for (int i = 0; i < 100; ++i)
/// {
/// data.push_back(i);
/// }
/// ses << "INSERT INTO Dummy VALUES(:data)", use(data);
///
/// NEVER try to bind to an empty collection. This will give a BindingException at run-time!
///
/// Retrieving data from a database works similar, you could use simple data types, vectors, sets or multiset as your targets:
///
/// std::set<int> retData;
/// ses << "SELECT * FROM Dummy", into(retData));
///
/// Due to the blocking nature of the above call it is possible to partition the data retrieval into chunks by setting a limit to
/// the maximum number of rows retrieved from the database:
///
/// std::set<int> retData;
/// Statement stmt = (ses << "SELECT * FROM Dummy", into(retData), limit(50));
/// while (!stmt.done())
/// {
/// stmt.execute();
/// }
///
/// The "into" keyword is used to inform the statement where output results should be placed. The limit value ensures
/// that during each run at most 50 rows are retrieved. Assuming Dummy contains 100 rows, retData will contain 50
/// elements after the first run and 100 after the second run, i.e.
/// the collection is not cleared between consecutive runs. After the second execute stmt.done() will return true.
///
/// A prepared Statement will behave exactly the same but a further call to execute() will simply reset the Statement,
/// execute it again and append more data to the result set.
///
/// Note that it is possible to append several "bind" or "into" clauses to the statement. Theoretically, one could also have several
/// limit clauses but only the last one that was added will be effective.
/// Also several preconditions must be met concerning binds and intos.
/// Take the following example:
///
/// ses << "CREATE TABLE Person (LastName VARCHAR(30), FirstName VARCHAR, Age INTEGER(3))";
/// std::vector<std::string> nameVec; // [...] add some elements
/// std::vector<int> ageVec; // [...] add some elements
/// ses << "INSERT INTO Person (LastName, Age) VALUES(:ln, :age)", use(nameVec), use(ageVec);
///
/// The size of all use parameters MUST be the same, otherwise an exception is thrown. Furthermore,
/// the amount of use clauses must match the number of wildcards in the query (to be more precise:
/// each binding has a numberOfColumnsHandled() value which defaults to 1. The sum of all these values
/// must match the wildcard count in the query.
/// However, this is only important if you have written your own TypeHandler specializations.
/// If you plan to map complex object types to tables see the TypeHandler documentation.
/// For now, we simply assume we have written one TypeHandler for Person objects. Instead of having n different vectors,
/// we have one collection:
///
/// std::vector<Person> people; // [...] add some elements
/// ses << "INSERT INTO Person (LastName, FirstName, Age) VALUES(:ln, :fn, :age)", use(people);
///
/// which will insert all Person objects from the people vector to the database (and again, you can use set, multiset too,
/// even map and multimap if Person provides an operator() which returns the key for the map).
/// The same works for a SELECT statement with "into" clauses:
///
/// std::vector<Person> people;
/// ses << "SELECT * FROM PERSON", into(people);
///
/// Mixing constants or variables with manipulators is allowed provided there are corresponding placeholders for the constants provided in
/// the SQL string, such as in following example:
///
/// std::vector<Person> people;
/// ses << "SELECT * FROM %s", into(people), "PERSON";
///
/// Formatting only kicks in if there are values to be injected into the SQL string, otherwise it is skipped.
/// If the formatting will occur and the percent sign is part of the query itself, it can be passed to the query by entering it twice (%%).
/// However, if no formatting is used, one percent sign is sufficient as the string will be passed unaltered.
/// For complete list of supported data types with their respective specifications, see the documentation for format in Foundation.
{
public:
static const std::size_t LOGIN_TIMEOUT_DEFAULT = SessionImpl::LOGIN_TIMEOUT_DEFAULT;
static const Poco::UInt32 TRANSACTION_READ_UNCOMMITTED = 0x00000001L;
static const Poco::UInt32 TRANSACTION_READ_COMMITTED = 0x00000002L;
static const Poco::UInt32 TRANSACTION_REPEATABLE_READ = 0x00000004L;
static const Poco::UInt32 TRANSACTION_SERIALIZABLE = 0x00000008L;
Session(Poco::AutoPtr<SessionImpl> ptrImpl);
/// Creates the Session.
Session(const std::string& connector,
const std::string& connectionString,
std::size_t timeout = LOGIN_TIMEOUT_DEFAULT);
/// Creates a new session, using the given connector (which must have
/// been registered), and connectionString.
Session(const std::string& connection,
std::size_t timeout = LOGIN_TIMEOUT_DEFAULT);
/// Creates a new session, using the given connection (must be in
/// "connection:///connectionString" format).
Session(const Session&);
/// Creates a session by copying another one.
Session(Session&&) noexcept;
/// Creates a session by moving another one.
Session& operator = (const Session&);
/// Assignment operator.
Session& operator = (Session&&) noexcept;
/// Move assignment.
~Session();
/// Destroys the Session.
void swap(Session& other);
/// Swaps the session with another one.
template <typename T>
Statement operator << (const T& t)
/// Creates a Statement with the given data as SQLContent
{
return _statementCreator << t;
}
SharedPtr<StatementImpl> createStatementImpl();
/// Creates a StatementImpl.
void open(const std::string& connect = "");
/// Opens the session using the supplied string.
/// Can also be used with default empty string to
/// reconnect a disconnected session.
/// If the connection is not established,
/// a ConnectionFailedException is thrown.
/// Zero timout means indefinite
void close();
/// Closes the session.
bool isConnected();
/// Returns true iff session is connected, false otherwise.
void reconnect();
/// Closes the session and opens it.
bool isGood();
/// Returns true iff the session is good and can be used, false otherwise.
void setLoginTimeout(std::size_t timeout);
/// Sets the session login timeout value.
std::size_t getLoginTimeout() const;
/// Returns the session login timeout value.
void setConnectionTimeout(std::size_t timeout);
/// Sets the session connection timeout value.
std::size_t getConnectionTimeout();
/// Returns the session connection timeout value.
void begin();
/// Starts a transaction.
void commit();
/// Commits and ends a transaction.
void rollback();
/// Rolls back and ends a transaction.
bool canTransact();
/// Returns true if session has transaction capabilities.
bool isTransaction();
/// Returns true iff a transaction is in progress, false otherwise.
void setTransactionIsolation(Poco::UInt32);
/// Sets the transaction isolation level.
Poco::UInt32 getTransactionIsolation();
/// Returns the transaction isolation level.
bool hasTransactionIsolation(Poco::UInt32 ti);
/// Returns true iff the transaction isolation level corresponding
/// to the supplied bitmask is supported.
bool isTransactionIsolation(Poco::UInt32 ti);
/// Returns true iff the transaction isolation level corresponds
/// to the supplied bitmask.
std::string connector() const;
/// Returns the connector name for this session.
std::string uri() const;
/// Returns the URI for this session.
static std::string uri(const std::string& connector,
const std::string& connectionString);
/// Utility function that teturns the URI formatted from supplied
/// arguments as "connector:///connectionString".
void setFeature(const std::string& name, bool state);
/// Set the state of a feature.
///
/// Features are a generic extension mechanism for session implementations.
/// and are defined by the underlying SessionImpl instance.
///
/// Throws a NotSupportedException if the requested feature is
/// not supported by the underlying implementation.
bool getFeature(const std::string& name) const;
/// Look up the state of a feature.
///
/// Features are a generic extension mechanism for session implementations.
/// and are defined by the underlying SessionImpl instance.
///
/// Throws a NotSupportedException if the requested feature is
/// not supported by the underlying implementation.
void setProperty(const std::string& name, const Poco::Any& value);
/// Set the value of a property.
///
/// Properties are a generic extension mechanism for session implementations.
/// and are defined by the underlying SessionImpl instance.
///
/// Throws a NotSupportedException if the requested property is
/// not supported by the underlying implementation.
Poco::Any getProperty(const std::string& name) const;
/// Look up the value of a property.
///
/// Properties are a generic extension mechanism for session implementations.
/// and are defined by the underlying SessionImpl instance.
///
/// Throws a NotSupportedException if the requested property is
/// not supported by the underlying implementation.
SessionImpl* impl();
/// Returns a pointer to the underlying SessionImpl.
private:
Session();
Poco::AutoPtr<SessionImpl> _pImpl;
StatementCreator _statementCreator;
};
//
// inlines
//
inline SharedPtr<StatementImpl> Session::createStatementImpl()
{
return _pImpl->createStatementImpl();
}
inline void Session::open(const std::string& connect)
{
_pImpl->open(connect);
}
inline void Session::close()
{
_pImpl->close();
}
inline bool Session::isConnected()
{
return _pImpl->isConnected();
}
inline void Session::reconnect()
{
_pImpl->reconnect();
}
inline bool Session::isGood()
{
return _pImpl->isGood();
}
inline void Session::setLoginTimeout(std::size_t timeout)
{
_pImpl->setLoginTimeout(timeout);
}
inline std::size_t Session::getLoginTimeout() const
{
return _pImpl->getLoginTimeout();
}
inline void Session::setConnectionTimeout(std::size_t timeout)
{
_pImpl->setConnectionTimeout(timeout);
}
inline std::size_t Session::getConnectionTimeout()
{
return _pImpl->getConnectionTimeout();
}
inline void Session::begin()
{
return _pImpl->begin();
}
inline void Session::commit()
{
return _pImpl->commit();
}
inline void Session::rollback()
{
return _pImpl->rollback();
}
inline bool Session::canTransact()
{
return _pImpl->canTransact();
}
inline bool Session::isTransaction()
{
return _pImpl->isTransaction();
}
inline void Session::setTransactionIsolation(Poco::UInt32 ti)
{
_pImpl->setTransactionIsolation(ti);
}
inline Poco::UInt32 Session::getTransactionIsolation()
{
return _pImpl->getTransactionIsolation();
}
inline bool Session::hasTransactionIsolation(Poco::UInt32 ti)
{
return _pImpl->hasTransactionIsolation(ti);
}
inline bool Session::isTransactionIsolation(Poco::UInt32 ti)
{
return _pImpl->isTransactionIsolation(ti);
}
inline std::string Session::connector() const
{
return _pImpl->connectorName();
}
inline std::string Session::uri(const std::string& connector,
const std::string& connectionString)
{
return SessionImpl::uri(connector, connectionString);
}
inline std::string Session::uri() const
{
return _pImpl->uri();
}
inline void Session::setFeature(const std::string& name, bool state)
{
_pImpl->setFeature(name, state);
}
inline bool Session::getFeature(const std::string& name) const
{
return const_cast<SessionImpl*>(_pImpl.get())->getFeature(name);
}
inline void Session::setProperty(const std::string& name, const Poco::Any& value)
{
_pImpl->setProperty(name, value);
}
inline Poco::Any Session::getProperty(const std::string& name) const
{
return const_cast<SessionImpl*>(_pImpl.get())->getProperty(name);
}
inline SessionImpl* Session::impl()
{
return _pImpl;
}
inline void swap(Session& s1, Session& s2)
{
s1.swap(s2);
}
} } // namespace Poco::Data
namespace std
{
template<>
inline void swap<Poco::Data::Session>(Poco::Data::Session& s1, Poco::Data::Session& s2) noexcept
/// Full template specalization of std:::swap for Session
{
s1.swap(s2);
}
}
#endif // Data_Session_INCLUDED

View File

@ -0,0 +1,99 @@
//
// SessionFactory.h
//
// Library: Data
// Package: DataCore
// Module: SessionFactory
//
// Definition of the SessionFactory class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_SessionFactory_INCLUDED
#define Data_SessionFactory_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/Connector.h"
#include "Poco/Data/Session.h"
#include "Poco/Mutex.h"
#include "Poco/SharedPtr.h"
#include "Poco/String.h"
#include <map>
namespace Poco {
namespace Data {
class Data_API SessionFactory
/// A SessionFactory is a singleton class that stores Connectors and allows to
/// create Sessions of the required type:
///
/// Session ses(SessionFactory::instance().create(connector, connectionString));
///
/// where the first param presents the type of session one wants to create (e.g. for SQLite one would choose "SQLite")
/// and the second param is the connection string that the connector requires to connect to the database.
///
/// A concrete example to open an SQLite database stored in the file "dummy.db" would be
///
/// Session ses(SessionFactory::instance().create(SQLite::Connector::KEY, "dummy.db"));
///
/// An even simpler way to create a session is to use the two argument constructor of Session, which
/// automatically invokes the SessionFactory:
///
/// Session ses("SQLite", "dummy.db");
{
public:
static SessionFactory& instance();
/// returns the static instance of the singleton.
void add(Connector* pIn);
/// Registers a Connector under its key at the factory. If a registration for that
/// key is already active, the first registration will be kept, only its reference count will be increased.
/// Always takes ownership of parameter pIn.
void remove(const std::string& key);
/// Lowers the reference count for the Connector registered under that key. If the count reaches zero,
/// the object is removed.
Session create(const std::string& key,
const std::string& connectionString,
std::size_t timeout = Session::LOGIN_TIMEOUT_DEFAULT);
/// Creates a Session for the given key with the connectionString. Throws an Poco:Data::UnknownDataBaseException
/// if no Connector is registered for that key.
Session create(const std::string& uri,
std::size_t timeout = Session::LOGIN_TIMEOUT_DEFAULT);
/// Creates a Session for the given URI (must be in key:///connectionString format).
/// Throws a Poco:Data::UnknownDataBaseException if no Connector is registered for the key.
private:
SessionFactory();
~SessionFactory();
SessionFactory(const SessionFactory&);
SessionFactory& operator = (const SessionFactory&);
struct SessionInfo
{
int cnt;
Poco::SharedPtr<Connector> ptrSI;
SessionInfo(Connector* pSI);
};
typedef std::map<std::string, SessionInfo, Poco::CILess> Connectors;
Connectors _connectors;
Poco::FastMutex _mutex;
};
} } // namespace Poco::Data
#endif // Data_SessionFactory_INCLUDED

View File

@ -0,0 +1,233 @@
//
// SessionImpl.h
//
// Library: Data
// Package: DataCore
// Module: SessionImpl
//
// Definition of the SessionImpl class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_SessionImpl_INCLUDED
#define Data_SessionImpl_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/RefCountedObject.h"
#include "Poco/String.h"
#include "Poco/Format.h"
#include "Poco/SharedPtr.h"
#include "Poco/AutoPtr.h"
#include "Poco/Any.h"
namespace Poco {
namespace Data {
class StatementImpl;
class Data_API SessionImpl: public Poco::RefCountedObject
/// Interface for Session functionality that subclasses must extend.
/// SessionImpl objects are noncopyable.
{
public:
using Ptr = Poco::AutoPtr<SessionImpl>;
static const std::size_t LOGIN_TIMEOUT_INFINITE = 0;
/// Infinite connection/login timeout.
static const std::size_t LOGIN_TIMEOUT_DEFAULT = 60;
/// Default connection/login timeout in seconds.
static const std::size_t CONNECTION_TIMEOUT_INFINITE = 0;
/// Infinite connection/login timeout.
static const std::size_t CONNECTION_TIMEOUT_DEFAULT = CONNECTION_TIMEOUT_INFINITE;
/// Default connection/login timeout in seconds.
SessionImpl(const std::string& connectionString,
std::size_t timeout = LOGIN_TIMEOUT_DEFAULT);
/// Creates the SessionImpl.
virtual ~SessionImpl();
/// Destroys the SessionImpl.
virtual Poco::SharedPtr<StatementImpl> createStatementImpl() = 0;
/// Creates a StatementImpl.
virtual void open(const std::string& connectionString = "") = 0;
/// Opens the session using the supplied string.
/// Can also be used with default empty string to reconnect
/// a disconnected session.
/// If the connection is not established within requested timeout
/// (specified in seconds), a ConnectionFailedException is thrown.
/// Zero timout means indefinite
virtual void close() = 0;
/// Closes the connection.
virtual bool isConnected() const = 0;
/// Returns true if session is connected, false otherwise.
virtual bool isGood() const;
/// Returns true if session is good and can be used, false otherwise.
///
/// The default implementation returns result of isConnected().
void setLoginTimeout(std::size_t timeout);
/// Sets the session login timeout value.
std::size_t getLoginTimeout() const;
/// Returns the session login timeout value.
virtual void setConnectionTimeout(std::size_t timeout) = 0;
/// Sets the session connection timeout value.
virtual std::size_t getConnectionTimeout() const = 0;
/// Returns the session connection timeout value.
void reconnect();
/// Closes the connection and opens it again.
virtual void reset() = 0;
/// Reset connection with dababase and clears session state, but without disconnecting
virtual void begin() = 0;
/// Starts a transaction.
virtual void commit() = 0;
/// Commits and ends a transaction.
virtual void rollback() = 0;
/// Aborts a transaction.
virtual bool canTransact() const = 0;
/// Returns true if session has transaction capabilities.
virtual bool isTransaction() const = 0;
/// Returns true iff a transaction is a transaction is in progress, false otherwise.
virtual void setTransactionIsolation(Poco::UInt32) = 0;
/// Sets the transaction isolation level.
virtual Poco::UInt32 getTransactionIsolation() const = 0;
/// Returns the transaction isolation level.
virtual bool hasTransactionIsolation(Poco::UInt32) const = 0;
/// Returns true iff the transaction isolation level corresponding
/// to the supplied bitmask is supported.
virtual bool isTransactionIsolation(Poco::UInt32) const = 0;
/// Returns true iff the transaction isolation level corresponds
/// to the supplied bitmask.
virtual const std::string& connectorName() const = 0;
/// Returns the name of the connector.
const std::string& connectionString() const;
/// Returns the connection string.
static std::string uri(const std::string& connector, const std::string& connectionString);
/// Returns formatted URI.
std::string uri() const;
/// Returns the URI for this session.
virtual void setFeature(const std::string& name, bool state) = 0;
/// Set the state of a feature.
///
/// Features are a generic extension mechanism for session implementations.
/// and are defined by the underlying SessionImpl instance.
///
/// Throws a NotSupportedException if the requested feature is
/// not supported by the underlying implementation.
virtual bool getFeature(const std::string& name) = 0;
/// Look up the state of a feature.
///
/// Features are a generic extension mechanism for session implementations.
/// and are defined by the underlying SessionImpl instance.
///
/// Throws a NotSupportedException if the requested feature is
/// not supported by the underlying implementation.
virtual void setProperty(const std::string& name, const Poco::Any& value) = 0;
/// Set the value of a property.
///
/// Properties are a generic extension mechanism for session implementations.
/// and are defined by the underlying SessionImpl instance.
///
/// Throws a NotSupportedException if the requested property is
/// not supported by the underlying implementation.
virtual Poco::Any getProperty(const std::string& name) = 0;
/// Look up the value of a property.
///
/// Properties are a generic extension mechanism for session implementations.
/// and are defined by the underlying SessionImpl instance.
///
/// Throws a NotSupportedException if the requested property is
/// not supported by the underlying implementation.
protected:
void setConnectionString(const std::string& connectionString);
/// Sets the connection string. Should only be called on
/// disconnected sessions. Throws InvalidAccessException when called on
/// a connected session.
private:
SessionImpl();
SessionImpl(const SessionImpl&);
SessionImpl& operator = (const SessionImpl&);
std::string _connectionString;
std::size_t _loginTimeout;
};
//
// inlines
//
inline const std::string& SessionImpl::connectionString() const
{
return _connectionString;
}
inline void SessionImpl::setLoginTimeout(std::size_t timeout)
{
_loginTimeout = timeout;
}
inline std::size_t SessionImpl::getLoginTimeout() const
{
return _loginTimeout;
}
inline std::string SessionImpl::uri(const std::string& connector,
const std::string& connectionString)
{
return format("%s:///%s", connector, connectionString);
}
inline std::string SessionImpl::uri() const
{
return uri(connectorName(), connectionString());
}
} } // namespace Poco::Data
#endif // Data_SessionImpl_INCLUDED

View File

@ -0,0 +1,233 @@
//
// SessionPool.h
//
// Library: Data
// Package: SessionPooling
// Module: SessionPool
//
// Definition of the SessionPool class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_SessionPool_INCLUDED
#define Data_SessionPool_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/PooledSessionHolder.h"
#include "Poco/Data/PooledSessionImpl.h"
#include "Poco/Data/Session.h"
#include "Poco/HashMap.h"
#include "Poco/Any.h"
#include "Poco/Timer.h"
#include "Poco/Mutex.h"
#include <list>
namespace Poco {
namespace Data {
class Data_API SessionPool: public RefCountedObject
/// This class implements session pooling for POCO Data.
///
/// Creating a connection to a database is often a time consuming
/// operation. Therefore it makes sense to reuse a session object
/// once it is no longer needed.
///
/// A SessionPool manages a collection of SessionImpl objects
/// (decorated with a PooledSessionImpl).
///
/// When a SessionImpl object is requested, the SessionPool first
/// looks in its set of already initialized SessionImpl for an
/// available object. If one is found, it is returned to the
/// client and marked as "in-use". If no SessionImpl is available,
/// the SessionPool attempts to create a new one for the client.
/// To avoid excessive creation of SessionImpl objects, a limit
/// can be set on the maximum number of objects.
/// Sessions found not to be connected to the database are purged
/// from the pool whenever one of the following events occurs:
///
/// - JanitorTimer event
/// - get() request
/// - putBack() request
///
/// Not connected idle sessions can not exist.
///
/// Usage example:
///
/// SessionPool pool("ODBC", "...");
/// ...
/// Session sess(pool.get());
/// ...
{
public:
SessionPool(const std::string& connector,
const std::string& connectionString,
int minSessions = 1,
int maxSessions = 32,
int idleTime = 60);
/// Creates the SessionPool for sessions with the given connector
/// and connectionString.
///
/// The pool allows for at most maxSessions sessions to be created.
/// If a session has been idle for more than idleTime seconds, and more than
/// minSessions sessions are in the pool, the session is automatically destroyed.
~SessionPool();
/// Destroys the SessionPool.
Session get();
/// Returns a Session.
///
/// If there are unused sessions available, one of the
/// unused sessions is recycled. Otherwise, a new session
/// is created.
///
/// If the maximum number of sessions for this pool has
/// already been created, a SessionPoolExhaustedException
/// is thrown.
template <typename T>
Session get(const std::string& name, const T& value)
/// Returns a Session with requested property set.
/// The property can be different from the default pool
/// value, in which case it is reset back to the pool
/// value when the session is reclaimed by the pool.
{
Session s = get();
_addPropertyMap.insert(AddPropertyMap::value_type(s.impl(),
std::make_pair(name, s.getProperty(name))));
s.setProperty(name, value);
return s;
}
Session get(const std::string& name, bool value);
/// Returns a Session with requested feature set.
/// The feature can be different from the default pool
/// value, in which case it is reset back to the pool
/// value when the session is reclaimed by the pool.
int capacity() const;
/// Returns the maximum number of sessions the SessionPool will manage.
int used() const;
/// Returns the number of sessions currently in use.
int idle() const;
/// Returns the number of idle sessions.
int dead();
/// Returns the number of not connected active sessions.
int allocated() const;
/// Returns the number of allocated sessions.
int available() const;
/// Returns the number of available (idle + remaining capacity) sessions.
std::string name() const;
/// Returns the name for this pool.
static std::string name(const std::string& connector,
const std::string& connectionString);
/// Returns the name formatted from supplied arguments as "connector:///connectionString".
void setFeature(const std::string& name, bool state);
/// Sets feature for all the sessions.
bool getFeature(const std::string& name);
/// Returns the requested feature.
void setProperty(const std::string& name, const Poco::Any& value);
/// Sets property for all sessions.
Poco::Any getProperty(const std::string& name);
/// Returns the requested property.
void shutdown();
/// Shuts down the session pool.
bool isActive() const;
/// Returns true if session pool is active (not shut down).
protected:
virtual void customizeSession(Session& session);
/// Can be overridden by subclass to perform custom initialization
/// of a newly created database session.
///
/// The default implementation does nothing.
typedef Poco::AutoPtr<PooledSessionHolder> PooledSessionHolderPtr;
typedef Poco::AutoPtr<PooledSessionImpl> PooledSessionImplPtr;
typedef std::list<PooledSessionHolderPtr> SessionList;
typedef Poco::HashMap<std::string, bool> FeatureMap;
typedef Poco::HashMap<std::string, Poco::Any> PropertyMap;
void purgeDeadSessions();
int deadImpl(SessionList& rSessions);
void applySettings(SessionImpl* pImpl);
void putBack(PooledSessionHolderPtr pHolder);
void onJanitorTimer(Poco::Timer&);
private:
typedef std::pair<std::string, Poco::Any> PropertyPair;
typedef std::pair<std::string, bool> FeaturePair;
typedef std::map<SessionImpl*, PropertyPair> AddPropertyMap;
typedef std::map<SessionImpl*, FeaturePair> AddFeatureMap;
SessionPool(const SessionPool&);
SessionPool& operator = (const SessionPool&);
void closeAll(SessionList& sessionList);
std::string _connector;
std::string _connectionString;
int _minSessions;
int _maxSessions;
int _idleTime;
int _nSessions;
SessionList _idleSessions;
SessionList _activeSessions;
Poco::Timer _janitorTimer;
FeatureMap _featureMap;
PropertyMap _propertyMap;
bool _shutdown;
AddPropertyMap _addPropertyMap;
AddFeatureMap _addFeatureMap;
mutable
Poco::Mutex _mutex;
friend class PooledSessionImpl;
};
inline std::string SessionPool::name(const std::string& connector,
const std::string& connectionString)
{
return Session::uri(connector, connectionString);
}
inline std::string SessionPool::name() const
{
return name(_connector, _connectionString);
}
inline bool SessionPool::isActive() const
{
return !_shutdown;
}
} } // namespace Poco::Data
#endif // Data_SessionPool_INCLUDED

View File

@ -0,0 +1,114 @@
//
// SessionPoolContainer.h
//
// Library: Data
// Package: SessionPooling
// Module: SessionPoolContainer
//
// Definition of the SessionPoolContainer class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_SessionPoolContainer_INCLUDED
#define Data_SessionPoolContainer_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/Session.h"
#include "Poco/Data/SessionPool.h"
#include "Poco/String.h"
#include "Poco/Mutex.h"
namespace Poco {
namespace Data {
class Data_API SessionPoolContainer
/// This class implements container of session pools.
{
public:
SessionPoolContainer();
/// Creates the SessionPoolContainer for sessions with the given session parameters.
~SessionPoolContainer();
/// Destroys the SessionPoolContainer.
void add(SessionPool* pPool);
/// Adds existing session pool to the container.
/// Throws SessionPoolExistsException if pool already exists.
Session add(const std::string& sessionKey,
const std::string& connectionString,
int minSessions = 1,
int maxSessions = 32,
int idleTime = 60);
/// Adds a new session pool to the container and returns a Session from
/// newly created pool. If pool already exists, request to add is silently
/// ignored and session is returned from the existing pool.
bool has(const std::string& name) const;
/// Returns true if the requested name exists, false otherwise.
bool isActive(const std::string& sessionKey,
const std::string& connectionString = "") const;
/// Returns true if the session is active (i.e. not shut down).
/// If connectionString is empty string, sessionKey must be a
/// fully qualified session name as registered with the pool
/// container.
Session get(const std::string& name);
/// Returns the requested Session.
/// Throws NotFoundException if session is not found.
SessionPool& getPool(const std::string& name);
/// Returns a SessionPool reference.
/// Throws NotFoundException if session is not found.
void remove(const std::string& name);
/// Removes a SessionPool.
int count() const;
/// Returns the number of session pols in the container.
void shutdown();
/// Shuts down all the held pools.
private:
typedef std::map<std::string, AutoPtr<SessionPool>, Poco::CILess> SessionPoolMap;
SessionPoolContainer(const SessionPoolContainer&);
SessionPoolContainer& operator = (const SessionPoolContainer&);
SessionPoolMap _sessionPools;
Poco::FastMutex _mutex;
};
inline bool SessionPoolContainer::has(const std::string& name) const
{
return _sessionPools.find(name) != _sessionPools.end();
}
inline void SessionPoolContainer::remove(const std::string& name)
{
_sessionPools.erase(name);
}
inline int SessionPoolContainer::count() const
{
return static_cast<int>(_sessionPools.size());
}
} } // namespace Poco::Data
#endif // Data_SessionPoolContainer_INCLUDED

View File

@ -0,0 +1,122 @@
//
// RowFormatter.h
//
// Library: Data
// Package: DataCore
// Module: SimpleRowFormatter
//
// Definition of the RowFormatter class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_SimpleRowFormatter_INCLUDED
#define Data_SimpleRowFormatter_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/RowFormatter.h"
namespace Poco {
namespace Data {
class Data_API SimpleRowFormatter: public RowFormatter
/// A simple row formatting class.
{
public:
//using NameVec = RowFormatter::NameVec;
//using NameVecPtr = RowFormatter::NameVecPtr;
//using ValueVec = RowFormatter::ValueVec;
static const int DEFAULT_COLUMN_WIDTH = 16;
static const int DEFAULT_SPACING = 1;
SimpleRowFormatter(std::streamsize columnWidth = DEFAULT_COLUMN_WIDTH, std::streamsize spacing = DEFAULT_SPACING);
/// Creates the SimpleRowFormatter and sets the column width to specified value.
SimpleRowFormatter(const SimpleRowFormatter& other);
/// Creates the copy of the supplied SimpleRowFormatter.
SimpleRowFormatter& operator = (const SimpleRowFormatter& row);
/// Assignment operator.
~SimpleRowFormatter();
/// Destroys the SimpleRowFormatter.
void swap(SimpleRowFormatter& other);
/// Swaps the row formatter with another one.
std::string& formatNames(const NameVecPtr pNames, std::string& formattedNames);
/// Formats the row field names.
std::string& formatValues(const ValueVec& vals, std::string& formattedValues);
/// Formats the row values.
int rowCount() const;
/// Returns row count.
void setColumnWidth(std::streamsize width);
/// Sets the column width.
std::streamsize getColumnWidth() const;
/// Returns the column width.
std::streamsize getSpacing() const;
/// Returns the spacing.
private:
std::streamsize _colWidth;
std::streamsize _spacing;
int _rowCount;
};
///
/// inlines
///
inline int SimpleRowFormatter::rowCount() const
{
return _rowCount;
}
inline void SimpleRowFormatter::setColumnWidth(std::streamsize columnWidth)
{
_colWidth = columnWidth;
}
inline std::streamsize SimpleRowFormatter::getColumnWidth() const
{
return _colWidth;
}
inline std::streamsize SimpleRowFormatter::getSpacing() const
{
return _spacing;
}
} } // namespace Poco::Data
namespace std
{
template<>
inline void swap<Poco::Data::SimpleRowFormatter>(Poco::Data::SimpleRowFormatter& s1,
Poco::Data::SimpleRowFormatter& s2)
/// Full template specalization of std:::swap for SimpleRowFormatter
{
s1.swap(s2);
}
}
#endif // Data_SimpleRowFormatter_INCLUDED

View File

@ -0,0 +1,827 @@
//
// Statement.h
//
// Library: Data
// Package: DataCore
// Module: Statement
//
// Definition of the Statement class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_Statement_INCLUDED
#define Data_Statement_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/StatementImpl.h"
#include "Poco/Data/Binding.h"
#include "Poco/Data/Range.h"
#include "Poco/Data/Bulk.h"
#include "Poco/Data/Row.h"
#include "Poco/Data/SimpleRowFormatter.h"
#include "Poco/SharedPtr.h"
#include "Poco/Mutex.h"
#include "Poco/ActiveMethod.h"
#include "Poco/ActiveResult.h"
#include "Poco/Format.h"
#include <algorithm>
namespace Poco {
namespace Data {
class AbstractBinding;
class AbstractExtraction;
class Session;
class Limit;
class Data_API Statement
/// A Statement is used to execute SQL statements.
/// It does not contain code of its own.
/// Its main purpose is to forward calls to the concrete StatementImpl stored inside.
/// Statement execution can be synchronous or asynchronous.
/// Synchronous ececution is achieved through execute() call, while asynchronous is
/// achieved through executeAsync() method call.
/// An asynchronously executing statement should not be copied during the execution.
///
/// Note:
///
/// Once set as asynchronous through 'async' manipulator, statement remains
/// asynchronous for all subsequent execution calls, both execute() and executeAsync().
/// However, calling executAsync() on a synchronous statement shall execute
/// asynchronously but without altering the underlying statement's synchronous nature.
///
/// Once asynchronous, a statement can be reverted back to synchronous state in two ways:
///
/// 1) By calling setAsync(false)
/// 2) By means of 'sync' or 'reset' manipulators
///
/// See individual functions documentation for more details.
///
/// Statement owns the RowFormatter, which can be provided externaly through setFormatter()
/// member function.
/// If no formatter is externally supplied to the statement, the SimpleRowFormatter is lazy
/// created and used.
{
public:
typedef void (*Manipulator)(Statement&);
using Result = ActiveResult<std::size_t>;
using ResultPtr = SharedPtr<Result>;
using AsyncExecMethod = ActiveMethod<std::size_t, bool, StatementImpl>;
using AsyncExecMethodPtr = SharedPtr<AsyncExecMethod>;
static const int WAIT_FOREVER = -1;
enum Storage
{
STORAGE_DEQUE = StatementImpl::STORAGE_DEQUE_IMPL,
STORAGE_VECTOR = StatementImpl::STORAGE_VECTOR_IMPL,
STORAGE_LIST = StatementImpl::STORAGE_LIST_IMPL,
STORAGE_UNKNOWN = StatementImpl::STORAGE_UNKNOWN_IMPL
};
Statement(StatementImpl::Ptr pImpl);
/// Creates the Statement.
explicit Statement(Session& session);
/// Creates the Statement for the given Session.
///
/// The following:
///
/// Statement stmt(sess);
/// stmt << "SELECT * FROM Table", ...
///
/// is equivalent to:
///
/// Statement stmt(sess << "SELECT * FROM Table", ...);
///
/// but in some cases better readable.
~Statement();
/// Destroys the Statement.
Statement(const Statement& stmt);
/// Copy constructor.
/// If the statement has been executed asynchronously and has not been
/// synchronized prior to copy operation (i.e. is copied while executing),
/// this constructor shall synchronize it.
Statement(Statement&& other) noexcept;
/// Move constructor.
Statement& operator = (const Statement& stmt);
/// Assignment operator.
Statement& operator = (Statement&& stmt) noexcept;
/// Move assignment.
void swap(Statement& other);
/// Swaps the statement with another one.
template <typename T>
Statement& operator << (const T& t)
/// Concatenates data with the SQL statement string.
{
_pImpl->add(t);
return *this;
}
Statement& operator , (Manipulator manip);
/// Handles manipulators, such as now, async, etc.
Statement& operator , (AbstractBinding::Ptr pBind);
/// Registers the Binding with the Statement by calling addBind().
Statement& addBind(AbstractBinding::Ptr pBind);
/// Registers a single binding with the statement.
void removeBind(const std::string& name);
/// Removes the all the bindings with specified name from the statement.
Statement& operator , (AbstractBindingVec& bindVec);
/// Registers the Binding vector with the Statement.
template <typename C>
Statement& addBinding(C& bindingCont, bool reset)
/// Registers binding container with the Statement.
{
if (reset) _pImpl->resetBinding();
typename C::iterator itAB = bindingCont.begin();
typename C::iterator itABEnd = bindingCont.end();
for (; itAB != itABEnd; ++itAB) addBind(*itAB);
return *this;
}
template <typename C>
Statement& bind(const C& value)
/// Adds a binding to the Statement. This can be used to implement
/// generic binding mechanisms and is a nicer syntax for:
///
/// statement , bind(value);
{
(*this) , Keywords::bind(value);
return *this;
}
Statement& operator , (AbstractExtraction::Ptr extract);
/// Registers objects used for extracting data with the Statement by
/// calling addExtract().
Statement& operator , (AbstractExtractionVec& extVec);
/// Registers the extraction vector with the Statement.
/// The vector is registered at position 0 (i.e. for the first returned data set).
Statement& operator , (AbstractExtractionVecVec& extVecVec);
/// Registers the vector of extraction vectors with the Statement.
template <typename C>
Statement& addExtraction(C& val, bool reset)
/// Registers extraction container with the Statement.
{
if (reset) _pImpl->resetExtraction();
typename C::iterator itAE = val.begin();
typename C::iterator itAEEnd = val.end();
for (; itAE != itAEEnd; ++itAE) addExtract(*itAE);
return *this;
}
template <typename C>
Statement& addExtractions(C& val)
/// Registers container of extraction containers with the Statement.
{
_pImpl->resetExtraction();
typename C::iterator itAEV = val.begin();
typename C::iterator itAEVEnd = val.end();
for (; itAEV != itAEVEnd; ++itAEV) addExtraction(*itAEV, false);
return *this;
}
Statement& addExtract(AbstractExtraction::Ptr pExtract);
/// Registers a single extraction with the statement.
Statement& operator , (const Bulk& bulk);
/// Sets the bulk execution mode (both binding and extraction) for this
/// statement.Statement must not have any extractors or binders set at the
/// time when this operator is applied.
/// Failure to adhere to the above constraint shall result in
/// InvalidAccessException.
Statement& operator , (BulkFnType);
/// Sets the bulk execution mode (both binding and extraction) for this
/// statement.Statement must not have any extractors or binders set at the
/// time when this operator is applied.
/// Additionally, this function requires limit to be set in order to
/// determine the bulk size.
/// Failure to adhere to the above constraints shall result in
/// InvalidAccessException.
Statement& operator , (const Limit& extrLimit);
/// Sets a limit on the maximum number of rows a select is allowed to return.
///
/// Set per default to zero to Limit::LIMIT_UNLIMITED, which disables the limit.
Statement& operator , (RowFormatter::Ptr pRowFformatter);
/// Sets the row formatter for the statement.
Statement& operator , (const Range& extrRange);
/// Sets a an extraction range for the maximum number of rows a select is allowed to return.
///
/// Set per default to Limit::LIMIT_UNLIMITED which disables the range.
Statement& operator , (char value);
/// Adds the value to the list of values to be supplied to the SQL string formatting function.
Statement& operator , (Poco::UInt8 value);
/// Adds the value to the list of values to be supplied to the SQL string formatting function.
Statement& operator , (Poco::Int8 value);
/// Adds the value to the list of values to be supplied to the SQL string formatting function.
Statement& operator , (Poco::UInt16 value);
/// Adds the value to the list of values to be supplied to the SQL string formatting function.
Statement& operator , (Poco::Int16 value);
/// Adds the value to the list of values to be supplied to the SQL string formatting function.
Statement& operator , (Poco::UInt32 value);
/// Adds the value to the list of values to be supplied to the SQL string formatting function.
Statement& operator , (Poco::Int32 value);
/// Adds the value to the list of values to be supplied to the SQL string formatting function.
#ifndef POCO_INT64_IS_LONG
Statement& operator , (long value);
/// Adds the value to the list of values to be supplied to the SQL string formatting function.
Statement& operator , (unsigned long value);
/// Adds the value to the list of values to be supplied to the SQL string formatting function.
#endif
Statement& operator , (Poco::UInt64 value);
/// Adds the value to the list of values to be supplied to the SQL string formatting function.
Statement& operator , (Poco::Int64 value);
/// Adds the value to the list of values to be supplied to the SQL string formatting function.
Statement& operator , (double value);
/// Adds the value to the list of values to be supplied to the SQL string formatting function.
Statement& operator , (float value);
/// Adds the value to the list of values to be supplied to the SQL string formatting function.
Statement& operator , (bool value);
/// Adds the value to the list of values to be supplied to the SQL string formatting function.
Statement& operator , (const std::string& value);
/// Adds the value to the list of values to be supplied to the SQL string formatting function.
Statement& operator , (const char* value);
/// Adds the value to the list of values to be supplied to the SQL string formatting function.
const std::string& toString() const;
/// Creates a string from the accumulated SQL statement.
std::size_t execute(bool reset = true);
/// Executes the statement synchronously or asynchronously.
/// Stops when either a limit is hit or the whole statement was executed.
/// Returns the number of rows extracted from the database (for statements
/// returning data) or number of rows affected (for all other statements).
/// If reset is true (default), associated storage is reset and reused.
/// Otherwise, the results from this execution step are appended.
/// Reset argument has no meaning for unlimited statements that return all rows.
/// If isAsync() returns true, the statement is executed asynchronously
/// and the return value from this function is zero.
/// The result of execution (i.e. number of returned or affected rows) can be
/// obtained by calling wait() on the statement at a later point in time.
const Result& executeAsync(bool reset = true);
/// Executes the statement asynchronously.
/// Stops when either a limit is hit or the whole statement was executed.
/// Returns immediately. Calling wait() (on either the result returned from this
/// call or the statement itself) returns the number of rows extracted or number
/// of rows affected by the statement execution.
/// When executed on a synchronous statement, this method does not alter the
/// statement's synchronous nature.
void setAsync(bool async = true);
/// Sets the asynchronous flag. If this flag is true, executeAsync() is called
/// from the now() manipulator. This setting does not affect the statement's
/// capability to be executed synchronously by directly calling execute().
bool isAsync() const;
/// Returns true if statement was marked for asynchronous execution.
std::size_t wait(long milliseconds = WAIT_FOREVER);
/// Waits for the execution completion for asynchronous statements or
/// returns immediately for synchronous ones. The return value for
/// asynchronous statement is the execution result (i.e. number of
/// rows retrieved). For synchronous statements, the return value is zero.
bool initialized();
/// Returns true if the statement was initialized (i.e. not executed yet).
bool paused();
/// Returns true if the statement was paused (a range limit stopped it
/// and there is more work to do).
bool done();
/// Returns true if the statement was completely executed or false if a range limit stopped it
/// and there is more work to do. When no limit is set, it will always return true after calling execute().
Statement& reset(Session& session);
/// Resets the Statement so that it can be filled with a new SQL command.
bool canModifyStorage();
/// Returns true if statement is in a state that allows the internal storage to be modified.
Storage storage() const;
/// Returns the internal storage type for the statement.
void setStorage(const std::string& storage);
/// Sets the internal storage type for the statement.
const std::string& getStorage() const;
/// Returns the internal storage type for the statement.
std::size_t columnsExtracted(int dataSet = StatementImpl::USE_CURRENT_DATA_SET) const;
/// Returns the number of columns returned for current data set.
/// Default value indicates current data set (if any).
std::size_t rowsExtracted(int dataSet = StatementImpl::USE_CURRENT_DATA_SET) const;
/// Returns the number of rows returned for current data set during last statement
/// execution. Default value indicates current data set (if any).
std::size_t subTotalRowCount(int dataSet = StatementImpl::USE_CURRENT_DATA_SET) const;
/// Returns the number of rows extracted so far for the data set.
/// Default value indicates current data set (if any).
std::size_t extractionCount() const;
/// Returns the number of extraction storage buffers associated
/// with the current data set.
std::size_t dataSetCount() const;
/// Returns the number of data sets associated with the statement.
std::size_t nextDataSet();
/// Returns the index of the next data set.
std::size_t previousDataSet();
/// Returns the index of the previous data set.
bool hasMoreDataSets() const;
/// Returns false if the current data set index points to the last
/// data set. Otherwise, it returns true.
void setRowFormatter(RowFormatter::Ptr pRowFormatter);
/// Sets the row formatter for this statement.
/// Statement takes the ownership of the formatter.
protected:
using ImplPtr = StatementImpl::Ptr;
const AbstractExtractionVec& extractions() const;
/// Returns the extractions vector.
const MetaColumn& metaColumn(std::size_t pos) const;
/// Returns the type for the column at specified position.
const MetaColumn& metaColumn(const std::string& name) const;
/// Returns the type for the column with specified name.
bool isNull(std::size_t col, std::size_t row) const;
/// Returns true if the current row value at column pos is null.
bool isBulkExtraction() const;
/// Returns true if this statement extracts data in bulk.
ImplPtr impl() const;
/// Returns pointer to statement implementation.
const RowFormatter::Ptr& getRowFormatter();
/// Returns the row formatter for this statement.
Session session();
/// Returns the underlying session.
private:
const Result& doAsyncExec(bool reset = true);
/// Asynchronously executes the statement.
template <typename T>
Statement& commaPODImpl(const T& val)
{
_arguments.push_back(val);
return *this;
}
StatementImpl::Ptr _pImpl;
// asynchronous execution related members
bool _async;
mutable ResultPtr _pResult;
Mutex _mutex;
AsyncExecMethodPtr _pAsyncExec;
std::vector<Any> _arguments;
RowFormatter::Ptr _pRowFormatter;
mutable std::string _stmtString;
};
//
// inlines
inline std::size_t Statement::subTotalRowCount(int dataSet) const
{
return _pImpl->subTotalRowCount(dataSet);
}
namespace Keywords {
//
// Manipulators
//
inline void Data_API now(Statement& statement)
/// Enforces immediate execution of the statement.
/// If _isAsync flag has been set, execution is invoked asynchronously.
{
statement.execute();
}
inline void Data_API sync(Statement& statement)
/// Sets the _isAsync flag to false, signalling synchronous execution.
/// Synchronous execution is default, so specifying this manipulator
/// only makes sense if async() was called for the statement before.
{
statement.setAsync(false);
}
inline void Data_API async(Statement& statement)
/// Sets the _async flag to true, signalling asynchronous execution.
{
statement.setAsync(true);
}
inline void Data_API deque(Statement& statement)
/// Sets the internal storage to std::deque.
/// std::deque is default storage, so specifying this manipulator
/// only makes sense if list() or deque() were called for the statement before.
{
if (!statement.canModifyStorage())
throw InvalidAccessException("Storage not modifiable.");
statement.setStorage("deque");
}
inline void Data_API vector(Statement& statement)
/// Sets the internal storage to std::vector.
{
if (!statement.canModifyStorage())
throw InvalidAccessException("Storage not modifiable.");
statement.setStorage("vector");
}
inline void Data_API list(Statement& statement)
/// Sets the internal storage to std::list.
{
if (!statement.canModifyStorage())
throw InvalidAccessException("Storage not modifiable.");
statement.setStorage("list");
}
inline void Data_API reset(Statement& statement)
/// Sets all internal settings to their respective default values.
{
if (!statement.canModifyStorage())
throw InvalidAccessException("Storage not modifiable.");
statement.setStorage("deque");
statement.setAsync(false);
}
} // namespace Keywords
//
// inlines
//
inline Statement& Statement::operator , (RowFormatter::Ptr pRowFformatter)
{
_pRowFormatter = pRowFformatter;
return *this;
}
inline Statement& Statement::operator , (char value)
{
return commaPODImpl(value);
}
inline Statement& Statement::operator , (Poco::UInt8 value)
{
return commaPODImpl(value);
}
inline Statement& Statement::operator , (Poco::Int8 value)
{
return commaPODImpl(value);
}
inline Statement& Statement::operator , (Poco::UInt16 value)
{
return commaPODImpl(value);
}
inline Statement& Statement::operator , (Poco::Int16 value)
{
return commaPODImpl(value);
}
inline Statement& Statement::operator , (Poco::UInt32 value)
{
return commaPODImpl(value);
}
inline Statement& Statement::operator , (Poco::Int32 value)
{
return commaPODImpl(value);
}
#ifndef POCO_INT64_IS_LONG
inline Statement& Statement::operator , (long value)
{
return commaPODImpl(value);
}
inline Statement& Statement::operator , (unsigned long value)
{
return commaPODImpl(value);
}
#endif
inline Statement& Statement::operator , (Poco::UInt64 value)
{
return commaPODImpl(value);
}
inline Statement& Statement::operator , (Poco::Int64 value)
{
return commaPODImpl(value);
}
inline Statement& Statement::operator , (double value)
{
return commaPODImpl(value);
}
inline Statement& Statement::operator , (float value)
{
return commaPODImpl(value);
}
inline Statement& Statement::operator , (bool value)
{
return commaPODImpl(value);
}
inline Statement& Statement::operator , (const std::string& value)
{
return commaPODImpl(value);
}
inline Statement& Statement::operator , (const char* value)
{
return commaPODImpl(std::string(value));
}
inline void Statement::removeBind(const std::string& name)
{
_pImpl->removeBind(name);
}
inline Statement& Statement::operator , (AbstractBinding::Ptr pBind)
{
return addBind(pBind);
}
inline Statement& Statement::operator , (AbstractBindingVec& bindVec)
{
return addBinding(bindVec, false);
}
inline Statement& Statement::operator , (AbstractExtraction::Ptr pExtract)
{
return addExtract(pExtract);
}
inline Statement& Statement::operator , (AbstractExtractionVec& extVec)
{
return addExtraction(extVec, false);
}
inline Statement& Statement::operator , (AbstractExtractionVecVec& extVecVec)
{
return addExtractions(extVecVec);
}
inline Statement::ImplPtr Statement::impl() const
{
return _pImpl;
}
inline const std::string& Statement::toString() const
{
return _stmtString = _pImpl->toString();
}
inline const AbstractExtractionVec& Statement::extractions() const
{
return _pImpl->extractions();
}
inline const MetaColumn& Statement::metaColumn(std::size_t pos) const
{
return _pImpl->metaColumn(pos);
}
inline const MetaColumn& Statement::metaColumn(const std::string& name) const
{
return _pImpl->metaColumn(name);
}
inline void Statement::setStorage(const std::string& storage)
{
_pImpl->setStorage(storage);
}
inline std::size_t Statement::extractionCount() const
{
return _pImpl->extractionCount();
}
inline std::size_t Statement::columnsExtracted(int dataSet) const
{
return _pImpl->columnsExtracted(dataSet);
}
inline std::size_t Statement::rowsExtracted(int dataSet) const
{
return _pImpl->rowsExtracted(dataSet);
}
inline std::size_t Statement::dataSetCount() const
{
return _pImpl->dataSetCount();
}
inline std::size_t Statement::nextDataSet()
{
return _pImpl->activateNextDataSet();
}
inline std::size_t Statement::previousDataSet()
{
return _pImpl->activatePreviousDataSet();
}
inline bool Statement::hasMoreDataSets() const
{
return _pImpl->hasMoreDataSets();
}
inline Statement::Storage Statement::storage() const
{
return static_cast<Storage>(_pImpl->getStorage());
}
inline bool Statement::canModifyStorage()
{
return (0 == extractionCount()) && (initialized() || done());
}
inline bool Statement::initialized()
{
return _pImpl->getState() == StatementImpl::ST_INITIALIZED;
}
inline bool Statement::paused()
{
return _pImpl->getState() == StatementImpl::ST_PAUSED;
}
inline bool Statement::done()
{
return _pImpl->getState() == StatementImpl::ST_DONE;
}
inline bool Statement::isNull(std::size_t col, std::size_t row) const
{
return _pImpl->isNull(col, row);
}
inline bool Statement::isBulkExtraction() const
{
return _pImpl->isBulkExtraction();
}
inline bool Statement::isAsync() const
{
return _async;
}
inline void Statement::setRowFormatter(RowFormatter::Ptr pRowFormatter)
{
_pRowFormatter = pRowFormatter;
}
inline const RowFormatter::Ptr& Statement::getRowFormatter()
{
if (!_pRowFormatter) _pRowFormatter = new SimpleRowFormatter;
return _pRowFormatter;
}
inline void swap(Statement& s1, Statement& s2)
{
s1.swap(s2);
}
} } // namespace Poco::Data
namespace std
{
template<>
inline void swap<Poco::Data::Statement>(Poco::Data::Statement& s1, Poco::Data::Statement& s2) noexcept
/// Full template specalization of std:::swap for Statement
{
s1.swap(s2);
}
}
#endif // Data_Statement_INCLUDED

View File

@ -0,0 +1,79 @@
//
// StatementCreator.h
//
// Library: Data
// Package: DataCore
// Module: StatementCreator
//
// Definition of the StatementCreator class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_StatementCreator_INCLUDED
#define Data_StatementCreator_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/SessionImpl.h"
#include "Poco/Data/Statement.h"
#include "Poco/AutoPtr.h"
namespace Poco {
namespace Data {
class Data_API StatementCreator
/// A StatementCreator creates Statements.
{
public:
StatementCreator();
/// Creates an unitialized StatementCreator.
StatementCreator(Poco::AutoPtr<SessionImpl> ptrImpl);
/// Creates a StatementCreator.
StatementCreator(const StatementCreator& other);
/// Creates a StatementCreator by copying another one.
StatementCreator(StatementCreator&& other) noexcept;
/// Creates a StatementCreator by moving another one.
~StatementCreator();
/// Destroys the StatementCreator.
StatementCreator& operator = (const StatementCreator& other);
/// Assignment operator.
StatementCreator& operator = (StatementCreator&& other) noexcept;
/// Assignment operator.
void swap(StatementCreator& other);
/// Swaps the StatementCreator with another one.
template <typename T>
Statement operator << (const T& t)
/// Creates a Statement.
{
if (!_ptrImpl->isConnected())
throw NotConnectedException(_ptrImpl->connectionString());
Statement stmt(_ptrImpl->createStatementImpl());
stmt << t;
return stmt;
}
private:
Poco::AutoPtr<SessionImpl> _ptrImpl;
};
} } // namespace Poco::Data
#endif // Data_StatementCreator_INCLUDED

View File

@ -0,0 +1,632 @@
//
// StatementImpl.h
//
// Library: Data
// Package: DataCore
// Module: StatementImpl
//
// Definition of the StatementImpl class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_StatementImpl_INCLUDED
#define Data_StatementImpl_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/AbstractBinding.h"
#include "Poco/Data/AbstractExtraction.h"
#include "Poco/Data/Range.h"
#include "Poco/Data/Bulk.h"
#include "Poco/Data/Column.h"
#include "Poco/Data/Extraction.h"
#include "Poco/Data/BulkExtraction.h"
#include "Poco/Data/SessionImpl.h"
#include "Poco/RefCountedObject.h"
#include "Poco/String.h"
#include "Poco/Format.h"
#include "Poco/Exception.h"
#include <vector>
#include <list>
#include <deque>
#include <string>
#include <sstream>
namespace Poco {
namespace Data {
class Data_API StatementImpl
/// StatementImpl interface that subclasses must implement to define database dependent query execution.
///
/// StatementImpl's are noncopyable.
{
public:
using Ptr = Poco::SharedPtr<StatementImpl>;
enum State
{
ST_INITIALIZED,
ST_COMPILED,
ST_BOUND,
ST_PAUSED,
ST_DONE,
ST_RESET
};
enum Storage
{
STORAGE_DEQUE_IMPL,
STORAGE_VECTOR_IMPL,
STORAGE_LIST_IMPL,
STORAGE_UNKNOWN_IMPL
};
enum BulkType
{
BULK_UNDEFINED,
/// Bulk mode not defined yet.
BULK_BINDING,
/// Binding in bulk mode.
/// If extraction is present in the same statement,
/// it must also be bulk.
BULK_EXTRACTION,
/// Extraction in bulk mode.
/// If binding is present in the same statement,
/// it must also be bulk.
BULK_FORBIDDEN
/// Bulk forbidden.
/// Happens when the statement has already been
/// configured as non-bulk.
};
static const std::string DEQUE;
static const std::string VECTOR;
static const std::string LIST;
static const std::string UNKNOWN;
static const int USE_CURRENT_DATA_SET = -1;
StatementImpl(SessionImpl& rSession);
/// Creates the StatementImpl.
virtual ~StatementImpl();
/// Destroys the StatementImpl.
template <typename T>
void add(const T& t)
/// Appends SQL statement (fragments).
{
_ostr << t;
}
void addBind(AbstractBinding::Ptr pBinding);
/// Registers the Binding with the StatementImpl.
void removeBind(const std::string& name);
/// Unregisters all the bindings having specified name with the StatementImpl.
/// Bindings are released and, if this class was the sole owner, deleted.
void addExtract(AbstractExtraction::Ptr pExtraction);
/// Registers objects used for extracting data with the StatementImpl.
void setExtractionLimit(const Limit& extrLimit);
/// Changes the extractionLimit to extrLimit.
/// Per default no limit (EXTRACT_UNLIMITED) is set.
std::string toString() const;
/// Create a string version of the SQL statement.
std::size_t execute(const bool& reset = true);
/// Executes a statement. Returns the number of rows
/// extracted for statements returning data or number of rows
/// affected for all other statements (insert, update, delete).
/// If reset is true (default), the underlying bound storage is
/// reset and reused. In case of containers, this means they are
/// cleared and resized to accomodate the number of rows returned by
/// this execution step. When reset is false, data is appended to the
/// bound containers during multiple execute calls.
void reset();
/// Resets the statement, so that we can reuse all bindings and re-execute again.
State getState() const;
/// Returns the state of the Statement.
void setStorage(Storage storage);
/// Sets the storage type for this statement;
void setStorage(const std::string& storage);
/// Sets the storage type for this statement;
Storage getStorage() const;
/// Returns the storage type for this statement.
std::size_t extractionCount() const;
/// Returns the number of extraction storage buffers associated
/// with the statement.
std::size_t dataSetCount() const;
/// Returns the number of data sets associated with the statement.
protected:
virtual std::size_t columnsReturned() const = 0;
/// Returns number of columns returned by query.
virtual int affectedRowCount() const = 0;
/// Returns the number of affected rows.
/// Used to find out the number of rows affected by insert, delete or update.
///
/// Some back-ends may return a negative number in certain circumstances (e.g.
/// some ODBC drivers when this function is called after a select statement
/// execution).
virtual const MetaColumn& metaColumn(std::size_t pos) const = 0;
/// Returns column meta data.
const MetaColumn& metaColumn(const std::string& name) const;
/// Returns column meta data.
virtual bool hasNext() = 0;
/// Returns true if a call to next() will return data.
///
/// Note that the implementation must support
/// several consecutive calls to hasNext without data getting lost,
/// ie. hasNext(); hasNext(); next() must be equal to hasNext(); next();
virtual std::size_t next() = 0;
/// Retrieves the next row or set of rows from the resultset and
/// returns the number of rows retreved.
///
/// Will throw, if the resultset is empty.
/// Expects the statement to be compiled and bound.
virtual bool canBind() const = 0;
/// Returns true if another bind is possible.
virtual bool canCompile() const = 0;
/// Returns true if another compile is possible.
virtual void compileImpl() = 0;
/// Compiles the statement, doesn't bind yet.
virtual void bindImpl() = 0;
/// Binds parameters.
virtual AbstractExtraction::ExtractorPtr extractor() = 0;
/// Returns the concrete extractor used by the statement.
const AbstractExtractionVec& extractions() const;
/// Returns the const reference to extractions vector.
AbstractExtractionVec& extractions();
/// Returns the reference to extractions vector.
void fixupExtraction();
/// Sets the AbstractExtractor at the extractors.
Limit::SizeT getExtractionLimit();
/// Returns the extraction limit value.
const Limit& extractionLimit() const;
/// Returns the extraction limit.
std::size_t columnsExtracted(int dataSet = USE_CURRENT_DATA_SET) const;
/// Returns the number of columns that the extractors handle.
std::size_t rowsExtracted(int dataSet = USE_CURRENT_DATA_SET) const;
/// Returns the number of rows extracted for current data set.
/// Default value (USE_CURRENT_DATA_SET) indicates current data set (if any).
std::size_t subTotalRowCount(int dataSet = USE_CURRENT_DATA_SET) const;
/// Returns the number of rows extracted so far for the data set.
/// Default value indicates current data set (if any).
void makeExtractors(std::size_t count);
/// Determines the type of the internal extraction container and
/// calls the extraction creation function (addInternalExtract)
/// with appropriate data type and container type arguments.
///
/// This function is only called in cases when there is data
/// returned by query, but no data storage supplied by user.
///
/// The type of the internal container is determined in the
/// following order:
/// 1. If statement has the container type set, the type is used.
/// 2. If statement does not have the container type set,
/// session is queried for container type setting. If the
/// session container type setting is found, it is used.
/// 3. If neither session nor statement have the internal
/// container type set, std::deque is used.
///
/// Supported internal extraction container types are:
/// - std::deque (default)
/// - std::vector
/// - std::list
SessionImpl& session();
/// Rteurns session associated with this statement.
virtual AbstractBinding::BinderPtr binder() = 0;
/// Returns the concrete binder used by the statement.
const AbstractBindingVec& bindings() const;
/// Returns the const reference to bindings vector.
AbstractBindingVec& bindings();
/// Returns the reference to bindings.
void fixupBinding();
/// Sets the AbstractBinder at the bindings.
void resetBinding();
/// Resets binding so it can be reused again.
virtual bool isStoredProcedure() const;
/// Returns true if the statement is stored procedure.
/// Used as a help to determine whether to automatically create the
/// internal extractions when no outside extraction is supplied.
/// The reason for this function is to prevent unnecessary internal
/// extraction creation in cases (behavior exhibited by some ODBC drivers)
/// when there is data available from the stored procedure call
/// statement execution but no external extraction is supplied (as is
/// usually the case when stored procedures are called). In such cases
/// no storage is needed because output parameters serve as storage.
/// At the Data framework level, this function always returns false.
/// When connector-specific behavior is desired, it should be overriden
/// by the statement implementation.
std::size_t currentDataSet() const;
/// Returns the current data set.
std::size_t activateNextDataSet();
/// Returns the next data set index, or throws NoDataException if the last
/// data set was reached.
std::size_t activatePreviousDataSet();
/// Returns the previous data set index, or throws NoDataException if the last
/// data set was reached.
bool hasMoreDataSets() const;
/// Returns true if there are data sets not activated yet.
private:
void compile();
/// Compiles the statement.
void bind();
/// Binds the statement, if not yet bound.
std::size_t executeWithLimit();
/// Executes with an upper limit set. Returns the number of rows
/// extracted for statements returning data or number of rows
/// affected for all other statements (insert, update, delete).
std::size_t executeWithoutLimit();
/// Executes without an upper limit set. Returns the number of rows
/// extracted for statements returning data or number of rows
/// affected for all other statements (insert, update, delete).
void resetExtraction();
/// Resets extraction so it can be reused again.
template <class C>
SharedPtr<InternalExtraction<C>> createExtract(const MetaColumn& mc)
{
C* pData = new C;
Column<C>* pCol = new Column<C>(mc, pData);
return new InternalExtraction<C>(*pData, pCol, Poco::UInt32(currentDataSet()));
}
template <class C>
SharedPtr<InternalBulkExtraction<C>> createBulkExtract(const MetaColumn& mc)
{
C* pData = new C;
Column<C>* pCol = new Column<C>(mc, pData);
return new InternalBulkExtraction<C>(*pData,
pCol,
static_cast<Poco::UInt32>(getExtractionLimit()),
Position(static_cast<Poco::UInt32>(currentDataSet())));
}
template <class T>
void addInternalExtract(const MetaColumn& mc)
/// Creates and adds the internal extraction.
///
/// The decision about internal extraction container is done
/// in a following way:
///
/// If this statement has _storage member set, that setting
/// overrides the session setting for storage, otherwise the
/// session setting is used.
/// If neither this statement nor the session have the storage
/// type set, std::vector is the default container type used.
{
std::string storage;
switch (_storage)
{
case STORAGE_DEQUE_IMPL:
storage = DEQUE; break;
case STORAGE_VECTOR_IMPL:
storage = VECTOR; break;
case STORAGE_LIST_IMPL:
storage = LIST; break;
case STORAGE_UNKNOWN_IMPL:
storage = AnyCast<std::string>(session().getProperty("storage"));
break;
}
if (storage.empty()) storage = DEQUE;
if (0 == icompare(DEQUE, storage))
{
if (!isBulkExtraction())
addExtract(createExtract<std::deque<T>>(mc));
else
addExtract(createBulkExtract<std::deque<T>>(mc));
}
else if (0 == icompare(VECTOR, storage))
{
if (!isBulkExtraction())
addExtract(createExtract<std::vector<T>>(mc));
else
addExtract(createBulkExtract<std::vector<T>>(mc));
}
else if (0 == icompare(LIST, storage))
{
if (!isBulkExtraction())
addExtract(createExtract<std::list<T>>(mc));
else
addExtract(createBulkExtract<std::list<T>>(mc));
}
}
bool isNull(std::size_t col, std::size_t row) const;
/// Returns true if the value in [col, row] is null.
void forbidBulk();
/// Forbids bulk operations.
void setBulkBinding();
/// Sets the bulk binding flag.
void setBulkExtraction(const Bulk& l);
/// Sets the bulk extraction flag and extraction limit.
void resetBulk();
/// Resets the bulk extraction and binding flag.
bool bulkBindingAllowed() const;
/// Returns true if statement can be set to bind data in bulk.
/// Once bulk binding is set for a statement, it can be
/// neither altered nor mixed with non-bulk mode binding.
bool bulkExtractionAllowed() const;
/// Returns true if statement can be set to extract data in bulk.
/// Once bulk extraction is set for a statement, it can be
/// neither altered nor mixed with non-bulk mode extraction.
bool isBulkBinding() const;
/// Returns true if statement is set to bind data in bulk.
bool isBulkExtraction() const;
/// Returns true if statement is set to extract data in bulk.
bool isBulkSupported() const;
/// Returns true if connector and session support bulk operation.
void formatSQL(std::vector<Any>& arguments);
/// Formats the SQL string by filling in placeholders with values from supplied vector.
void assignSubTotal(bool reset);
StatementImpl(const StatementImpl& stmt);
StatementImpl& operator = (const StatementImpl& stmt);
using CountVec = std::vector<std::size_t>;
State _state;
Limit _extrLimit;
std::size_t _lowerLimit;
std::vector<int> _columnsExtracted;
SessionImpl& _rSession;
Storage _storage;
std::ostringstream _ostr;
AbstractBindingVec _bindings;
AbstractExtractionVecVec _extractors;
std::size_t _curDataSet;
BulkType _bulkBinding;
BulkType _bulkExtraction;
CountVec _subTotalRowCount;
friend class Statement;
};
//
// inlines
//
inline void StatementImpl::addBind(AbstractBinding::Ptr pBinding)
{
poco_check_ptr (pBinding);
_bindings.push_back(pBinding);
}
inline std::string StatementImpl::toString() const
{
return _ostr.str();
}
inline const AbstractBindingVec& StatementImpl::bindings() const
{
return _bindings;
}
inline AbstractBindingVec& StatementImpl::bindings()
{
return _bindings;
}
inline const AbstractExtractionVec& StatementImpl::extractions() const
{
poco_assert (_curDataSet < _extractors.size());
return _extractors[_curDataSet];
}
inline AbstractExtractionVec& StatementImpl::extractions()
{
poco_assert (_curDataSet < _extractors.size());
return _extractors[_curDataSet];
}
inline StatementImpl::State StatementImpl::getState() const
{
return _state;
}
inline SessionImpl& StatementImpl::session()
{
return _rSession;
}
inline void StatementImpl::setStorage(Storage storage)
{
_storage = storage;
}
inline StatementImpl::Storage StatementImpl::getStorage() const
{
return _storage;
}
inline std::size_t StatementImpl::extractionCount() const
{
return static_cast<std::size_t>(extractions().size());
}
inline std::size_t StatementImpl::dataSetCount() const
{
return static_cast<std::size_t>(_extractors.size());
}
inline bool StatementImpl::isStoredProcedure() const
{
return false;
}
inline bool StatementImpl::isNull(std::size_t col, std::size_t row) const
{
try
{
return extractions().at(col)->isNull(row);
}
catch (std::out_of_range& ex)
{
throw RangeException(ex.what());
}
}
inline std::size_t StatementImpl::currentDataSet() const
{
return _curDataSet;
}
inline Limit::SizeT StatementImpl::getExtractionLimit()
{
return _extrLimit.value();
}
inline const Limit& StatementImpl::extractionLimit() const
{
return _extrLimit;
}
inline void StatementImpl::forbidBulk()
{
_bulkBinding = BULK_FORBIDDEN;
_bulkExtraction = BULK_FORBIDDEN;
}
inline void StatementImpl::setBulkBinding()
{
_bulkBinding = BULK_BINDING;
}
inline bool StatementImpl::bulkBindingAllowed() const
{
return BULK_UNDEFINED == _bulkBinding ||
BULK_BINDING == _bulkBinding;
}
inline bool StatementImpl::bulkExtractionAllowed() const
{
return BULK_UNDEFINED == _bulkExtraction ||
BULK_EXTRACTION == _bulkExtraction;
}
inline bool StatementImpl::isBulkBinding() const
{
return BULK_BINDING == _bulkBinding;
}
inline bool StatementImpl::isBulkExtraction() const
{
return BULK_EXTRACTION == _bulkExtraction;
}
inline void StatementImpl::resetBulk()
{
_bulkExtraction = BULK_UNDEFINED;
_bulkBinding = BULK_UNDEFINED;\
setExtractionLimit(Limit(Limit::LIMIT_UNLIMITED, false, false));
}
inline bool StatementImpl::isBulkSupported() const
{
return _rSession.getFeature("bulk");
}
inline bool StatementImpl::hasMoreDataSets() const
{
return currentDataSet() + 1 < dataSetCount();
}
} } // namespace Poco::Data
#endif // Data_StatementImpl_INCLUDED

View File

@ -0,0 +1,229 @@
//
// Time.h
//
// Library: Data
// Package: DataCore
// Module: Time
//
// Definition of the Time class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_Time_INCLUDED
#define Data_Time_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Dynamic/VarHolder.h"
#include "Poco/Exception.h"
namespace Poco {
namespace Dynamic {
class Var;
}
class DateTime;
namespace Data {
class Date;
class Data_API Time
/// Time class wraps a DateTime and exposes time related interface.
/// The purpose of this class is binding/extraction support for time fields.
{
public:
Time();
/// Creates the Time
Time(int hour, int minute, int second);
/// Creates the Time
Time(const DateTime& dt);
/// Creates the Time from DateTime
~Time();
/// Destroys the Time.
int hour() const;
/// Returns the hour.
int minute() const;
/// Returns the minute.
int second() const;
/// Returns the second.
void assign(int hour, int minute, int second);
/// Assigns time.
Time& operator = (const Time& t);
/// Assignment operator for Time.
Time& operator = (const DateTime& dt);
/// Assignment operator for DateTime.
Time& operator = (const Poco::Dynamic::Var& var);
/// Assignment operator for Var.
bool operator == (const Time& time) const;
/// Equality operator.
bool operator != (const Time& time) const;
/// Inequality operator.
bool operator < (const Time& time) const;
/// Less then operator.
bool operator > (const Time& time) const;
/// Greater then operator.
private:
int _hour;
int _minute;
int _second;
};
//
// inlines
//
inline int Time::hour() const
{
return _hour;
}
inline int Time::minute() const
{
return _minute;
}
inline int Time::second() const
{
return _second;
}
inline Time& Time::operator = (const Time& t)
{
assign(t.hour(), t.minute(), t.second());
return *this;
}
inline Time& Time::operator = (const DateTime& dt)
{
assign(dt.hour(), dt.minute(), dt.second());
return *this;
}
inline bool Time::operator == (const Time& time) const
{
return _hour == time.hour() &&
_minute == time.minute() &&
_second == time.second();
}
inline bool Time::operator != (const Time& time) const
{
return !(*this == time);
}
inline bool Time::operator > (const Time& time) const
{
return !(*this == time) && !(*this < time);
}
} } // namespace Poco::Data
//
// VarHolderImpl<Time>
//
namespace Poco {
namespace Dynamic {
template <>
class VarHolderImpl<Poco::Data::Time>: public VarHolder
{
public:
VarHolderImpl(const Poco::Data::Time& val): _val(val)
{
}
~VarHolderImpl()
{
}
const std::type_info& type() const
{
return typeid(Poco::Data::Time);
}
void convert(Poco::Timestamp& val) const
{
Poco::DateTime dt;
dt.assign(dt.year(), dt.month(), dt.day(), _val.hour(), _val.minute(), _val.second());
val = dt.timestamp();
}
void convert(Poco::DateTime& val) const
{
Poco::DateTime dt;
dt.assign(dt.year(), dt.month(), dt.day(), _val.hour(), _val.minute(), _val.second());
val = dt;
}
void convert(Poco::LocalDateTime& val) const
{
Poco::LocalDateTime ldt;
ldt.assign(ldt.year(), ldt.month(), ldt.day(), _val.hour(), _val.minute(), _val.second());
val = ldt;
}
void convert(std::string& val) const
{
DateTime dt(0, 1, 1, _val.hour(), _val.minute(), _val.second());
val = DateTimeFormatter::format(dt, "%H:%M:%S");
}
VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const
{
return cloneHolder(pVarHolder, _val);
}
const Poco::Data::Time& value() const
{
return _val;
}
private:
VarHolderImpl();
Poco::Data::Time _val;
};
} } // namespace Poco::Dynamic
#endif // Data_Time_INCLUDED

View File

@ -0,0 +1,194 @@
//
// Transaction.h
//
// Library: Data
// Package: DataCore
// Module: Transaction
//
// Definition of the Transaction class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_Transaction_INCLUDED
#define Data_Transaction_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/Session.h"
#include "Poco/Logger.h"
namespace Poco {
namespace Data {
class Data_API Transaction
/// Transaction helps with transactions in domain logic.
/// When an Transaction object is created, it first checks whether a
/// transaction is in progress. If not, a new transaction is created.
/// When the Transaction is destroyed, and commit() has been called,
/// nothing is done. Otherwise, the current transaction is rolled back.
/// See Transaction for more details and purpose of this template.
{
public:
Transaction(Poco::Data::Session& session, Poco::Logger* pLogger = 0);
/// Creates the Transaction and starts it, using the given database session and logger.
Transaction(Poco::Data::Session& session, bool start);
/// Creates the Transaction, using the given database session.
/// If start is true, transaction is started, otherwise begin() must be called
/// to start the transaction.
template <typename T>
Transaction(Poco::Data::Session& rSession, T& t, Poco::Logger* pLogger = 0):
_rSession(rSession),
_pLogger(pLogger)
/// Creates the Transaction, using the given database session, transactor and logger.
/// The transactor type must provide operator () overload taking non-const Session
/// reference as an argument.
///
/// When transaction is created using this constructor, it is executed and
/// commited automatically. If no error occurs, rollback is disabled and does
/// not occur at destruction time. If an error occurs resulting in exception being
/// thrown, the transaction is rolled back and exception propagated to calling code.
///
/// Example usage:
///
/// struct Transactor
/// {
/// void operator () (Session& session) const
/// {
/// // do something ...
/// }
/// };
///
/// Transactor tr;
/// Transaction tn(session, tr);
{
try { transact(t); }
catch (...)
{
if (_pLogger) _pLogger->error("Error executing transaction.");
rollback();
throw;
}
}
~Transaction();
/// Destroys the Transaction.
/// Rolls back the current database transaction if it has not been commited
/// (by calling commit()), or rolled back (by calling rollback()).
///
/// If an exception is thrown during rollback, the exception is logged
/// and no further action is taken.
void setIsolation(Poco::UInt32 ti);
/// Sets the transaction isolation level.
Poco::UInt32 getIsolation();
/// Returns the transaction isolation level.
bool hasIsolation(Poco::UInt32 ti);
/// Returns true iff the transaction isolation level corresponding
/// to the supplied bitmask is supported.
bool isIsolation(Poco::UInt32 ti);
/// Returns true iff the transaction isolation level corresponds
/// to the supplied bitmask.
void execute(const std::string& sql, bool doCommit = true);
/// Executes and, if doCommit is true, commits the transaction.
/// Passing true value for commit disables rollback during destruction
/// of this Transaction object.
void execute(const std::vector<std::string>& sql);
/// Executes all the SQL statements supplied in the vector and, after the last
/// one is sucesfully executed, commits the transaction.
/// If an error occurs during execution, transaction is rolled back.
/// Passing true value for commit disables rollback during destruction
/// of this Transaction object.
template <typename T>
void transact(T& t)
/// Executes the transactor and, unless transactor throws an exception,
/// commits the transaction.
{
if (!isActive()) begin();
t(_rSession);
commit();
}
void commit();
/// Commits the current transaction.
void rollback();
/// Rolls back the current transaction.
bool isActive();
/// Returns false after the transaction has been committed or rolled back,
/// true if the transaction is ongoing.
void setLogger(Poco::Logger* pLogger);
/// Sets the logger for this transaction.
/// Transaction does not take the ownership of the pointer.
private:
Transaction();
Transaction(const Transaction&);
Transaction& operator = (const Transaction&);
void begin();
/// Begins the transaction if the session is already not in transaction.
/// Otherwise does nothing.
Session _rSession;
Logger* _pLogger;
};
inline bool Transaction::isActive()
{
return _rSession.isTransaction();
}
inline void Transaction::setIsolation(Poco::UInt32 ti)
{
_rSession.setTransactionIsolation(ti);
}
inline Poco::UInt32 Transaction::getIsolation()
{
return _rSession.getTransactionIsolation();
}
inline bool Transaction::hasIsolation(Poco::UInt32 ti)
{
return _rSession.isTransactionIsolation(ti);
}
inline bool Transaction::isIsolation(Poco::UInt32 ti)
{
return _rSession.isTransactionIsolation(ti);
}
inline void Transaction::setLogger(Poco::Logger* pLogger)
{
_pLogger = pLogger;
}
} } // namespace Poco::Data
#endif // Data_Transaction_INCLUDED

File diff suppressed because it is too large Load Diff